diff --git a/.agents/notes/README.i18n.yaml b/.agents/notes/README.i18n.yaml new file mode 100644 index 0000000000..fa9c0d9a21 --- /dev/null +++ b/.agents/notes/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 4db9f16956b9c569cf5f9b53f04cb650f6058668 +README.zh.md: 60ec5421e7f271460daebc966aa6548f6ef8a511 diff --git a/.agents/notes/README.md b/.agents/notes/README.md index e62dc18954..4db9f16956 100644 --- a/.agents/notes/README.md +++ b/.agents/notes/README.md @@ -1,5 +1,7 @@ # Agent Notes +English | [中文](README.zh.md) + One kind of design doc lives here. An **Agent Note** records a decision or proposal that shapes this codebase — the *why* and *what we gave up*, the parts code and docs can't carry. This file is the front door and contract: where Agent Notes live, when to write one, and [the in-file format](#the-file-format). ## Layout and naming diff --git a/.agents/notes/README.zh.md b/.agents/notes/README.zh.md new file mode 100644 index 0000000000..60ec5421e7 --- /dev/null +++ b/.agents/notes/README.zh.md @@ -0,0 +1,117 @@ +# Agent Notes + +[English](README.md) | 中文 + +这里存放一类设计文档。**Agent Note(agent 决策记录)** 记录塑造本代码库的决策或提案:代码和文档无法承载的*为什么*以及*放弃了什么*。本文件是入口和契约:Agent Note 存放在哪里、何时需要写一份,以及[文件内格式](#the-file-format)。 + +## 布局与命名 + +每份 Agent Note 有两个维度,都编码在其**路径**中:`{lifecycle}/{class}/yyyy-mm-dd-topic-title.md`。 + +- **生命周期**(顶层文件夹)是 Agent Note 的状态,Agent Note 随状态变化在文件夹之间移动: + - **`proposed/`**:实施前评审的提案;尚未构建(或仅部分构建)。 + - **`implemented/`**:决策已交付。文件记录做了什么决定、否决了什么,并**与实际交付的内容保持同步**:当代码后续移动文件、重命名包(package)或更改键名/默认值时,Agent Note 在同一个变更中同步更新(仅限事实——路径、名称、结构——而非决策本身)。见 [implemented/AGENTS.md](implemented/AGENTS.md)。 + - **`rejected/`**:提案经过讨论后被否决。保留以备查阅,避免同一问题被反复争论。 +- **类别**(嵌套文件夹)是决策的*种类*——见下方[分类](#classification)。 + +文件名中的日期是该主题**首次提出**的时间(以 git 历史为准)。Agent Note 之间的交叉引用使用相对 Markdown 链接(`[topic](../../implemented/architecture/2026-…-….md)`),从不使用纯文字或编号,这样既可机械检查,也能在文件夹间移动时保持有效。 + +目录树就是清单:浏览其生命周期/类别文件夹,或搜索仓库即可。请勿添加集中式 `INDEX.md`;设计理由见[不设索引的 Agent Note](implemented/process/2026-07-19-remove-generated-agent-note-index.md)。 + + + +## 分类 + +每份 Agent Note 属于 `scripts/agent-note-tree.ts` 中封闭集合里的一个路径编码类别;分类门禁拒绝其他文件夹。新增类别需要同时更新规范集合与本节。见[分类 Agent Note](implemented/process/2026-06-20-agent-note-classification.md)。 + +| 类别 | 覆盖范围 | +|---|---| +| `feature` | 面向用户或模型的新功能。 | +| `bug-fix` | 修正缺陷或弥补事故复盘(postmortem)发现的缺口。 | +| `simplification` | 在不增加功能的前提下移除代码、行为或对外表面积。 | +| `architecture` | 关于**交付源码**的结构性决策:包之间的关系、运行时词汇。 | +| `process` | 代码**周边**的工具、策略或工作流——门禁、包管理器、vendor 化——不涉及运行时行为。 | +| `testing` | 测试基础设施与策略。 | + +`architecture` 与 `process` 的界线:**architecture** 关乎我们交付的源码;**process** 关乎围绕源码的工具与工作流。(`refactor` 被有意排除:它与 `simplification` 重叠,而后者的判别标准「可观察行为是否改变」已经覆盖了它。) + +## 何时需要写一份 + +每个非平凡变更都必须在同一 PR(Pull Request)中新增或更新至少一份 Agent Note。如果变更修改了行为、架构、跨文件或跨包契约、流程或工具、测试策略、磁盘、协议或配置格式,或者其他维护者可能合理重新审视的决策,就属于非平凡变更。对未来重大工作的提案从 `proposed/` 开始;已经做出的决策从 `implemented/` 开始。选择与决策匹配的类别文件夹(见[分类](#classification))。 + +更新已经拥有该决策的 Agent Note 即可满足规则;不要创建重复记录。只有不涉及行为、契约、结构、流程或理由变化的纯机械性或局部编辑才可豁免。Agent Note 永远不会被编辑为一个*不同的决策*:用新 Agent Note 取代旧的,并互相链接。编辑 `implemented/` Agent Note 以跟踪其现有决策的所在位置是必需的,而非禁止的;见 [implemented/AGENTS.md](implemented/AGENTS.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)。 + +### 头部块 + +每份 Agent Note 的前三行严格为: + +```markdown +# Agent Note: + +Status: <status> +``` + +后跟一个空行。`Status:` 的值有三种形式,且必须与文件所在的生命周期文件夹一致——门禁会交叉检查: + +- `Status: proposed` +- `Status: implemented` +- `Status: rejected — <why, in one line>` + +状态行不带日期、不带括号补充说明:文件名记录首次提出日期,git 记录其余一切;「以修订形式接受」之类的说明属于正文内容(在陈述决策的地方说明修订)。拒绝原因是唯一带内容的状态,因为读者查阅被否决的 Agent Note 时,结论正是他们要找的。 + +### 正文骨架 + +每份 Agent Note 的正文以 `## Problem` 开头:动机,写法上不依赖解决方案即可独立成文。后续内容取决于生命周期;固定章节使用以下规范名称且仅限这些名称,而真正独特的技术章节(包拓扑、协议契约、schema 等)在必需章节之间可自由组织。 + +#### `proposed/` + +```markdown +## Problem +## Proposal +…bespoke sections… +## Alternatives considered +## Acceptance criteria +## Risks +``` + +`## Proposal` 描述拟议的变更,可以合理地使用将来时态——计划、迁移步骤和待解决问题在工作尚未完成时属于此处。`## Acceptance criteria` 说明什么可观察状态意味着完成。`## Risks` 涵盖可能出错的事项以及该变更有意放弃的东西。 + +#### `implemented/` + +```markdown +## Problem +## Decision +…bespoke sections… +## Alternatives considered +## Consequences +``` + +`## 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/` + +被否决的 Agent Note 是冻结的提案:保留提案时的所有章节(包括 `## Acceptance criteria` 或 `## Plan`),结论写在 `Status:` 行上。仅头部块、`## Problem` 开头、`## Proposal` 章节以及下方的「曾考虑的替代方案」强制要求适用。 + +### 曾考虑的替代方案——必需 + +每份 Agent Note 都必须包含 `## Alternatives considered` 章节:每个真实的替代方案及其落选原因,每个替代方案用一个加粗引导的段落,或对争议较大的替代方案用 `### Why not <X>?` 子节。记录决策时不记录它击败了什么,就是在邀请反复争论——正是这些 Agent Note 存在的意义所要防止的。 + +替代方案是记录下来的,不是凭空编造的。日期早于 2026-07-05 且替代方案无法从记录中重建的 Agent Note,在该章节位置放置以下精确注释,门禁仅对格式规范之前的文件接受此注释: + +```markdown +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> +``` + +### 在生命周期之间移动 + +将文件在生命周期文件夹之间移动意味着在同一个变更中更新 `Status:` 行并满足目标文件夹的骨架要求——否则门禁会失败。具体而言,`proposed/` → `implemented/` 将 `## Proposal` 改写为现在时态的 `## Decision`,将 `## Acceptance criteria` 和 `## Risks` 折入 `## Consequences`(或折入一个现在时态的 `## Testing`/`## Verification` 章节,用于描述现在锁定该行为的内容),并用实际交付的内容替换计划——即 [implemented/AGENTS.md](implemented/AGENTS.md) 所要求的改写,使之机械化。`proposed/` → `rejected/` 仅在 `Status:` 行添加原因并冻结文件。 + +### 中文对侧文件 + +`.zh.md` 对侧文件按 [i18n 契约](../../docs/i18n/README.md)逐章节镜像其英文兄弟文件的结构;机器检查的头部标记(`# Agent Note: ` 和 `Status:` 行)保持英文原样不翻译。格式门禁跳过 `.zh.md` 文件——配对门禁负责它们的一致性。 diff --git a/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.i18n.yaml new file mode 100644 index 0000000000..01823c55d0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-content-block-vocabulary.md: 9aad01cee6083b1f380be66869af3137a07d9f1f +2026-06-11-content-block-vocabulary.zh.md: 5720f0742a0729a3f98e4b05ab37acf97ae78db5 diff --git a/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.md b/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.md index 1133b990c3..9aad01cee6 100644 --- a/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.md +++ b/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-content-block-vocabulary.zh.md) + ## Problem The harness needs one internal language for messages that the loop, session log, and all plugins speak. diff --git a/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.zh.md b/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.zh.md new file mode 100644 index 0000000000..5720f0742a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.zh.md @@ -0,0 +1,28 @@ +# Agent Note: 由 dsh-llm 拥有的提供方无关内容块词汇 + +Status: implemented + +[English](2026-06-11-content-block-vocabulary.md) | 中文 + +## 问题 + +harness 需要一套统一的内部消息语言,供 agent loop(智能体循环)、会话日志和所有插件共同使用。 + +## 决策 + +自主拥有词汇:消息是类型化内容块的数组(`text`、`reasoning`、`tool-call`、`tool-result`),其联合类型派生自可合并扩展的 `ContentBlockMap`,插件通过声明合并添加新的块类型。同一可合并扩展映射模式为所有「字符串化」字段提供类型(`MessageSource`、`FinishReason`、`TurnTrigger`、`TurnEndReason`)。流式输出采用原始分片协议;`BlockAssembler` 是唯一的共享组装实现。适配器负责转换为提供方的协议格式(wire format)——映射成本留在适配器中,正是它该在的地方。 + +会话内上下文注入(`context/message`)和轮次中途 steering(`steering/message`)最初渲染为带标签的 user-role 信封(system-reminder 模式),而非引入新角色,因此适配器无需承担额外负担。如今两者都投影为无包装的普通用户内容;见[注入内容信封 Agent Note](../simplification/2026-07-20-unwrap-injected-content-envelopes.md)。实际适配器验证已确认此渲染方式符合当前 DeepSeek 的行为;如果未来某提供方出现不兼容,应在该适配器内处理,而非引入新的规范角色。 + +## 曾考虑的替代方案 + +- **镜像 DeepSeek/OpenAI chat-completions 结构**:对第一个提供方零映射成本,但对富内容(推理、结构化块形式的工具结果)处理不便。 +- **原样采用 Anthropic Messages 块结构**:经过实战检验,但规范类型将镜像一个 harness 并非首要对接的第三方 API。 + +## 后果 + +- 推理(reasoning)在核心层有了归属,无需依赖提供方特有的结构。 +- 多模态块只有在适配器、UI 和上下文压缩(context compaction)三方协同支持后才会回归;见 [drop-image Agent Note](../simplification/2026-07-04-drop-image-content-block.md)。 +- 缓存提示与 assistant prefill 在有实际适配器能兑现之前保持缺席;见[无生产者的词汇变体](../simplification/2026-07-04-prune-producerless-vocabulary-variants.md)与[无端到端可用路径的请求旋钮](../simplification/2026-07-04-drop-inert-request-knobs.md) Agent Note。 +- 每个适配器都需承担翻译成本;首批真实适配器已验证了流式输出协议,新适配器应继续在适配器本地测试中验证其提供方特有的映射。 +- 跨包(package)边界的 ID 使用品牌类型(`CallId`、agent 与会话共享的 `SessionId`)——零运行时开销的名义类型。 diff --git a/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.i18n.yaml new file mode 100644 index 0000000000..41265a5b0f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-custom-schema-dsl.md: 947d53555df078bfa9f3dac48eab4b8c0074007c +2026-06-11-custom-schema-dsl.zh.md: 26ebfe2fb15a6c034e809b3f51187342fa500193 diff --git a/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.md b/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.md index 41b72f1551..947d53555d 100644 --- a/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.md +++ b/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-custom-schema-dsl.zh.md) + ## Problem Tool parameters must reach the model as standard JSON Schema while giving tool authors typed `execute(args)` without casts. Schemastery already serves plugin config, but the tool-author API needs per-property `required: true` booleans rather than JSON Schema's separate `required` array. diff --git a/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.zh.md b/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.zh.md new file mode 100644 index 0000000000..26ebfe2fb1 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.zh.md @@ -0,0 +1,23 @@ +# Agent Note: 使用自定义类型化工具 schema DSL 替代 schemastery + +Status: implemented + +[English](2026-06-11-custom-schema-dsl.md) | 中文 + +## 问题 + +工具参数必须以标准 JSON Schema 形式到达模型,同时让工具作者在 `execute(args)` 中获得类型化的参数而无需类型断言。Schemastery 已用于插件配置,但工具作者 API 需要逐属性的 `required: true` 布尔值,而非 JSON Schema 的独立 `required` 数组。 + +## 决策 + +该决策已由[统一 JSON 值 schema DSL](2026-07-20-unified-json-value-schema-dsl.md)取代;新设计保留小型编写接口,同时让参数与类型化值共享一套词汇。`ParameterSchemaSpec` 保留逐属性的 `required: true`;`InferArgs<S>` 将必需键映射为非可选属性;`parameterSchemaSpecToJsonSchema()` 编译隐式开放的对象根;`defineTool()` 则将类型推导、编译与校验串联起来。原始 JSON Schema 的 `ToolDefinition` 仍是 `ToolRegistry.register()` 接受的输入,供 MCP 和其他外部工具使用。 + +## 曾考虑的替代方案 + +**Schemastery**(已作为 vendor 引入,用于插件 Config)经评估后被否决:它面向的是基于 StandardSchema 的校验/转换,而非 JSON Schema *生成*,因此会增加间接层却无法干净地产出协议格式(wire format)。 + +## 后果 + +- 第一方工具作者获得零类型断言的类型化参数;类型体操的成本留在核心包内部(符合 AGENTS.md 的类型安全策略)。 +- 当前节点、字面量约束、联合类型、JSON 值边界与对象开放性规则均由上述统一说明定义。 +- `InferArgs` 映射在类型层面有回归测试,源于早期一个可选性 bug。 diff --git a/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.i18n.yaml new file mode 100644 index 0000000000..c6ddb39d01 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-dev-invariants-over-deep-readonly.md: 8f0e79f15af82ce3125b1f6f767d4ea727aa6d29 +2026-06-11-dev-invariants-over-deep-readonly.zh.md: 2f787bbd55b5a9a91bc5342351756e45cb0515d3 diff --git a/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md b/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md index fb1dc93159..8f0e79f15a 100644 --- a/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md +++ b/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-dev-invariants-over-deep-readonly.zh.md) + ## Problem The session log needs two different protections: immutable ownership of each stored fact, and checks for relationships among facts across time and service seams. Conflating them in an optional development plugin would leave production history vulnerable; trying to express both through TypeScript readonly types would not create a runtime boundary or describe relational rules. diff --git a/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.zh.md b/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.zh.md new file mode 100644 index 0000000000..2f787bbd55 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.zh.md @@ -0,0 +1,60 @@ +# Agent Note: 源端拥有的会话不可变性与开发模式不变式 + +Status: implemented + +[English](2026-06-11-dev-invariants-over-deep-readonly.md) | 中文 + +## 问题 + +会话日志需要两种不同的保护:对每条已存储事实的不可变所有权,以及对跨时间和服务 seam 的事实之间关系的检查。如果将二者混为一个可选的开发插件,生产环境的历史记录将失去保护;如果试图通过 TypeScript readonly 类型同时表达两者,既无法建立运行时边界,也无法描述关系规则。 + +会话日志是回放、请求重建、持久化与用户可见历史的持久真源。会话包(package)外部的代码必须能检视历史,但不能保留一个可在之后改写历史的引用;从调用方接受的输入也不能继续连接到调用方拥有的可变对象。 + +单个值的不可变性只是契约的一半。一份日志可以包含完全不可变的记录,但其序列、轮次/步骤嵌套、工具调用配对、作用域分发或重建的模型请求是错误的。这些规则涉及多条记录或多个服务,无法通过冻结单个对象来建立。 + +TypeScript readonly 类型不是充分的运行时边界。它们在程序运行时消失,类型转换可以绕过它们,而递归的 `DeepReadonly<T>` 会扩散到每个日志和消息消费方,尽管某些下游请求处理 API 有意使用可变值。 + +## 决策 + +职责在始终启用的存储边界与可选的开发断言之间分离。 + +### Session 拥有不可变历史 + +`Session` 仅在一次递归遍历完成无损 JSON 快照的物化之后才接受事件。该遍历拒绝不支持的值,并产出进入日志的确切分离记录,因此验证与存储不会从有状态的 getter 观察到不同的值,也不会保留调用方拥有的嵌套引用。 + +被接受的事件及其所有后代在发布前被深度冻结。`append()` 返回该拥有的冻结事件,`session/event` 观察者接收同一记录,`session.events` 返回冻结的数组快照。先前返回的数组不会因后续 append 而增长。种子记录在构造成功前经过相同的验证、快照与冻结边界。 + +此保证属于 `Session` 而非可选监听器,因为每种组合都依赖可信的历史。无论是否注册了开发支持插件,生产部署、聚焦测试或自定义嵌入都获得相同的存储语义。 + +### 派生请求保持分离 + +`deriveMessages()` 将已记录的表面事件投影为分离的、深度冻结的 `Message` 对象,并返回一份新的数组快照。因此请求组装可以将派生历史与其他输入组合,而不会暴露一条回到日志的路径。缓存复用安全的不可变投影,而非为每次模型调用重新克隆完整历史。 + +### 包拥有的不变式配套插件检查关系 + +`dsh-invariants` 注册可配置的 `ctx.invariants` 服务,本身不包含产品检查。每个包发布一个 `./invariant` 所有权配套插件;`dsh-session`、`dsh-agent`、`dsh-scope` 和 `dsh-agent-loop` 目前添加需要 trace 状态或观察另一个 seam 的规则:单调递增的序列号、轮次与步骤嵌套、工具调用/结果配对、合法的 agent(智能体)状态转换、主体正确的作用域分发,以及循环构建的请求与从其会话日志前缀重建的请求之间的等价性。全局启用和包名 regex 过滤器归该服务所有(见[包拥有的不变式服务](2026-07-19-package-owned-invariant-service.md))。 + +当会话配套插件附加到已有或已播种的会话时,它回放不可变日志以重建跟踪状态。服务为每项贡献提供一个可 dispose(资源释放)的子 fiber,因此轮次中途热重载是安全的,同时不赋予诊断逻辑对会话存储的所有权。 + +## 曾考虑的替代方案 + +### 全面的 deep-readonly 类型 + +[被否决的不可变公共表面提案](../../rejected/architecture/2026-06-11-immutable-public-surfaces.md)会在公共日志和消息表面上应用递归 readonly 类型。这能提供编辑器反馈,但无法提供运行时保证:TypeScript 类型在运行时被擦除,插件代码可以通过类型转换绕过。它还会将 readonly 类型推入有意进行修改的消费方。在 `Session` 边界处的运行时所有权保护所有调用方,无需这种类型传播。 + +### 仅在开发模式冻结 + +仅当不变式插件安装时才冻结历史,会使核心保证依赖于组合方式。代码可能通过开发测试,却在生产环境或省略了该插件的聚焦组合中破坏历史。因此存储不可变性始终启用,而开销更大的关系检查则保持为可选的开发支持。 + +### 仅在派生消息时克隆 + +分离 `deriveMessages()` 能保护最常见的请求路径,但 `session.events` 的其他读取者、append 返回值和会话事件观察者仍能修改持久历史。日志必须保护自身的边界;派生投影是额外的隔离边界,而非替代品。 + +## 后果 + +- 每个被接受的实时或种子会话事件在任何观察者接收之前,都已从调用方拥有的输入中分离并深度不可变。 +- `session.events` 暴露稳定的不可变快照,而非私有的增长数组。 +- 请求侧的修改无法通过派生消息触及已存储的历史。 +- 开发构建可以启用关系断言而不改变存储行为;dispose 或过滤一个配套插件不会削弱日志不可变性。 +- `dsh-invariants` 配置全局启用状态以及包允许/阻止 regex 列表;每项检查仍由其产品包拥有并测试。 +- 运行时边界对每个被接受的事件产生一次递归快照与冻结的开销;后续读取者和缓存投影复用已拥有的不可变记录。 diff --git a/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.i18n.yaml new file mode 100644 index 0000000000..6ea6fce11e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-event-sourced-sessions.md: 15ba7b23d5eae48e7dee2328b5924493d54aeeb0 +2026-06-11-event-sourced-sessions.zh.md: da3be5965a6900076f253cad065b847c6f5ce17e diff --git a/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.md b/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.md index bab36ee783..15ba7b23d5 100644 --- a/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.md +++ b/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-event-sourced-sessions.zh.md) + ## Problem The MVP requires strict event-based tracing with fully replayable sessions (严格的基于事件的trace、logging系统,session完全可回放). diff --git a/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.zh.md b/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.zh.md new file mode 100644 index 0000000000..da3be5965a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.zh.md @@ -0,0 +1,28 @@ +# Agent Note: 事件溯源的会话与派生消息历史 + +Status: implemented + +[English](2026-06-11-event-sourced-sessions.md) | 中文 + +## 问题 + +MVP 要求严格的基于事件的追踪,以及完全可回放的会话(严格的基于事件的 trace、logging 系统,会话完全可回放)。 + +## 决策 + +`Session` 是一份仅追加的、类型化的 `SessionEvent` 日志,是唯一的真源。LLM(大语言模型)消息历史从日志*派生*(`deriveMessages()`);原始流分片被记录以保证 token 级别的回放保真度,而组装后的 `assistant/message` 事件才是派生的权威依据。回放/fork = 用已有日志初始化一个新会话。 + +追加操作是同步的(热路径从不阻塞于 I/O);`session/event` 是同步通知;持久化插件在后台缓冲写入,并在每个轮次结束时触发的 `session/flush` 检查点处等待排空。 + +顺序契约:agent loop(智能体循环)*先*追加到会话,再发出对应的 Cordis 事件;`agent/step-result` waterfall(瀑布式事件)在 `assistant/message` 追加之前运行,因此日志记录的是工具调度实际使用的消息。回归测试固定了这一顺序。 + +## 曾考虑的替代方案 + +**可变消息数组 + 事件仅作通知发出**:更简单,但状态与日志可能分歧;采用事件溯源后,日志本身即是状态,分歧在结构上不可能发生。 + +## 后果 + +- 回放、追踪与遥测在结构上得到保证,而非事后附加。 +- 持久化仍是插件关注点;内存存储随 dsh-session 一起提供。 +- 事件词汇可通过合并扩展(插件可添加如压缩(compaction)事件);[会话持久化](2026-06-14-session-persistence.md)在日志变为持久后冻结了其形状。 +- 派生成本随日志长度增长,压缩(未来插件)是预期的缓解手段,而非日志变更。 diff --git a/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.i18n.yaml new file mode 100644 index 0000000000..a15ebcfddf --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-microkernel-event-taxonomy.md: 8bf05b7deba5f054d4ec8ecf104c3b8798e42d4e +2026-06-11-microkernel-event-taxonomy.zh.md: 4ff2ab632ca02e98137a15f19a7996a740a519b0 diff --git a/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.md b/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.md index abdadb447b..8bf05b7deb 100644 --- a/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.md +++ b/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-microkernel-event-taxonomy.zh.md) + ## Problem The product principle is "everything is a plugin": hooks, /goal, /loop, dynamic workflows, compaction, sandboxing, permissions, UI, persistence, MCP, skills must all be writable as plugins without modifying the core. diff --git a/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.zh.md b/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.zh.md new file mode 100644 index 0000000000..4ff2ab632c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 微内核——通过 Cordis 事件分类体系实现扩展,唯一具体循环 + +Status: implemented + +[English](2026-06-11-microkernel-event-taxonomy.md) | 中文 + +## 问题 + +产品原则是「一切皆插件」:钩子、/goal、/loop、动态工作流、上下文压缩(context compaction)、沙箱、权限、UI、持久化、MCP、skill(技能)都必须能以插件形式编写,无需修改核心。 + +## 决策 + +纯 Cordis 事件分类体系。agent loop(智能体循环)的扩展 seam 是带类型的事件,具有明确的分发模式: + +- **waterfall(瀑布式事件)**(around-middleware):插件可变换、否决、恢复或包装:`agent/prompt-submit`、`agent/request`、`agent/request-error`、`agent/step-result`、`agent/turn-continuation`、`tools/pre-execute`、`tools/execute`、`tools/post-execute`、`llm/stream`、`system-prompt/assemble`。 +- **serial**(按监听器顺序依次 await;bail 值会阻止后续监听器执行):用于有序检查点。所有 `agent/pre-step` 和 `agent/post-step` 监听器在全部弃权时才继续运行,而 `agent/turn-stop` 返回的第一个 stop 值即为最终的终止决策。 +- **parallel**(await 扇出):每个监听器都必须获得独立执行的机会:`session/flush` 持久性检查点。 +- **emit**(同步 fire-and-forget):用于通知:轮次/步骤边界、流分片、生命周期、错误,以及包含不可变 `tools/result` 观测的事件。 + +事件词汇定义在接口包中(dsh-agent 声明 agent/* 事件);`@deepseek-ai/dsh-agent-loop` 是唯一的具体循环插件,且自身可替换——外部不得依赖它。 + +## 曾考虑的替代方案 + +**专用中间件栈(koa-compose 风格)** 与**显式阶段状态机(插件向其中插入阶段)**:两者都需要重新实现 Cordis 原生事件系统已提供的分发、dispose(资源释放)与重载语义;作为 Cordis effect,监听器天然获得 HMR(热模块替换)与 dispose 能力。 + +## 后果 + +- 每个 MVP 功能都映射到一个监听器([功能→机制映射](../../../../docs/cookbook/extension-cookbook.md#the-feature--mechanism-map)是证明义务,保持更新)。 +- HMR 与 dispose 无需额外工作:监听器和注册均为 Cordis effect。 +- waterfall 语义(调用 `next()` 或短路)不直观,需要教学——在 AGENTS.md 中记录,并由组合测试覆盖。 +- 循环必须具备防御性:插件异常在轮次级别被隔离,任何 seam 发出的 steering(中途引导)永远不会被搁置(有回归测试保障)。 diff --git a/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.i18n.yaml new file mode 100644 index 0000000000..0697332171 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-runtime-arg-validation.md: e0bca0ff24c5adc7ca58007932dff6580694b01d +2026-06-11-runtime-arg-validation.zh.md: 09958147766b4015d6bebf786c4947b9d2941f74 diff --git a/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.md b/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.md index 94b0c6af60..e0bca0ff24 100644 --- a/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.md +++ b/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-runtime-arg-validation.zh.md) + ## Problem `defineTool` ([the unified schema DSL](2026-07-20-unified-json-value-schema-dsl.md)) gives tool authors a typed `execute(args)` via the `InferArgs<S>` mapping. But that type is a compile-time claim about a value that arrives at runtime as model-generated JSON: nothing forced the model to honor the schema, so a malformed call — missing a required key, a string where a number was declared, or a literal outside the declared set — reached `execute` typed-in-name-only. The tool body then either crashed on the bad shape or silently misbehaved. diff --git a/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.zh.md b/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.zh.md new file mode 100644 index 0000000000..0995814776 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.zh.md @@ -0,0 +1,24 @@ +# Agent Note: 模型边界处的运行时参数校验 + +Status: implemented + +[English](2026-06-11-runtime-arg-validation.md) | 中文 + +## 问题 + +`defineTool`([统一 schema DSL](2026-07-20-unified-json-value-schema-dsl.md))为工具作者的 `execute(args)` 提供了经 `InferArgs<S>` 映射的类型化参数。但该类型只是对运行时值的编译期声明,而这个值实际上是模型生成的 JSON:没有任何机制强制模型遵守 schema,因此畸形调用(缺少必需键、声明为数字的位置传入字符串,或字面量超出声明的集合)会以「仅名义类型化」的状态到达 `execute`。工具函数体随后要么在错误形状上崩溃,要么静默地行为异常。 + +## 决策 + +`validateArgs(spec, args): string[]` 编译 `ParameterSchemaSpec`,并委托共享的 `validateJsonSchemaValue()` 遍历器,对格式正确的声明返回可读的违规列表。`defineTool` 在定义时对编译后的参数 schema 创建快照,并在调用类型化函数体之前执行校验;存在违规时会抛出 `ToolArgsError`(`INVALID_ARGS`),注册表将其作为模型可据以修正的错误结果返回。 + +校验器与编译器因此共享完全一致的语义:隐式参数根是开放对象;必需键仅来自 `required: true`;默认值仍是注解;显式嵌套对象遵循其声明的开放性;数组通过 `items` 递归;标量字面量约束保证类型正确;`oneOf` 仅在恰好一个分支匹配时才接受。原始注册的工具自行负责输入校验。 + +## 后果 + +- 模型在自身畸形调用上获得可操作的反馈,而非不透明的崩溃,弥合了 `InferArgs` 的承诺与运行时现实之间的鸿沟。 +- 校验器与 `InferArgs` 必须保持一致;一项[属性测试](../testing/2026-06-11-property-based-testing.md)生成满足 spec 的参数并断言它们通过 `validateArgs`(同时断言定向破坏的参数被拒绝),以机械方式封堵漂移风险。 +- `ToolArgsError` 目前是带 `code` 字段的普通 `Error`;如果日后引入 harness 级别的错误分类体系,它将变为子类,但不影响读取 `.message` 的调用方。 +- 校验开销相对于一次模型调用可忽略不计。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.i18n.yaml new file mode 100644 index 0000000000..ca9d2117ec --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-structured-error-taxonomy.md: 9122193b3d01cf5a4c315e6f7a7218153fd4a60a +2026-06-11-structured-error-taxonomy.zh.md: 56a196ccd10a81b51953887f18e522412cd9463b diff --git a/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.md b/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.md index b2f4ea66b4..9122193b3d 100644 --- a/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.md +++ b/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-structured-error-taxonomy.zh.md) + ## Problem Failures crossed seams as bare strings. A tool error flattened to a text block — name, code, and stack lost — so a future sandbox/retry plugin couldn't tell ENOENT from EACCES, and the model got less actionable feedback than it could. A non-Error throw degraded further: the loop wrapped it in `new Error(String(x))`, dropping any code. And `LlmError` was the only typed error in the system, with no shared base, so there was nothing for a consumer to `instanceof` against generically. diff --git a/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.zh.md b/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.zh.md new file mode 100644 index 0000000000..56a196ccd1 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.zh.md @@ -0,0 +1,26 @@ +# Agent Note: 结构化错误分类体系 + +Status: implemented + +[English](2026-06-11-structured-error-taxonomy.md) | 中文 + +## 问题 + +故障跨越 seam 时只是裸字符串。工具错误被扁平化为一个文本块(name、code 和 stack 全部丢失),导致未来的沙箱/重试插件无法区分 ENOENT 和 EACCES,模型得到的反馈也不如本可以那样具有可操作性。非 Error 的 throw 退化更严重:agent loop(智能体循环)将其包装为 `new Error(String(x))`,丢弃了所有 code。而 `LlmError` 是系统中唯一的类型化错误,没有共享基类,消费方无法对其进行通用的 `instanceof` 判断。 + +## 决策 + +在 `dsh-llm`(叶子包,所有其他包都已依赖它,不引入新的依赖边)中引入一个 `HarnessError extends Error` 基类:稳定的 `code`(与 `message` 分离)、通过 `ErrorOptions` 进行 `cause` 链接、`name` 默认为子类名。`isHarnessError` 在 seam 处做类型收窄。 + +- `LlmError` 和 `ToolArgsError`(dsh-tools)继承该基类,保留各自既有的 code。 +- `ToolExecutionResult` 新增可选字段 `error: { name, code }`,在注册表的 catch 中当抛出值为 `HarnessError` 时填充。agent loop 将其转发到 `tool/result` 会话事件(该事件也新增了同一可选字段),使结构化的失败信息存活到日志中,供重试/沙箱插件和回放使用。面向模型的文本块保持不变。 +- agent loop 的 `toError` 将非 Error 的 throw 包装为 `HarnessError`(`code: 'UNKNOWN'`,原始值作为 `cause` 链接),而非裸 `Error`;这样即使是不规范的 throw 也能携带可路由的 code 进入会话的 `error` 事件(该事件此前已暴露 `code`)。 + +## 后果 + +- 错误端到端可机器路由:插件可以基于 `error.code` 分支,而无需对消息做子串匹配。 +- 一个基类被广泛导入,但它位于所有包已经依赖的包中,代价仅是一条 import 语句,而非新的依赖边。 +- `deriveMessages` 不会将 `error` 暴露到模型历史中——模型仍然看到文本块;结构化字段服务于代码和回放。 +- 参数校验保留其既有的 code 和行为;包自有的诊断不变式独立携带稳定 code,使不变式注册表无需导入产品包。共享基类增加了跨 seam 的路由元数据,不改变面向模型的文本。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.i18n.yaml new file mode 100644 index 0000000000..61ecb29ca3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-tool-schemas-in-prompt-assembly.md: 3643ac3d61be08f629ef0cd0424fef5cb9696c3a +2026-06-11-tool-schemas-in-prompt-assembly.zh.md: 10389fd7c63755e5b00b3c508fd303a541287f2c diff --git a/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.md b/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.md index 59ea9117dc..3643ac3d61 100644 --- a/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.md +++ b/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-tool-schemas-in-prompt-assembly.zh.md) + ## Problem On the wire, tool schemas travel in a dedicated `tools` field of the model request, not in prompt text. Architecturally, though, "what the model is told it can do" is one coherent concern: prompt sections and the tool list are assembled from the same plugin contributions and consumed at the same moment. diff --git a/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.zh.md b/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.zh.md new file mode 100644 index 0000000000..10389fd7c6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.zh.md @@ -0,0 +1,23 @@ +# Agent Note: 工具 schema 是系统提示词组装的一部分 + +Status: implemented + +[English](2026-06-11-tool-schemas-in-prompt-assembly.md) | 中文 + +## 问题 + +在协议格式(wire format)层面,工具 schema 通过模型请求中专用的 `tools` 字段传输,而非嵌入提示词文本。然而从架构角度看,「模型被告知它能做什么」是一个统一的关注点:提示词段落与工具列表由相同的插件贡献组装,并在同一时刻被消费。 + +## 决策 + +`PromptAssembly { sections, tools }`:系统提示词服务同时收集有序的文本段落和工具 schema(工具注册表自动贡献一个提供方)。agent loop(智能体循环)每个步骤消费一份 assembly;适配器将 `sections` 映射到提供方的 system 槽位,将 `tools` 映射到协议格式的 `tools` 字段。因此 `system-prompt/assemble` waterfall(瀑布式事件)是模型预先获知的所有信息的唯一拦截点:工具过滤(ToolSearch / 渐进式披露)是一次 assembly 重写,与提示词编辑无异。 + +## 曾考虑的替代方案 + +**循环从工具注册表和提示词服务分别查询**:将一个统一的关注点拆到两个 seam 上;任何想影响「模型被告知什么」的拦截(工具过滤、plan 模式)都需要在两个接口上各挂一个监听器,而非一次 assembly 重写即可完成。 + +## 后果 + +- 一条 waterfall 统管模型的常驻上下文;plan 模式等插件可以在一个监听器中同时替换提示词文本和可见工具。 +- assembly 接口通过声明合并实现可扩展(没有无类型的 `extras` 包——扩展即声明合并),为未来的槽位预留空间。 +- 将 schema 放在「提示词」服务中略有概念上的意外感,已在本文及包 README 中加以说明。 diff --git a/.agents/notes/implemented/architecture/2026-06-13-capability-seams.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-13-capability-seams.i18n.yaml new file mode 100644 index 0000000000..63063f8d5f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-13-capability-seams.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-13-capability-seams.md: 7c755dced7825d2831acc0901f6412b8e5afe95a +2026-06-13-capability-seams.zh.md: 4148c79cb5e1930dca77eaf3afd2024f508275b5 diff --git a/.agents/notes/implemented/architecture/2026-06-13-capability-seams.md b/.agents/notes/implemented/architecture/2026-06-13-capability-seams.md index 5ca299abc0..7c755dced7 100644 --- a/.agents/notes/implemented/architecture/2026-06-13-capability-seams.md +++ b/.agents/notes/implemented/architecture/2026-06-13-capability-seams.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-13-capability-seams.zh.md) + ## Problem The harness has swappable capabilities — bash execution today, sandboxed/remote executors and alternative model providers tomorrow. A capability has three concerns that change at different rates and for different reasons: the *contract* (what the capability is), the *implementation* (how it runs), and the *consumer surface* (what the model and other plugins program against). Bundling them in one package couples those rates of change — swapping a local executor for a sandboxed one would churn the tool schemas the model sees, even though the model-facing contract never changed. diff --git a/.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md b/.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md new file mode 100644 index 0000000000..4148c79cb5 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md @@ -0,0 +1,32 @@ +# Agent Note: 能力 seam——接口/实现/消费方三分 + +Status: implemented + +[English](2026-06-13-capability-seams.md) | 中文 + +## 问题 + +harness 具有可替换的能力:当前是 bash 执行,未来会有沙箱化/远程执行器和替代模型提供方。一项能力涉及三个关注点,它们以不同速率、因不同原因变化:*契约*(这项能力是什么)、*实现*(它如何运行)、*消费方接口*(模型和其他插件面向什么编程)。将三者捆绑在一个包(package)中会耦合这些变化速率——把本地执行器换成沙箱化执行器时,模型看到的工具 schema 也会被搅动,尽管面向模型的契约从未改变。 + +这与「谁在运行时提供、谁需要一项能力」是不同的问题,后者 Cordis 已通过服务 + `inject` 解决(提供方注册 `ctx.bash`;消费方声明 `inject: ['bash']`,其 fiber 挂起直到服务存在)。该机制是必要的,但不决定包的边界;本 Agent Note 决定的是包的边界。 + +## 决策 + +一项可替换的能力由**三个包**构成: + +1. **接口**——一个抽象服务加词汇类型,拥有 `ctx.<key>`,仅依赖其词汇依赖(例如 `dsh-bash`:`BashExecutor`、`BashRunResult`、`BashProcess`)。 +2. **实现**——一个具体子类,以插件形式加载(例如 `dsh-bash-local`:子进程、进程组 kill、溢出文件截断)。沙箱化/远程后端是实现同一接口的兄弟包。 +3. **消费方**——模型和插件看到的内容(例如 `dsh-tool-bash`:`bash` schema,后台句柄注册到通用任务运行时)。消费方 `inject` 接口键,从不导入实现类型。 + +实现与消费方由此独立演进:沙箱化执行器替换 `dsh-bash-local` 时无需触碰任何工具 schema。 + +当各部分确实属于同一个关注点时,三分并非强制:LLM(大语言模型) seam 将接口 + 消费方合并为 `dsh-llm`(消费方是 agent loop(智能体循环)本身,而非可替换的 schema 表面),适配器作为实现包。不要预防性地拆分——如果一项能力只有一种可设想的实现和一个消费方,就保持为一个包,直到第二种出现。 + +## 曾考虑的替代方案 + +- **单一合并包**:否决。因为它重新耦合了三分设计本要分离的三种变化速率(这正是拆分的意义所在)。 +- **`@cordisjs/plugin-capability`**:这是完全不同的维度。它是一个权限/能力*安全*服务(具名权限加继承,通过 `ctx.capability.test` 对会话进行检测),是延后的权限/沙箱工作(`tools/pre-execute` deny/ask seam)的候选方案,不是替换实现的机制。混淆这两个「能力」概念正是本 Agent Note 所指出的陷阱。 + +## 后果 + +每项能力需要更多包和更多样板代码(一组 `package.json`/`tsconfig`/README,加上 inject 接线)。换来的是:实现与消费方独立发布和版本管理,新后端永远不会波及面向模型的契约。该规则记录在 [AGENTS.md](../../../../AGENTS.md) § Conventions(「Capability seams are three packages」)和 [architecture.md](../../../../docs/architecture.md) §「Capability seams」中;bash 三件套是参考模板。何时合并、何时拆分是一个判断问题,架构文档对此有详细说明——本 Agent Note 记录的是*为什么*默认选择拆分。 diff --git a/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.i18n.yaml new file mode 100644 index 0000000000..f1d2fe1a90 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-13-twin-llm-adapters.md: 5c3308b281ce71407002e95dd6e794da2a421fa8 +2026-06-13-twin-llm-adapters.zh.md: 93b084973bccaeb802508e4e939a259c281f2608 diff --git a/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.md b/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.md index 7f2f5933ad..5c3308b281 100644 --- a/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.md +++ b/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-13-twin-llm-adapters.zh.md) + ## Problem `dsh-llm` owns a provider-neutral streaming vocabulary — the `StreamChunk` protocol (`block-start`, `text-delta`, `reasoning-delta`, `tool-call-delta`, `block-end`, `usage`, `finish`) and the content-block types ([the content-block vocabulary](2026-06-11-content-block-vocabulary.md)). A vocabulary defined against a single adapter risks baking that adapter's quirks into the "neutral" contract: anything the one implementation happens to do becomes the de-facto spec, and the abstraction is unverified until a second provider arrives — by which point the leak is expensive to fix. diff --git a/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.zh.md b/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.zh.md new file mode 100644 index 0000000000..93b084973b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.zh.md @@ -0,0 +1,27 @@ +# Agent Note: 以两个 LLM 适配器作为设计验证孪生体 + +Status: implemented + +[English](2026-06-13-twin-llm-adapters.md) | 中文 + +## 问题 + +`dsh-llm` 拥有一套提供方无关的流式词汇:`StreamChunk` 协议(`block-start`、`text-delta`、`reasoning-delta`、`tool-call-delta`、`block-end`、`usage`、`finish`)以及内容块类型([内容块词汇](2026-06-11-content-block-vocabulary.md))。如果词汇仅针对单个适配器定义,就有可能将该适配器的特异行为烘焙进「中立」契约:唯一实现碰巧做了什么,什么就成为事实上的规范;在第二个提供方到来之前,抽象层未经验证——而届时泄漏已代价高昂。 + +## 决策 + +从一开始就针对同一份契约交付**两个**适配器,刻意基于不同的内部实现构建: + +- `dsh-llm-deepseek`:手写 `fetch` + SSE(Server-Sent Events)解析,直接对接 DeepSeek API。 +- `dsh-llm-pi-ai`:通过 `@earendil-works/pi-ai` 库访问同一端点(该库有自己的事件词汇)。 + +二者共同执行的规则是:**凡 StreamChunk 词汇无法为两个实现同时表达的内容,都是核心词汇的缺陷**——立即暴露,而非等到下一个提供方接入时才发现。这对孪生体确定了现已记录在 `dsh-llm/src/types.ts` 中 `StreamChunk` 上的约定:usage 在 finish 之前发出、finish 之后不再有任何事件、工具调用的 `arguments` 全程以原始 JSON 字符串传递,以及消费方必须在两侧都处理的两条合法错误路径(`stream()` 抛异常,*或者*以 `finish {kind:'error'|'aborted'}` 结束)。后一项分歧正是由基于库的适配器暴露出来的,单一手写适配器会将其隐藏。 + +## 曾考虑的替代方案 + +- **单一适配器**:代码更少、e2e 成本减半,但「提供方无关」的声明无从验证;词汇会默默编码 DeepSeek-via-fetch 的假设。 +- **mock 第二适配器**:更便宜,但不会触及真实提供方的协议格式(wire format)怪癖,因此证明力有限。孪生体是真实对真实的验证。 + +## 后果 + +孪生体使适配器和需要密钥的 e2e 维护量翻倍——两者都覆盖 V4 Flash 和 Pro 在各代表性推理(reasoning)模式下的行为——换来的是持续的 seam 中立性验证和第二份实现示例。两个适配器均使用 `apiKey`、`baseURL` 和 `models`;手写适配器暴露 `thinking`/`reasoningEffort`,pi-ai 适配器暴露一个 `reasoning` 级别。未来如果有一致性测试套件,可以通过后续 Agent Note 论证退役其中一个适配器。 diff --git a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.i18n.yaml new file mode 100644 index 0000000000..33a0bce890 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-14-session-persistence.md: 52434930bb662b0c97e61f7c2f69b67c309b6317 +2026-06-14-session-persistence.zh.md: 143b58d32191108d7ba24b489bd4f898b1547aab diff --git a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.md b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.md index 4e105ef598..52434930bb 100644 --- a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.md +++ b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.md @@ -2,9 +2,11 @@ Status: implemented +English | [中文](2026-06-14-session-persistence.zh.md) + ## Problem -Sessions lived only in memory. The example `session-jsonl.ts` plugin (duplicated byte-for-byte in both examples) was write-only telemetry: it buffered `session/event` and appended JSON lines, with no read/replay path, no crash-safety (no fsync, no atomic write, a fire-and-forget dispose drain), no listing, and no format versioning. Nothing could rehydrate a past session from disk into a live agent, so durable resume ("continue yesterday's task"), durable forking, and the ACP `session/load` method ([ACP support](../feature/2026-06-14-acp-agent-client-protocol.md)) were all impossible. +Sessions lived only in memory. The example `session-jsonl.ts` plugin (duplicated byte-for-byte in both examples) was write-only telemetry: it buffered `session/event` and appended JSON lines, with no read/replay path, no crash-safety (no fsync, no atomic write, a fire-and-forget dispose drain), no listing, and no format versioning. Nothing could rehydrate a past session from disk into a live agent, so durable resume, durable forking, and host-side session browsing were all impossible. The [event-sourced model](2026-06-11-event-sourced-sessions.md) makes the append-only log the single source of truth and derives LLM history from it. Persistence had to stay faithful to that: persist the existing `SessionEvent` directly, with no parallel "persisted message" type that the log is converted to and from. The backend also had to be swappable — a file store now, a database store later — behind one interface. @@ -19,16 +21,16 @@ Key choices recorded here because they are durable, contested, and surprising: - **The canonical durable log persists every `SessionEvent` verbatim, including `assistant/chunk`.** `deriveMessages()` skips chunks, and a chunk-filtered rollout (Codex's `policy.rs`) is tempting — but `seq = log.length` and the load-validation `events[i].seq === i` require a *contiguous* log; filtering chunks out would leave holes and break both the contract and resume. A chunk-filtered projection is possible later as a derived view with its own renumbering, but it is NOT the canonical log. - **Append-only; a crashed turn is closed, never truncated.** Flushed events are never rewritten. The [semantic checkpoint policy](../bug-fix/2026-07-21-semantic-session-checkpoints.md) drains the request before model dispatch, a recorded top-level call before tool dispatch, and the complete response/result batch after a step; the loop drains the final turn boundary. Because one interrupted turn may contain substantial valid work, `load` preserves its contiguous, parseable events and appends risk-classified error results for unanswered assistant calls, a missing `step/end`, and `turn/end` with `{ kind: 'interrupted' }`. The synthetic results keep resumed provider transcripts valid. Only an incomplete final record is discarded; a parse error or sequence gap at or before the last real `turn/end` is corruption and makes the session unloadable. -- **File backend canonical, DB backend a proven drop-in.** `SessionEvent` maps 1:1 onto a row `(session_id, seq, type, time, data)` — `append` is INSERT (in a transaction asserting the contiguous-seq contract), `load` is SELECT … ORDER BY seq. `dsh-session-persistence-sqlite` is exactly this: a `SessionPersistence` subclass with no interface change (opencode runs this exact shape on SQLite/WAL), and it passes the same `runPersistenceContract` suite as the JSONL backend — so the contract holds both backends to identical semantics (lazy materialization, interrupted-turn close on load, contiguous-seq), expressed once over file bytes and once over rows. -- **Metadata is out-of-log.** Format version, cwd, and lineage are storage concerns, not replayable conversation state, so they live in a `SessionHeader` owned by `dsh-session` and attached to a `Session` via a new readonly `session.header` — never in `SessionEventMap`, never reaching `deriveMessages()`. The alternative (a merge-extensible `session/meta` event as log line 0) was rejected: an in-log event would ride along with a seeded/forked session for free, but metadata is not replayable state, so the explicit out-of-log header seam is the cleaner cost. (The header was originally split into an immutable `SessionHeader` plus a mutable `SessionSummary` whose union was `SessionMeta`; the mutable summary was later removed as dead state — see [Drop the mutable session summary](../simplification/2026-06-19-drop-mutable-session-summary.md).) +- **File backend canonical, DB backend a proven drop-in.** `SessionEvent` maps 1:1 onto a row `(session_id, seq, type, time, data)` — `append` is INSERT (in a transaction asserting the contiguous-seq contract), `load` is SELECT … ORDER BY seq. `dsh-session-persistence-sqlite` is exactly this: a `SessionPersistence` subclass with no interface change (opencode runs this exact shape on SQLite/WAL), and it passes the same `runPersistenceContract` suite as the JSONL backend — so the contract holds both backends to identical semantics (lazy materialization, interrupted-turn close on load, contiguous-seq), expressed once over file bytes and once over rows. Its database carries a dedicated application id and monotonic schema version. A pristine file creates all tables and stamps both header values in one transaction; an unversioned file with any user-defined schema object or application identity, a foreign current-version identity, and every non-current version reject before journal-mode mutation. +- **Metadata is out-of-log.** Format version, cwd, and lineage are storage concerns, not replayable conversation state, so they live in a `SessionHeader` owned by `dsh-session` and attached to a `Session` via a new readonly `session.header` — never in `SessionEventMap`, never reaching `deriveMessages()`. `createdAt` is non-negative safe-integer Unix epoch milliseconds: live creation and persistence registration reject fractional values, JSONL validates the decoded header, and SQLite stores it in a strict `INTEGER` column. The alternative (a merge-extensible `session/meta` event as log line 0) was rejected: an in-log event would ride along with a seeded/forked session for free, but metadata is not replayable state, so the explicit out-of-log header seam is the cleaner cost. (The header was originally split into an immutable `SessionHeader` plus a mutable `SessionSummary` whose union was `SessionMeta`; the mutable summary was later removed as dead state — see [Drop the mutable session summary](../simplification/2026-06-19-drop-mutable-session-summary.md).) - **`ctx.agents.create()` and `ctx.agents.resume()` are async factories; resume additionally crosses the persistence boundary.** `ctx.agents.resume({ resumeSessionId })` awaits `ctx.sessionPersistence.load`, recreates the live session with the loaded events (so `lastTurnNumber`/`deriveMessages` continue), and registers the fresh agent under the exact resumed id. The agent-loop does NOT hard-inject `sessionPersistence` (that would pend non-persistent demos forever); `resume` rejects with a clear error when it is absent. ## Alternatives considered -Each key choice above records its rejected alternative where the choice is stated: a **chunk-filtered canonical log** (Codex's `policy.rs` shape) — breaks the contiguous-seq contract; **truncating a crashed turn** — silently destroys a long autonomous run's real work; an **in-log `session/meta` event as line 0** — metadata is not replayable state; **hard-injecting `sessionPersistence` into the loop** — would pend non-persistent demos forever. +Each key choice above records its rejected alternative where the choice is stated: a **chunk-filtered canonical log** (Codex's `policy.rs` shape) — breaks the contiguous-seq contract; **truncating a crashed turn** — silently destroys a long autonomous run's real work; an **in-log `session/meta` event as line 0** — metadata is not replayable state; **finite fractional `createdAt` values** — have no producer and diverge from integer Unix-millisecond storage and query columns; **adopting a non-pristine unversioned SQLite file** — can overwrite unrelated objects or identity; **hard-injecting `sessionPersistence` into the loop** — would pend non-persistent demos forever. Format versioning: the header carries a `version`; `load` rejects any non-current version (no migration — the pre-release session format is pinned at `SESSION_FORMAT_VERSION = 0` and absorbs shape churn, per the AGENTS.md pre-release stance). Stated honestly: append-only + flush is robust to partial trailing writes (tolerated on load) but not to fsync-less power loss mid-line; a DB/WAL backend is the stronger option later. ## Consequences -Two new packages and the metadata seam in `dsh-session` (`session.header`, the `create(id?, options?)` signature). Bought: durable resume/fork, a read/replay path, crash tolerance, and the foundation the ACP `session/load` ([ACP support](../feature/2026-06-14-acp-agent-client-protocol.md)) needs — all over the existing event-sourced log, with the backend swappable behind one interface. The reusable `runPersistenceContract` suite holds every backend to the same append-only, contiguous-seq, lazy-materialization, and serializability semantics. Persisting the full log also settles event fidelity: `assistant/chunk` remains verbatim. +Two new packages and the metadata seam in `dsh-session` (`session.header`, the `create(id?, options?)` signature). Bought: durable resume/fork, a read/replay path, crash tolerance, and host-side session access over the existing event-sourced log, with the backend swappable behind one interface. The reusable `runPersistenceContract` suite holds every backend to the same append-only, contiguous-seq, lazy-materialization, integer-metadata, and serializability semantics. Persisting the full log also settles event fidelity: `assistant/chunk` remains verbatim. SQLite initialization either commits its complete owned schema and header identity or leaves no partial schema to strand on the next open. diff --git a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.zh.md b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.zh.md new file mode 100644 index 0000000000..143b58d321 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 会话持久化作为基于现有 `SessionEvent` 的抽象服务 + +Status: implemented + +[English](2026-06-14-session-persistence.md) | 中文 + +## 问题 + +会话此前仅存在于内存中。示例插件 `session-jsonl.ts`(在两个示例中逐字节重复)是只写的遥测:它缓冲 `session/event` 并追加 JSON 行,没有读取/回放路径,没有崩溃安全性(无 fsync、无原子写入、fire-and-forget 的 dispose 排空),没有列表功能,也没有格式版本控制。没有任何机制能将磁盘上的历史会话重新注入到活跃的 agent(智能体)中,因此持久恢复、持久 fork 以及宿主侧的会话浏览都无法实现。 + +[事件溯源模型](2026-06-11-event-sourced-sessions.md)将仅追加日志作为唯一真源,并从中派生 LLM(大语言模型)历史。持久化必须忠实于这一设计:直接持久化现有的 `SessionEvent`,不引入需要来回转换的并行「持久化消息」类型。后端也必须可替换——当前用文件存储,以后用数据库存储——统一在一个接口之后。 + +## 决策 + +持久化是一个抽象的**能力 seam**([能力 seam](2026-06-13-capability-seams.md),`dsh-bash` 模板),而非循环或核心逻辑: + +1. **接口**(`dsh-session-persistence`,`ctx.sessionPersistence`):一个抽象的 `SessionPersistence` 服务,提供 `create`/`append`/`load`/`list`。其持久化单元就是现有的 `SessionEvent`(`{ type, seq, time, data }`),原样复用,无转换类型。 +2. **实现**(`dsh-session-persistence-jsonl`):每个会话一个仅追加的逻辑 JSONL 日志(一行 `SessionHeader`,之后每行一个 `SessionEvent`,逐字节保留,**包括 `assistant/chunk`**),默认编码为[带校验和的 Zstandard 帧](2026-07-19-zstandard-jsonl-session-logs.md),也可通过配置使用原始行。 + +以下关键选择记录于此,因为它们是持久性的、有争议的、且出人意料的: + +- **规范的持久日志逐字节保留每个 `SessionEvent`,包括 `assistant/chunk`。** `deriveMessages()` 跳过分片,而过滤分片的方案(Codex 的 `policy.rs`)很有吸引力,但 `seq = log.length` 以及加载验证 `events[i].seq === i` 要求日志是*连续*的;过滤掉分片会留下空洞,同时破坏契约和恢复功能。基于分片过滤的投影可以作为派生视图在后续实现(带有自己的重新编号),但它不是规范日志。 +- **仅追加;崩溃的轮次被关闭,而非截断。** 已刷写的事件永不被重写。[语义检查点策略](../bug-fix/2026-07-21-semantic-session-checkpoints.md)会在模型分发前排空请求、在工具分发前排空已记录的顶层调用,并在步骤结束后排空完整的响应/结果批次;循环则排空最终轮次边界。由于一个被中断的轮次可能包含大量有效工作,`load` 保留其连续、可解析的事件,并为未应答的 assistant 调用追加按风险分类的错误结果、补一个缺失的 `step/end`,以及带 `{ kind: 'interrupted' }` 的 `turn/end`。合成的结果保证恢复后的提供方 transcript(文本记录)仍然有效。只有不完整的最后一条记录会被丢弃;在最后一个真实 `turn/end` 处或之前出现解析错误或序号间隙,属于数据损坏,会使该会话不可加载。 +- **文件后端为规范实现,数据库后端为经过验证的直接替换。** `SessionEvent` 1:1 映射到一行 `(session_id, seq, type, time, data)`:`append` 是 INSERT(在一个断言连续 seq 契约的事务中),`load` 是 SELECT … ORDER BY seq。`dsh-session-persistence-sqlite` 正是如此:一个 `SessionPersistence` 子类,接口无变化(opencode 在 SQLite/WAL 上运行的正是这个形状),且通过与 JSONL 后端相同的 `runPersistenceContract` 测试套件。该契约以相同的语义约束两个后端(惰性物化、加载时关闭中断轮次、连续 seq),一次表达在文件字节上,一次表达在数据库行上。其数据库拥有专用的 application id 与单调递增的 schema 版本。系统会在一个事务中为全新文件创建所有表并写入这两个 header 值;未版本化文件若带有任何用户定义的 schema 对象或应用标识、当前版本文件若带有外部应用标识,以及任何非当前版本文件,都会在修改日志模式之前被拒绝。 +- **元数据在日志之外。** 格式版本、cwd 和谱系是存储关注点,不是可回放的对话状态,因此它们存放在 `dsh-session` 拥有的 `SessionHeader` 中,并通过新的只读属性 `session.header` 附加到 `Session` 上——永远不进入 `SessionEventMap`,永远不到达 `deriveMessages()`。`createdAt` 是以 Unix epoch 毫秒表示的非负安全整数:运行时创建和持久化注册会拒绝小数值,JSONL 会验证解码后的 header,SQLite 则将其存入严格的 `INTEGER` 列。替代方案(一个可合并扩展的 `session/meta` 事件作为日志第 0 行)被否决:日志内事件会随 seed/fork 的会话免费携带,但元数据不是可回放状态,因此显式的日志外 header seam 是更干净的代价。(header 最初被拆分为不可变的 `SessionHeader` 加可变的 `SessionSummary`,二者的联合类型为 `SessionMeta`;可变 summary 后来因属于死状态而被移除——见 [移除可变会话摘要](../simplification/2026-06-19-drop-mutable-session-summary.md)。) +- **`ctx.agents.create()` 和 `ctx.agents.resume()` 是异步工厂;恢复还跨越持久化边界。** `ctx.agents.resume({ resumeSessionId })` 等待 `ctx.sessionPersistence.load`,用加载的事件重建活跃会话(使 `lastTurnNumber`/`deriveMessages` 得以延续),并以原样恢复的 id 注册新 agent。agent loop(智能体循环)不会硬注入 `sessionPersistence`(那样会让非持久化的演示永远挂起);当它不存在时,`resume` 会以明确的错误拒绝。 + +## 曾考虑的替代方案 + +上述每个关键选择都在陈述处记录了被否决的替代方案:**过滤分片的规范日志**(Codex 的 `policy.rs` 形式)破坏连续 seq 契约;**截断崩溃的轮次**会静默销毁长时间自主运行中的真实工作;**日志内 `session/meta` 事件作为第 0 行**——元数据不是可回放状态;**有限的非整数 `createdAt` 值**没有生产方,且与整数 Unix 毫秒存储及查询列不一致;**接受非全新的未版本化 SQLite 文件**可能覆盖无关对象或应用标识;**将 `sessionPersistence` 硬注入循环**会让非持久化的演示永远挂起。 + +格式版本控制:header 携带一个 `version`;`load` 拒绝任何非当前版本(不做迁移——预发布阶段的会话格式固定为 `SESSION_FORMAT_VERSION = 0` 并吸收形状变动,遵循 AGENTS.md 的预发布立场)。坦率地说:仅追加 + 刷写对部分尾部写入是健壮的(加载时容忍),但对行写入中途的无 fsync 断电不健壮;数据库/WAL 后端是后续更强的选项。 + +## 后果 + +新增两个包(package),以及 `dsh-session` 中的元数据 seam(`session.header`,`create(id?, options?)` 签名)。收益:持久恢复/fork、读取/回放路径、崩溃容忍,以及基于现有事件溯源日志的宿主侧会话访问,后端在一个接口之后可替换。可复用的 `runPersistenceContract` 测试套件以相同的仅追加、连续 seq、惰性物化、整数元数据与可序列化语义约束每个后端。持久化完整日志还确定了事件保真度:`assistant/chunk` 保持逐字节不变。SQLite 初始化要么提交完整的自有 schema 与 header 标识,要么不留下任何会使下次打开受阻的部分 schema。 diff --git a/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.i18n.yaml new file mode 100644 index 0000000000..46cb7aaa20 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-15-turn-enclosure-invariant.md: 6e2abd1716f8efc08c06d5ff8faec38282f2a17f +2026-06-15-turn-enclosure-invariant.zh.md: 0921c2574dc171e887664d8a2ea840a4e81f1531 diff --git a/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.md b/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.md index 00352b01c4..6e2abd1716 100644 --- a/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.md +++ b/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-15-turn-enclosure-invariant.zh.md) + ## Problem A durable session-persistence backend (added in a companion change) uses the **turn** as its crash-recovery boundary: a crash can leave an unclosed final turn, which `load` closes with a synthetic `turn/end {kind:'interrupted'}` while preserving the turn's real events (see [session persistence](2026-06-14-session-persistence.md)). This recovery is only well-defined if nothing *legitimately* durable sits OUTSIDE a turn — between the last `turn/end` and the next `turn/start` — since such an event would be swept into the next turn's interrupted close. diff --git a/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.zh.md b/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.zh.md new file mode 100644 index 0000000000..0921c2574d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.zh.md @@ -0,0 +1,42 @@ +# Agent Note: 每个会话事件都封闭在一个轮次内 + +Status: implemented + +[English](2026-06-15-turn-enclosure-invariant.md) | 中文 + +## 问题 + +持久化的会话持久化后端(在配套变更中引入)以**轮次**作为崩溃恢复边界:崩溃可能留下一个未关闭的最终轮次,`load` 会用一个合成的 `turn/end {kind:'interrupted'}` 将其关闭,同时保留该轮次的真实事件(见[会话持久化](2026-06-14-session-persistence.md))。这种恢复只有在没有任何*合法的*持久事件位于轮次之外(即上一个 `turn/end` 与下一个 `turn/start` 之间的间隙)时才是良定义的,否则这类事件会被卷入下一个轮次的中断关闭中。 + +这一假设并不成立。有两条路径在任何轮次之外记录了事件: + +1. **排队的用户消息。** agent loop(智能体循环)排空排队消息并在 `turn/start` *之前*追加 `user/message`——于是一个轮次自身的提示词落在了前一个 `turn/end` 与下一个 `turn/start` 之间的间隙中。 +2. **空闲时的上下文注入。** `agent.inject()` 直接追加一条 `context/message`。它在生产环境中的真实调用方是 `dsh-tool-bash`,后者从 `ctx.bash.onTaskDone` 注入后台任务完成通知——该回调在后台 bash 任务完成时触发,而这经常发生在 agent **空闲**(轮次之间)时。 + +在情况 2 中,如果注入的 `context/message` 是 flush/dispose 之前的最后一个事件(之后没有轮次追加 `turn/end`),`scanLog` 会将其视为崩溃残留并在**恢复时丢弃**——注入的上下文已持久写入磁盘,但重新加载后被静默丢失。情况 1 本身无害(`user/message` 之后总会跟着它触发的轮次),但使「什么可以出现在轮次之外」这条规则变得模糊。 + +## 决策 + +**每个会话事件都位于一个轮次内部**:在 `turn/start` 与其匹配的 `turn/end` 之间。具体而言: + +- agent loop 在 `turn/start` **之后**(轮次内部)追加排队的 `user/message` 事件,而非之前。因此,一旦这些消息被记录,就欠下一个 `turn/end`,既有的 finalizer 保证它被写入。 +- agent **运行中**调用 `agent.inject()` 时,它会加入已打开的轮次。当前步骤执行 assistant 工具调用期间,已接受的上下文按到达顺序等待该批次结算,随后在每个已记录结果之后追加;即使执行中断,也会在轮次关闭前写入。 +- agent **空闲时**调用 `agent.inject()`,则将 `context/message` 包裹在一个一次性轮次中:`turn/start{trigger:{kind:'injection'}}` → `context/message` → `turn/end{completed}`。一个新的 `injection` 变体加入可合并扩展的 `TurnTriggerMap`。 +- agent loop 每次迭代从日志推导下一个轮次编号(`lastTurnNumber(session) + 1`),而不是维护一个私有计数器,这样空闲注入的一次性轮次不会与下一个真实轮次的编号冲突。 +- `dsh-session/invariant` companion 将该检查注册到 `ctx.invariants`:选中后,在没有打开轮次的情况下追加 `user/message` / `context/message` / `steering/message` 会抛出归因于 `@deepseek-ai/dsh-session` 的 `InvariantError`。 + +可序列化性不变式在同一源码边界处强制执行(`Session.append` 对不可 JSON 序列化的数据抛出异常),因此「什么可以进入日志」现在由一个位置统一管控,而非由下游碰巧在监听的某个后端各自发现。 + +## 曾考虑的替代方案 + +**放宽读取端而非约束生产端**——让 `scanLog` 提交位于已打开轮次之外的事件。否决:一条单一、可检查的生产端规则优于一个更宽松的边界扫描(后者需要同时推理部分轮次*和*轮次间的散落事件)。 + +## 后果 + +轮次现在是*唯一的*持久性/回放边界,因此[会话持久化](2026-06-14-session-persistence.md)的崩溃恢复规则是完备的,而不仅仅是充分的:被中断的最终轮次被关闭(用合成的 `turn/end {interrupted}`),其真实事件得以保留,且零风险将轮次间上下文混入其中,因为不存在轮次间上下文。`scanLog` 保持简洁(最多一个可能未关闭的最终轮次,绝无散落的轮次间事件),空闲时的后台任务通知在持久化 + 恢复后依然存活。 + +代价:空闲时调用 `agent.inject()` 现在写入三行日志而非一行;派生的历史中多出一个仅包含注入上下文(无 assistant 输出)的轮次——`deriveMessages()` 已经纯粹按事件类型派生,因此渲染结果完全相同。`injection` 触发器是一个新的磁盘词汇值;与每次 `SessionEventMap`/`TurnTriggerMap` 的新增一样,它属于冻结格式的一部分。轮次内的事件顺序发生了变化(`turn/start` 现在先于 `user/message`),这对任何断言旧顺序的代码可观测——agent loop 自身的测试是唯一的此类消费方。 + +该规则有意采用生产端强制、开发环境检查的方式,而非读取端容忍的方式:未来的后端(SQLite/WAL)无需额外工作即可继承同样干净的边界,而在轮次外记录事件的插件会在开发环境中大声失败,而非在下次重新加载时静默丢失数据。 + +轮次内检测到的失败在 `turn/end` 之前记录。后续的 flush 失败没有有效的轮次内位置,因此通过 `agent/error` 和日志报告,而非作为会话事件追加。这保持了回放日志的平衡;持久化的运维诊断需要一个独立的遥测通道。 diff --git a/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.i18n.yaml new file mode 100644 index 0000000000..6f85d08fe8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-17-filesystem-capability-seam.md: 08e8d52b314eb10e2c7ec444dd61a96d8621e032 +2026-06-17-filesystem-capability-seam.zh.md: 6f4889234516ee134c9873781a874b5f1a3644ac diff --git a/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.md b/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.md index 7fa2bde08c..08e8d52b31 100644 --- a/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-17-filesystem-capability-seam.zh.md) + ## Problem The harness has a concrete `bash` capability seam (`dsh-bash` / `dsh-bash-local` / `dsh-tool-bash`), but filesystem operations are about to be added as model-facing tools without an equivalent seam. If `read`, `write`, and `edit` directly use `node:fs`, the model-facing tool package will own filesystem execution policy, local path resolution, atomic write behavior, text decoding, symlink behavior, and edit semantics all at once. diff --git a/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.zh.md new file mode 100644 index 0000000000..6f48892345 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.zh.md @@ -0,0 +1,160 @@ +# Agent Note: 文件系统能力 seam——ctx.fs、本地后端与面向模型的文件系统工具 + +Status: implemented + +[English](2026-06-17-filesystem-capability-seam.md) | 中文 + +## 问题 + +harness 已有一个具体的 `bash` 能力 seam(`dsh-bash` / `dsh-bash-local` / `dsh-tool-bash`),但文件系统操作即将作为面向模型的工具加入,却没有等价的 seam。如果 `read`、`write` 和 `edit` 直接使用 `node:fs`,面向模型的工具包将同时承担文件系统执行策略、本地路径解析、原子写入行为、文本解码、符号链接行为和编辑语义。 + +这把三个独立变化的关注点耦合在了一起: + +1. 文件系统契约:插件可以请求哪些操作。 +2. 后端:当前是本地磁盘,未来可能是沙箱/远程/项目作用域的文件系统。 +3. 消费方接口:面向模型的 `read` / `write` / `edit` schema 与结果格式化。 + +如果没有 `ctx.fs` 接口,将本地文件系统访问替换为沙箱或远程后端时,即使面向模型的契约应当保持稳定,工具 schema、演示和提示词引导也会被迫变动。这还使权限/沙箱边界更难推理:一个 `cwd` 选项看起来像沙箱,但除非有显式的后端或 `tools/execute` 策略强制隔离,否则它只是一个基础路径。 + +我们需要文件系统工具在成为公开包(package)接口之前,以与 bash 相同的能力 seam 形态落地。 + +## 决策 + +文件系统访问是一个一等的能力 seam,遵循[能力 seam Agent Note](2026-06-13-capability-seams.md): + +1. `@deepseek-ai/dsh-fs`(`packages/fs/fs`)拥有抽象的 `ctx.fs` 服务、文件系统词汇类型,以及 `fs/*` 策略事件词汇。 +2. `@deepseek-ai/dsh-fs-local`(`packages/fs/fs-local`)提供第一个实现,以本地文件系统为后端。 +3. `@deepseek-ai/dsh-tool-fs`(`packages/fs/tool-fs`)通过 `ctx.fs` 提供面向模型的 `read`、`write` 和 `edit` 工具,是分发 `fs/*` 事件的执行器。 + +消费方包仅依赖接口包,从不依赖 `dsh-fs-local`。需要不同后端的部署只需为 `ctx.fs` 加载不同的提供方,无需改动工具 schema 或面向模型的提示词引导。 + +读后写/编辑与观测状态策略是第四个包 `@deepseek-ai/dsh-fs-policy`(`packages/fs/fs-policy`),通过 `fs/*` 事件门控贡献,而非挂在 `ctx.fs` 上;加载 `dsh-tool-fs` 的部署同时加载 `dsh-fs-policy` 以获得读后写/编辑能力。本 Agent Note 确立了由三个包构成的 seam;策略从提供方基类拆出的决策由 [拆分文件系统 seam Agent Note](../simplification/2026-06-26-fsspec-style-fs-seam.md) 做出,其以事件门控插件(而非方法服务)实现的方式由 [事件门控 Agent Note](2026-06-26-file-context-as-event-gate.md) 做出。本文已更新为描述最终落地的四包形态。 + +第一个后端有意仅限本地:`dsh-fs-local` 基于宿主文件系统实现 `ctx.fs`。未来的兄弟后端可在同一接口之后提供沙箱、远程、虚拟或项目作用域的文件系统。 + +第一个消费方有意仅限文本文件:`dsh-tool-fs` 暴露面向模型的 `read`、`write` 和 `edit` 工具,处理 UTF-8 文本文件。未来的消费方可以添加目录列表、搜索/glob、二进制安全操作、文件监视或更高层的项目操作,只要 `ctx.fs` 上存在所需能力,就无需改动本地后端包。直接目录列表后来由[为文件系统 seam 添加直接目录列举能力](2026-07-03-filesystem-directory-listing-seam.md)添加。 + +文件系统权限和沙箱并非此拆分所隐含。本地后端从其配置的基目录解析相对路径,但隔离策略是独立的决策:要么由更严格的 `ctx.fs` 实现强制执行,要么由权限/沙箱插件包装 `tools/execute` 并在调用到达消费方之前否决。 + +读后写/编辑与观测状态属于 `dsh-fs-policy`,而非 `ctx.fs`。通过 `fs/*` 事件门控,策略按不透明 actor 记录版本,并提供可选的变更期望;提供方原子性地强制新鲜度。`dsh-tool-fs` 发出事件但不依赖策略。见[拆分文件系统 seam](../simplification/2026-06-26-fsspec-style-fs-seam.md)和[事件门控插件](2026-06-26-file-context-as-event-gate.md) Agent Note。 + +## 包拓扑 + +文件系统 seam 使用与 bash 三件套相同的依赖方向: + +```text +@deepseek-ai/dsh-tool-fs --depends on--> @deepseek-ai/dsh-fs <--depends on-- @deepseek-ai/dsh-fs-local + consumer interface implementation +``` + +`@deepseek-ai/dsh-fs` 仅依赖 `cordis` 加上来自 `@deepseek-ai/dsh-llm` 的仓库级 `HarnessError` 基类。它声明 `ctx.fs` 键、抽象 `FileSystem` 服务、后端和消费方共享的词汇类型、文件系统错误词汇,以及 `fs/*` 策略事件词汇。它不持有观测状态存储,也不持有 owner 推导形态;事件传递一个不透明的 `object` actor,提供方从不读取它,`dsh-fs-policy` 插件在这些事件之上拥有 owner 推导形态和观测状态存储。 + +`@deepseek-ai/dsh-fs-local` 依赖 `@deepseek-ai/dsh-fs` 和 `cordis`。它继承 `FileSystem`,将自身注册为 `ctx.fs`,拥有本地后端配置(如基目录),并包含所有直接的 `node:fs` / `node:path` 访问。它不持有观测状态存储——新鲜度是后端铸造、策略插件记录的版本令牌。 + +`@deepseek-ai/dsh-tool-fs` 依赖 `@deepseek-ai/dsh-fs`、`@deepseek-ai/dsh-tools`、`@deepseek-ai/dsh-system-prompt` 和 `cordis`。它注册面向模型的工具和提示词段落。它禁止导入 `node:fs`、`node:path` 或 `@deepseek-ai/dsh-fs-local`;文件系统执行始终通过 `ctx.fs`。如果实现需要具体的 agent 或会话辅助类型,这些依赖属于 `tool-fs`;它们禁止回漏到 `dsh-fs` 中。 + +根 `tool-fs` 插件通过组合各工具的注册辅助函数来注册完整的文件系统工具套件(`read`、`write` 和 `edit`)。它注入 `fs`,从不导入实现包。 + +## `ctx.fs` 契约 + +`@deepseek-ai/dsh-fs` 拥有一个语义文件系统服务。它比 `readFile` / `writeFile` 更高层,这样 `tool-fs` 就不必重新实现路径解析、版本管理、文本解码、二进制拒绝、分页、原子替换、符号链接行为或字面编辑语义。 + +该接口涵盖以下语义操作: + +- 将模型/插件提供的路径解析为后端定义的目标。 +- 获取目标元数据而不读取文件内容。 +- 从目标读取有界的 UTF-8 文本页。 +- 创建或替换一个 UTF-8 文本文件。 +- 通过字面替换编辑一个已有的 UTF-8 文本文件。 + +提供方 seam 还携带策略所依赖的新鲜度钩子——但观测状态存储和 owner 推导位于 `dsh-fs-policy` 插件中,而非 `ctx.fs` 上: + +- 后端为每个目标铸造一个不透明的 `version` 令牌(在 `stat` 以及每次读取/变更结果中)。 +- `writeText`/`editText` 接受一个可选的版本期望:省略它表示无条件的裸提供方变更;提供它则在后端的原子临界区内守护变更。 +- `dsh-fs-policy` 插件在 `fs/write-intent`/`fs/edit-intent` 上决定该期望,并在 `fs/observed` 上记录观测版本,以它从不透明事件 actor 推导出的 owner 为键(通常是 `exec.agent.session`)。 + +授权基于版本新鲜度,而非完整/部分视图的区分:任何读取都会记录目标的版本,后续的写入/编辑只要文件仍处于该版本就被授权——因此对第 100-150 行的窗口化读取可以授权对第 120 行的编辑。观测状态存储是 `dsh-fs-policy` 内部的 `WeakMap<owner, Map<targetKey, version>>`;`dsh-fs` 不持有任何此类数据,并将 actor 视为不透明。(本 Agent Note 最初建模了一个带 `full`/`partial` 视图的 `FileState` 缓存放在 `ctx.fs` 上;拆分文件系统 seam 与事件门控两份 Agent Note 将其替换为此处描述的基于新鲜度的策略插件。) + +路径解析是显式的,允许异步。本地解析可能只做路径规范化,但沙箱/远程/项目作用域的后端可能需要 I/O 才能将用户提供的路径解析为稳定的目标标识。 + +解析后的目标必须至少暴露三个概念: + +- 原始输入路径,用于诊断。 +- 不透明的 `targetKey`,用于陈旧守护和文件状态查找。本地后端可能使用类似 realpath 的键;远程后端可能使用工作区 URI 或文件 id。消费方禁止解析或假设它是本地绝对路径。 +- `displayPath`,用于面向模型/UI 的输出。根据后端不同,它可能是本地绝对路径、工作区相对路径或远程 URI。 + +读取和变更结果必须包含不透明的文件 `version`。本地后端从 bigint stat 元数据(`dev`、`ino`、`size`、`mtimeNs` 和 `ctimeNs`)派生令牌,因此同大小重写和 inode 替换都会可靠地使消费方失效;远程后端可以使用 revision id 或类似 hash 的令牌。`dsh-fs-policy` 插件记录版本用于陈旧检查;消费方可以展示相关元数据但禁止解释版本令牌。 + +提供方返回已解码的文本:`readText` 返回整个常规文本文件,`streamText` 为大文件流式传输相同的文本语义。两者负责常规文件检查;有界的行/输出处理不是它们的职责——行窗口化、带行号渲染和总行数统计位于执行器(`dsh-tool-fs`)中,执行器通过 `ctx.fs` 读取并渲染面向模型的窗口。提供方负责 UTF-8 解码和二进制/NUL 拒绝;它不知道行窗口或视图。 + +观测状态记录不在 `ctx.fs` 上:成功读取后,执行器发出 `fs/observed`,`dsh-fs-policy` 插件为推导出的 owner 记录 `{ version }`。没有 `full`/`partial` 视图——任何窗口的读取都记录版本,新鲜度(而非视图完整性)授权后续的写入/编辑。 + +全文件写入创建或替换 UTF-8 文本文件。后端在支持且有文档说明时可以创建父目录。已有的非常规目标被拒绝。`writeText` 接受一个可选期望:`createIfAbsent` 创建缺失的目标并拒绝已存在的(报 `FS_NOT_OBSERVED`,这是策略为未观测 owner 使用的路径);`replaceIfVersion` 仅在目标处于观测版本时替换,否则报 `FS_STALE_VERSION`;省略期望则为无条件的裸提供方创建或覆盖。策略插件根据 owner 的观测状态选择提供哪个期望。 + +字面编辑是提供方原语(`editText`),而非在 `tool-fs` 中由读取加写入组合而成。字面匹配、重复匹配拒绝、CRLF 保留、二进制拒绝、可选的陈旧版本检查和原子读-改-写必须一起留在后端的变更临界区内。`editText` 接受相同的可选版本期望;陈旧检查在字面匹配之前运行,因此基于旧读取的编辑会报 `FS_STALE_VERSION`。远程后端可以将编辑实现为原生的 compare-and-edit 操作;消费方不强制本地风格的组合。 + +策略插件(而非 `ctx.fs`)对先前观测进行门控:`edit` 要求 owner 有先前观测(否则报 `FS_NOT_OBSERVED`),记录的版本作为 CAS 基础传给 `editText`。在策略插件缺席时,`ctx.fs` 本身是一个完整的无约束 seam(无条件写入/编辑);工具从不与策略方法耦合。 + +文件系统契约失败以 `FsError extends HarnessError` 抛出,工具注册表将其转换为带结构化 `{ name, code }` 元数据的 `isError` 工具结果。`dsh-fs` 拥有此词汇,而非由每个工具各自发明消息。错误码包括 `FS_NOT_FOUND`、`FS_NOT_TEXT`、`FS_STALE_VERSION`、`FS_NOT_OBSERVED`、`FS_NOT_REGULAR_FILE`、`FS_AMBIGUOUS_EDIT`、`FS_EDIT_NOT_FOUND` 和 `FS_ABORTED`。(早期草案包含 `FS_PARTIAL_OBSERVATION`;基于新鲜度的授权没有 partial/full 区分,因此已删除。目录列表相关的错误码后来由[为文件系统 seam 添加直接目录列举能力](2026-07-03-filesystem-directory-listing-seam.md)添加。) + +## 工具消费方行为 + +`@deepseek-ai/dsh-tool-fs` 是面向模型的消费方。它拥有工具名称、JSON Schema、模型边界的参数校验、提示词段落和结果格式化。它不拥有文件系统执行。 + +第一个工具套件包含: + +- `read`:检查一个 UTF-8 文本文件并返回带行号的内容与分页引导。 +- `write`:创建或完全替换一个 UTF-8 文本文件。 +- `edit`:通过替换字面文本更新一个已有的 UTF-8 文本文件,默认要求唯一匹配,并允许显式的全部替换模式。 + +每个工具遵循相同的执行形态: + +1. 校验并规范化模型参数。 +2. 调用相应的 `ctx.fs` 操作。 +3. 将结果格式化为面向模型的 `ContentBlock[]`。 +4. 让抛出的后端/工具错误流经 `ToolRegistry.execute()`,由其转换为 `isError` 工具结果。 + +该包通过 `ctx.systemPrompt.section(...)` 注册提示词引导,通过 `ctx.tools.register(...)` 注册 schema。工具 schema 仍通过 `SystemPrompt.assemble()` 和 `ToolRegistry.schemas()` 流入正常的提示词组装路径;无需改动 agent loop(智能体循环)。 + +工具包在后端变化时保持面向模型的契约稳定:本地后端和远程后端内部可能以不同方式解析路径,但 `read` / `write` / `edit` schema 不会仅因后端变化而改变。 + +默认部署要求在用 `write` 或 `edit` 更新已有文件之前先 `read`。`tool-fs` 不通过检查是否运行过名为 `read` 的工具来实现这一点:它分发 `fs/write-intent`/`fs/edit-intent` 事件(将执行上下文作为不透明 actor 传递),`dsh-fs-policy` 插件推导 owner、对先前观测进行门控并提供版本期望。任何窗口化读取都能授权后续的写入/编辑,只要文件未变。用 `write` 创建新文件不要求先前观测。 + +根插件通过组合各工具的注册辅助函数来注册完整套件。它注入 `fs`、`tools` 和 `systemPrompt`。 + +## 测试 + +测试遵循包边界,而不仅是用户可见的工具:`dsh-fs` 中的服务 seam;`dsh-fs-local` 中通过 `ctx.fs` 接口测试的真实文件系统行为(解析、符号链接、流式传输、二进制/UTF-8 拒绝、无条件和版本守护的写入、字面编辑语义、行尾保留、结构化 `FsError` 错误码);`dsh-tool-fs` 中基于真实本地提供方的消费方接口(只 mock 模型/时钟,从不 mock 协作者);以及通过 `ctx.tools.execute()` 在有和没有 `dsh-fs-policy` 的情况下进行集成测试,通过从磁盘回读文件来验证世界状态,既不信任规范值,也不信任渲染内容。观测状态/owner 推导策略在 `dsh-fs-policy` 中测试,不在此处。 + +本仓库曾踩过的防御性模式类别被直接固定: + +- **原子写入临时文件安全。** 写入/编辑通过目标旁边一个私有随机 `0700` 目录中的独占 owner-only(`'wx'`、`0o600`)临时文件暂存,失败时清理,最后原子 rename——与 bash 溢出文件规则一致,因为可预测的 world-readable 临时路径招致符号链接竞争和信息泄露。测试断言权限,并断言已存在的临时路径不会被覆盖;此原语是 seam 的常设要求。 +- **通过符号链接的 `targetKey` 同一性。** 两个输入路径解析到同一 realpath 时共享一个观测状态条目:通过路径 A 的 `read` 满足通过符号链接路径 B 的 `edit` 的读后编辑守护,通过一个路径的陈旧写入可通过另一个路径检测到。 +- **并发/陈旧竞争。** 对同一目标的两个并发写入/编辑操作确定性地收敛——一个成功,另一个被 `FS_STALE_VERSION` 拒绝——成功的编辑刷新记录状态,使同一 owner 的下一次编辑可以继续。 +- **HMR(热模块替换)安全与 dispose(资源释放)。** dispose 后端的 fiber 会撤回 `ctx.fs` 提供方;后续的提供方以无继承状态启动。 + +## 曾考虑的替代方案 + +- **面向模型的工具直接基于 `node:fs`**:工具包将同时承担执行策略、路径解析、原子写入、文本解码和编辑语义,耦合问题部分所列的三个独立变化的关注点,且任何后端替换都会搅动 schema。 +- **单一合并包 `dsh-fs-tools`**:seam 之前的形态;以与 bash 相同的接口/实现/消费方拆分理由否决,且合并名称从未成为公开接口。 +- **观测状态放在 `ctx.fs` 上**:本 Agent Note 最初落地的形态;被 [拆分文件系统 seam Agent Note](../simplification/2026-06-26-fsspec-style-fs-seam.md) 和 [事件门控 Agent Note](2026-06-26-file-context-as-event-gate.md) 取代:沙箱/远程后端不应继承面向模型的观测策略,因此提供方只保留版本令牌和可选的版本守护变更。 + +## 后果 + +**`cwd` 可能被误认为沙箱。** 本地后端的基目录是解析默认值,而非自动的隔离边界。如果需要隔离,必须由后端契约或 `tools/execute` 上的权限/沙箱插件强制执行。 + +**接口可能变得过于本地化。** 如果 `ctx.fs` 返回 `absolutePath` 之类的字段,远程、沙箱或虚拟后端会变得尴尬。契约应暴露显示元数据,而不要求消费方理解宿主路径。 + +**接口可能变得过于薄。** 如果 `ctx.fs` 只镜像 `node:fs` 原语,`tool-fs` 将重新实现二进制检测、分页、原子写入和编辑语义,重新制造本 Agent Note 试图避免的耦合。 + +**编辑语义天然易受竞争影响。** 字面编辑是读-改-写操作;守护手段是后端的原子变更临界区加上可选的版本期望,因此并发编辑确定性地收敛——一个赢,另一个得到 `FS_STALE_VERSION`。 + +**观测状态不属于 `ctx.fs`。** 记录执行上下文看到了什么是工作流策略,而非原始文件系统 I/O。本 Agent Note 最初将其放在文件系统 seam 内部;拆分文件系统 seam Agent Note 随后确立了沙箱/远程后端不应继承面向模型的观测策略,并将其移入 `dsh-fs-policy` 插件。提供方 seam 只保留写入/编辑安全在存储层真正需要的东西——后端铸造的版本令牌和可选的版本守护变更——而策略插件拥有 owner 推导、观测状态和基于 `fs/*` 事件的读后编辑门控。 + +**`resolve` 然后操作的形态每次调用多一次往返。** 每个工具可能先将路径解析为 `FsTarget`,再以单独的 `ctx.fs` 调用发起读取/写入/编辑。对本地后端来说这可以忽略(解析是内存中的路径规范化),但远程/沙箱后端可能将每步变成独立请求,使单次 `read` 变为两次网络往返。往返开销重要的后端可以在内部缓存或折叠解析,同时保持可观测契约不变。 + +**观测状态持久化被推迟。** 观测状态存在于内存中(`dsh-fs-policy` 内部的 `WeakMap`),因此恢复的会话保守地要求文件在写入/编辑前重新读取,直到未来的会话事件或持久化机制使观测可回放。 + +**错误码成为 seam 的一部分。** `FsError` 错误码使陈旧版本和观测失败可通过既有的结构化错误分类体系进行机器路由。代价是 `dsh-fs` 从 `dsh-llm` 导入共享的 `HarnessError` 基类;该依赖是有意为之且限于错误词汇。 + +**包拆分的成本前置。** 三包拆分在只有一个后端时就增加了样板代码。这是有意为之:文件系统访问是可能的沙箱/远程边界,在面向模型的工具发布后再改包接口代价更高。 diff --git a/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.i18n.yaml new file mode 100644 index 0000000000..3b07958faa --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-18-agent-lifecycle-and-ownership-seams.md: f190b4ba2b7f22d29f473c8a2725401ff371488e +2026-06-18-agent-lifecycle-and-ownership-seams.zh.md: dcaa319232baa8951a4f515abc6bce5611da5576 diff --git a/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md b/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md index 3d84c8074b..f190b4ba2b 100644 --- a/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md +++ b/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-18-agent-lifecycle-and-ownership-seams.zh.md) + ## Problem Several ACP and tool-bash limitations were symptoms of the same missing seam: plugins could create or resume agents through `ctx.agents`, but they could not own and dispose one agent independently, and long-running bash tasks carried no stable owner in the executor itself. ACP aborted and awaited agents on disconnect but could not unregister just that session's agent; `session/cancel` could not cancel queued-but-not-yet-started work; and `tool-bash` kept task ownership in a plugin-local `Map`, so an HMR reload could make an old task look unowned. @@ -16,7 +18,7 @@ A new `cancel()` verb on the `Agent` interface — the single public stop primit ### 2. `AgentHandle` async disposer -`ctx.agents.create`/`resume` (and the `AgentFactory` interface) return `AgentHandle = { agent: Agent; dispose(): Promise<void> }`. The disposer is a **consumer capability** — a registry observer holding only the bare `Agent` cannot tear it down. The caller fiber and registered factory provider are structural co-owners: caller unload enforces structured ownership, while provider unload must stop old instances whose scoped dependency surface resolves through that provider. All three paths reach the same memoized teardown: stop the loop, await its exit and idle flushes (true quiescence, not just the `disposed` status flip), detach the agent, detach its session, and unwind its scope. Each public ID becomes reusable when its exact registry entry detaches; there is no separate reservation-release phase. Config-created agents are already owned by the `AgentLoop` fiber (the handle is discarded). ACP holds each session's disposer in its `SessionRecord` and runs it on disconnect/teardown, so a bare client disconnect leaves no registered agent and no session-store entry — even when `session/load` races teardown (the just-resumed handle is disposed before the closed-guard throw). +`ctx.agents.create`/`resume` (and the `AgentFactory` interface) return `AgentHandle = { agent: Agent; dispose(): Promise<void> }`. The disposer is a **consumer capability** — a registry observer holding only the bare `Agent` cannot tear it down. The caller fiber and registered factory provider are structural co-owners: caller unload enforces structured ownership, while provider unload must stop old instances whose scoped dependency surface resolves through that provider. All three paths reach the same memoized teardown: stop the loop, await its exit and idle flushes (true quiescence, not just the `disposed` status flip), detach the agent, detach its session, and unwind its scope. Each public ID becomes reusable when its exact registry entry detaches; there is no separate reservation-release phase. Config-created agents are already owned by the `AgentLoop` fiber (the handle is discarded). ACP holds each fresh session's disposer in its `SessionRecord` and runs it on disconnect or plugin teardown, so a bare client disconnect leaves no registered agent and no session-store entry. A create that loses the close race disposes its unpublished handle. **Teardown ORDER is load-bearing for durability**, and the implementation folds the session lifecycle into the agent's SINGLE composite cordis effect (`SessionStore.prepare`/`enter`/`announce`, replacing a sibling-effect split). A fiber unload disposes sibling effects concurrently (`Promise.all`), which would race removing the session store's append publication hooks against the loop's closing `session/flush` and drop the closing `turn/end`; inside one effect the disposers run as an ordered LIFO chain (loop stopped + `await agent.done` BEFORE the session detaches), so the loop's final flush is captured on BOTH the handle's `dispose()` and a fiber unload. The contained `agent/disposed` and `session/disposed` notifications cannot reject the chain or skip later teardown. @@ -28,7 +30,7 @@ Background-task ownership moved from a `tool-bash` plugin-local `Map<string, Age These invariants hold and are pinned by tests: -- ACP disconnect/session close leaves no registered agent AND no session-store entry for that session, even when `session/load` races teardown. +- ACP disconnect or plugin teardown leaves no registered agent and no session-store entry for any bridge-owned session, including a create racing connection closure. - `session/cancel` before a queued prompt starts prevents that prompt from running; a later accepted prompt remains an independent queued turn. - A `tool-bash` HMR reload does NOT make an existing background task readable or killable by a different session (ownership survives on the executor). - Existing non-ACP demos still work without managing handles explicitly; config-created agents remain owned by the `AgentLoop` plugin fiber. diff --git a/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.zh.md b/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.zh.md new file mode 100644 index 0000000000..dcaa319232 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.zh.md @@ -0,0 +1,50 @@ +# Agent Note: Agent 生命周期与所有权 seam + +Status: implemented + +[English](2026-06-18-agent-lifecycle-and-ownership-seams.md) | 中文 + +## 问题 + +ACP(Agent Client Protocol)与 tool-bash 的若干限制是同一个缺失 seam 的症状:插件可以通过 `ctx.agents` 创建或恢复 agent(智能体),但无法独立拥有和 dispose(资源释放)单个 agent,而长时间运行的 bash 任务在执行器中也没有稳定的所有者。ACP 在断连时中止并等待 agent,却无法仅注销该会话的 agent;`session/cancel` 无法取消已入队但尚未开始的工作;`tool-bash` 将任务所有权保存在插件本地的 `Map` 中,因此一次 HMR(热模块替换)重载就可能让旧任务看起来无主。 + +## 决策 + +三个 seam:队列感知的取消、`AgentHandle` 释放器,以及 bash 所有者令牌。 + +### 1. 队列感知的 `Agent.cancel(cause?)` + +`Agent` 接口新增 `cancel()` 动词——唯一的公开停止原语。(它最初与范围更窄、仅作用于步骤的 `abort()` 一同交付;后者后来因无人使用而移除,使 `cancel()` 成为唯一公开的停止工作方式。)它清空 inbox 的 queued + steering FIFO,在存在活跃轮次时中止它,并保留一个不带 cause 的 pre-run 标记,使在取得所有权前被取消的提示词永不运行,而后来的提示词仍保持独立。有效调用会在清空或中止前发出 `agent/cancel-requested`,携带类型化的 `user | parent` cause;空闲取消不发出任何事件,也不会使下一条提示词搁浅。`whenIdle()` 会在取消后达到完全停稳,ACP 的 `session/cancel` 映射到 `user`。[显式轮次取消决策](2026-07-16-explicit-turn-cancellation.md)拥有当前的 cause、signal 生命周期与协作式结算契约。 + +### 2. `AgentHandle` 异步释放器 + +`ctx.agents.create`/`resume`(以及 `AgentFactory` 接口)返回 `AgentHandle = { agent: Agent; dispose(): Promise<void> }`。释放器是一种**消费方能力**——仅持有裸 `Agent` 的注册表观察者无法将其拆除。调用方 fiber 和已注册的 factory 提供方是结构上的共同所有者:调用方卸载强制结构化所有权,而提供方卸载必须停止旧实例,因为其实例作用域的依赖 surface 通过该提供方解析。三条路径都会进入同一个 memoize 的拆除过程:停止循环、等待其退出与空闲刷写完成(完全停稳,而非仅把状态翻转为 `disposed`)、分离 agent、分离其会话,然后解除其 scope。每个公开 ID 在其精确注册表条目分离时变得可复用;不存在独立的保留释放阶段。由配置创建的 agent 已归 `AgentLoop` fiber 所有(handle 被丢弃)。ACP 在其 `SessionRecord` 中保存每个全新会话的释放器,并在断连或插件拆除时运行它,因此单纯的客户端断连不会留下已注册 agent 或会话存储条目。在与关闭的竞态中落败的创建流程会 dispose 其尚未发布的 handle。 + +**拆除顺序对持久性至关重要**,实现将会话生命周期折叠进 agent 的单个复合 Cordis effect(`SessionStore.prepare`/`enter`/`announce`,取代兄弟 effect 拆分)。fiber 卸载会并发释放兄弟 effect(`Promise.all`),这会让会话存储的 append 发布钩子移除与循环关闭时的 `session/flush` 竞争,从而丢失关闭的 `turn/end`;在一个 effect 内,释放器作为有序的 LIFO 链运行(停止循环 + `await agent.done` 在会话分离之前),因此无论 handle 的 `dispose()` 还是 fiber 卸载,都会捕获循环的最终刷写。被隔离的 `agent/disposed` 和 `session/disposed` 通知无法拒绝该链或跳过后续拆除。 + +### 3. Bash seam 中的所有者令牌 + +后台任务所有权从 `tool-bash` 插件本地的 `Map<string, Agent>` 移入执行器。`BashExecRequest` 新增可选的 `owner?: string`;解析后的 `BashExecSpec` 将其作为必需但可空的 `owner: string | undefined` 携带(被遗忘的 owner 是可见的 `undefined`,而非静默缺失的属性)。执行器把 token 存在任务上,并通过新的 `BashExecutor.ownerOf(id): string | undefined` seam 暴露它(不放在公开的 `BashTask` 上——只有一条读取路径,没有冗余 API)。`tool-bash` 完全删除其 `Map`:它在 `start` 时将 `exec.agent?.id`(共享的注册表/会话 id)盖章为 owner,`bash_output`/`bash_kill` 则以 `!== undefined` 语义把 `ctx.bash.ownerOf(id)` 与调用方 token 比较(空字符串 token 仍是真实 owner)。完成通知通过扫描 `ctx.get('agents')?.list()` 查找 `agent.id === ownerToken` 的存活 agent(经 `ctx.get` 读取——`onTaskDone` 运行在 bash fiber 这一外部 fiber 上,直接使用 `ctx.agents` proxy 会抛异常)。由于所有权现在存活在执行器的任务上(随 `dsh-bash` fiber dispose),它能跨越 `tool-bash` HMR 重载,关闭旧的 `XXX(tool-bash-owner-hmr)` 缺口。(`onTaskDone` 监听器仍受 `tool-bash` 的 `apply` effect 约束,因此落在重载间隙的完成仍会丢失一条通知——既有的重载间隙丢失——但所有权隔离本身已经不受 HMR 影响。) + +## 验证 + +以下不变式已经成立,并由测试固定: + +- ACP 断连或插件拆除后,任何由桥接层拥有的会话都不留下已注册 agent 或会话存储条目,包括与连接关闭竞争的创建流程。 +- 已入队的提示词启动前执行 `session/cancel`,能阻止该提示词运行;后来接受的提示词仍是独立的已入队轮次。 +- `tool-bash` HMR 重载不会使另一个会话能够读取或终止已有的后台任务(所有权保留在执行器上)。 +- 既有的非 ACP 演示无需显式管理 handle 仍能工作;由配置创建的 agent 仍归 `AgentLoop` 插件 fiber 所有。 + +## 会话所有者令牌在存活 agent 中唯一 + +bash 所有者 token 比较依赖共享的 `Agent.id`/`SessionId` 在存活 agent 中唯一。并发的同 ID 操作可以都私下准备,但发布会依次进入会话和 agent;`SessionStore.enter()` 拒绝重复的存活会话 id,每个失败事务都回滚自己的私有状态。因此程序化调用方无法发布两个共享同一会话 token 的存活 agent。访问*策略*(token 比较)留在消费方 `tool-bash`;bash seam 只存储不透明的 `owner` 字符串且从不解释它——这是正确的接口/实现/消费方拆分。 + +## 曾考虑的替代方案 + +- **公开的 `BashTask.owner` 字段**而非 `BashExecutor.ownerOf(id)` seam:否决。一条读取路径即可,无需冗余 API。 +- **为 agent 的会话生命周期使用兄弟 Cordis effect**:否决。fiber 卸载时并发释放兄弟 effect(`Promise.all`),store 拥有的 append 发布钩子的移除与循环的关闭 `session/flush` 产生竞争;单一复合 effect 的有序 LIFO 链才能在两条释放路径上都捕获关闭的 `turn/end`。 +- **在 `cancel()` 之外另设一个仅中止步骤的 `abort()`**:最初发布过,后因无人使用而移除;`cancel()` 是唯一的公开停止原语(见[公开停止接口 Agent Note](../simplification/2026-06-20-public-agent-stop-surface.md))。 + +## 后果 + +本变更有意触及公开接口(`Agent`、`AgentFactory`、bash seam),而非作为 ACP 的局部补丁。同步 `Agent.send()` 的简洁易用性得以保留;异步生命周期路径是增量添加的,供需要它的所有者使用。 diff --git a/.agents/notes/implemented/architecture/2026-06-18-session-surface.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-18-session-surface.i18n.yaml new file mode 100644 index 0000000000..4946fc219a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-18-session-surface.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-18-session-surface.md: 80034881d0112076759a68737b5931c8ff659d15 +2026-06-18-session-surface.zh.md: 26a3119faf0b6988049a7599ea9551a8ae65d63d diff --git a/.agents/notes/implemented/architecture/2026-06-18-session-surface.md b/.agents/notes/implemented/architecture/2026-06-18-session-surface.md index f1297b1f05..80034881d0 100644 --- a/.agents/notes/implemented/architecture/2026-06-18-session-surface.md +++ b/.agents/notes/implemented/architecture/2026-06-18-session-surface.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-18-session-surface.zh.md) + ## Problem The event log is authoritative, but history manipulation had no durable shared mechanism. Plugins such as compaction would otherwise rewrite derived requests through order-sensitive listeners, leave no provenance, and require repeated changes to `deriveMessages()`. diff --git a/.agents/notes/implemented/architecture/2026-06-18-session-surface.zh.md b/.agents/notes/implemented/architecture/2026-06-18-session-surface.zh.md new file mode 100644 index 0000000000..26a3119faf --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-18-session-surface.zh.md @@ -0,0 +1,73 @@ +# Agent Note: 会话 surface:事件日志上的有序投影 + +Status: implemented + +[English](2026-06-18-session-surface.md) | 中文 + +## 问题 + +事件日志是权威数据源,但历史操纵此前没有持久化的共享机制。如果没有这样的机制,上下文压缩(context compaction)等插件只能通过顺序敏感的监听器改写派生请求,不留溯源信息,且每次新增操纵都要反复修改 `deriveMessages()`。 + +## 决策 + +新增一个 **surface**:事件 seq 的派生、缓存有序投影(即产出 LLM(大语言模型)消息的事件子集),通过事件日志中的 `surfaceOp` 标记维护。 + +### `SessionEvent` 新增两个顶层字段 + +每个 `SessionEvent` 获得两个可选字段(结构性元数据,与 `seq`/`time` 同级): + +- **`sourceEventSeqs?: number[]`**:作为溯源来源的事件 seq 编号(例如构成 `assistant/message` 的各 `assistant/chunk` 的 seq,或被压缩标记遮蔽的 surface 节点)。出现的 `[]` 只在 `assistant/message` 上有效,表示已知为空的提供方流;在该事件上省略字段表示旧数据或未记录的溯源。其他 surface 事件一旦出现此字段,就必须是非空列表。溯源是核心设计原则;没有它,replace-range 操作在回放时无法被验证。 +- **`surfaceOp?: SurfaceOp`**:该事件如何进入 surface。非 surface 事件不携带此字段。 + +### SurfaceOp:两种操作 + +```ts +export type SurfaceOp = + | 'append' // normal tail append + | { op: 'replace'; start: number; end: number } // shadow [start, end] inclusive +``` + +1. **Append**:在尾部追加新事件的 seq。`user/message`、`assistant/message`、`tool/result`、`context/message`、`steering/message` 使用此操作。agent loop(智能体循环)在所有此类追加上传入 `surfaceOp: 'append'`,并在适用时记录 `sourceEventSeqs`:每个成功的 `assistant/message` 都记录完整的 `assistant/chunk` 来源集合(包括 `[]`),而 `tool/result` 记录其 `tool/call` 来源。 + +2. **Replace**:移除从 `start` 到 `end`(两端包含)的条目,并在其位置插入新事件的 seq。`start` 和 `end` 都必须存在于当前 surface;`start === end` 表示替换单个条目。该事件的 `sourceEventSeqs` 必须包含所有被遮蔽的 surface seq。被遮蔽的事件仍留在日志中,但不再出现在 surface 上。 + +### SurfaceManager:基于增量,而非全量重建 + +一个 `Session` 拥有一个 `SurfaceManager`,后者维护事件 seq 的有序 `number[]`。管理器会在提交前校验每个种子或追加候选项而不应用它,然后只处理上次同步之后已经提交的事件,而不重新扫描整个日志。`Session.surface` 通过只读的 `SessionSurface` 契约暴露同一个管理器,因此接纳、派生历史、压缩与工作区上下文共享同一份增量状态。Replace 按数组位置找到两端都包含的端点,并把替换 seq splice 到该范围;不会用第二个管理器、链接对象或 seq 到节点的 map 来重复表达顺序。 + +无新事件时增量处理为 O(1),有新事件到达时为 O(新事件数)。 + +`deriveMessages()` 在存在 surface 标记时使用 surface,对没有标记的会话回退到既有的线性扫描(向后兼容)。 + +### 持久化 + +新字段作为顶层 JSON 属性序列化。JSONL 后端无需任何改动:`JSON.stringify`/`JSON.parse` 透明地保留一切。SQLite 后端的 `events` 表新增两个可空 TEXT 列(`source_event_seqs`、`surface_op`)。磁盘上的 `SCHEMA_VERSION` 递增以反映列集变化,并且按照预发布的 bump-and-reject 策略,由其他构建写入的数据库在打开时被拒绝而非迁移(没有需要升级的持久化用户数据)。会话格式 `version` 固定为 `SESSION_FORMAT_VERSION = 0`(「不稳定/预发布」立场):可选的 surface 字段被吸收而不递增版本号。 + +### 崩溃恢复 + +`repair.ts` 模块在崩溃后为孤立的工具调用合成 `tool/result` 闭合事件。这些闭合事件携带 `surfaceOp: 'append'` 和指向孤立 `tool/call` 事件的 `sourceEventSeqs`,确保重建的 surface 有效。 + +### 不变式 + +`Session` 在始终启用的 seed/append 边界校验 `sourceEventSeqs` 与 `surfaceOp`:只有 `assistant/message` 可以使用空的溯源列表;引用必须唯一、更早且已知;替换端点必须存在于 surface 顺序中;溯源必须覆盖每个被遮蔽的节点。这些是单记录接纳与存储投影规则,不是可选的不变式服务贡献。 + +每个 surface 可达事件都必须携带 `surfaceOp`,否则它将从派生历史中消失。类型化的 `append` 重载对字面事件类型强制执行此规则;`append` 和种子构造函数中的运行时检查覆盖宽化联合类型和加载的日志。按照预发布格式策略,无效的种子被拒绝而非升级。 + +## 曾考虑的替代方案 + +- **逐插件的 `agent/request` 包装**(surface 之前的历史操纵模式):监听器排序脆弱、无法持久记录改动内容,且每种新操纵都迫使核心 `deriveMessages()` 再次修改。 +- **半开区间 `[start, endExclusive)` 的 replace 范围**:否决。端点由 surface 事件 seq 命名,单条目替换(`start === end`)在闭区间语义下读起来更自然。 +- **链接节点对象加 seq map**:否决。生产代码不读取前驱链接,唯一的后继用途就是数组中的下一个位置,而替换本来就需要线性 `indexOf` 查找。单个 seq 数组在保留相同渐进复杂度的同时,只留下一个需要校验的表示。 +- **脏标记后全量重建**替代增量处理:在会话生命周期内为 O(N²),每次单事件追加都要重新扫描所有先前事件。 + +## 后果 + +- **`packages/core/session`**:`surface.ts`(`SurfaceManager`)维护一个用于候选接纳和实时投影的有序 seq 数组;`SessionSurface` 是其只读公共视图。`SurfaceOp`/`SurfaceIntent` 与顶层会话事件字段记录条目如何加入它。`append()` 要求 surface 事件携带 `SurfaceIntent`,`deriveMessages()` 以遍历 surface 作为唯一派生路径,`repair.ts` 则发出 surface 感知的闭合事件。种子构造函数拒绝缺少 `surfaceOp` 标记的 surface 可达种子事件(见「不变式」一节)。 +- **`packages/core/agent-loop`**:所有 surface 可达的追加操作传入 surface 选项。收集分片 seq 用于 `assistant/message` 溯源;捕获 `tool/call` seq 用于 `tool/result` 溯源。 +- **`packages/session-persistence/session-persistence-sqlite`**:`events` 表新增两个可空 TEXT 列(`source_event_seqs`、`surface_op`);`SCHEMA_VERSION` 递增(bump-and-reject,无迁移)。 +- **`packages/session-persistence/session-persistence-jsonl`**:无需改动。 +- **`packages/session-persistence/session-persistence`**:抽象接口不变。 + +Surface 是未来历史操纵的基础。压缩或 tool-result-prune 插件追加一个既有的消息产出事件类型(例如一条携带摘要的 `user/message`),附带 `surfaceOp: { op: 'replace', start, end }` 和覆盖被遮蔽条目的 `sourceEventSeqs`——新事件在 surface 上取代该范围的位置,而插件自身的 trace 事件(如 `compaction/start`、`compaction/end`)不进入 surface。回放以确定性方式保留该决策。 + +一次 `tool/result` 替换只能改写当前的一个 `tool/result`,并且必须保留除 `content` 以外的每个数据字段。Session 接纳会与位置范围和溯源校验一起强制这条规则,不依赖可选的诊断插件。 diff --git a/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.i18n.yaml new file mode 100644 index 0000000000..b289d47edd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-18-shared-persistence-write-coordinator.md: ea9c4fb74f7c1bd68fb62efedd3e1657da96ea65 +2026-06-18-shared-persistence-write-coordinator.zh.md: 3b4dd7b762c2f39a908eabe23e5d734981b5767b diff --git a/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md b/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md index 48b1bfa45f..ea9c4fb74f 100644 --- a/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md +++ b/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-18-shared-persistence-write-coordinator.zh.md) + ## Problem `dsh-session-persistence-jsonl` and `dsh-session-persistence-sqlite` intentionally prove the same `SessionPersistence` contract over different storage media, but their write-path orchestration was duplicated: per-session state, `session/created` adoption, backend-specific prefix reads, write-behind control, per-id operation serialization, HMR seeding, and dispose drains. The pure seed-prefix collision and serializability guards had already moved into the seam package; the remaining orchestration was still correctness-heavy and received the same fixes twice. Only the storage primitives (write bytes vs. INSERT rows) differed. diff --git a/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.zh.md b/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.zh.md new file mode 100644 index 0000000000..3b4dd7b762 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.zh.md @@ -0,0 +1,47 @@ +# Agent Note: 共享持久化写入协调器 + +Status: implemented + +[English](2026-06-18-shared-persistence-write-coordinator.md) | 中文 + +## 问题 + +`dsh-session-persistence-jsonl` 与 `dsh-session-persistence-sqlite` 有意在不同存储介质上证明同一份 `SessionPersistence` 契约,但它们重复实现了写入路径编排:每会话状态、`session/created` 接管、后端特定的前缀读取、write-behind 控制、按 id 串行执行操作、HMR(热模块替换)种子注入与 dispose(资源释放)排空。纯粹的种子前缀碰撞检查与可序列化守卫已迁入 seam 包;剩余的编排仍然对正确性要求很高,且同样的修复被应用了两次。唯一的差异在于存储原语(写字节 vs. INSERT 行)。 + +## 决策 + +将一个后端无关的 `PersistenceCoordinator` 提取到 `dsh-session-persistence` 中。协调器统一拥有编排逻辑;每个第一方后端组合一个协调器实例(`new PersistenceCoordinator(ctx, this)`),实现一个小型 `PersistenceBackend` 钩子接口,并将其有状态的公开方法(`create`/`append`/`load`/`inspect`)委托给协调器。由后端拥有的元数据与修订版本列举会绕过协调器。 + +组合,而非继承。协调器是后端持有的具体类,不是后端继承的基类。本 Agent Note 的风险——「协调器不得让非常规后端与继承层级作斗争」——由此规避:后端只暴露钩子,无法触及协调器的私有编排状态。第三方后端仍然可以完全不使用协调器、直接实现抽象服务,包括供读模型使用、不修改状态的 `inspect` 契约。 + +协调器为每个确切的存活 `Session` 持有一个控制器;该控制器统合初始化、待处理事件与共享 flush promise。每个 `session/event` 都会立即启动排空,而 `session/flush` 只观察完全停稳,不会发起常规写入路径。[flush 控制器简化](../simplification/2026-07-23-collapse-persistence-flush-state.md)定义该生命周期。 + +协调器通过 `session/disposed` 退役会话:它等待控制器完成初始化和当前 flush,串行执行最后一次排空,且仅在成功后才移除控制器与其拥有的每 id 状态。失败时保持控制器可被找到,以供后端 teardown(拆除)重试。每个 id 的已结算链尾仅在其仍是当前链尾时才移除自身,因此旧操作完成后不会抹除同一 id 的新操作。后端 teardown 会注销写入路径监听器、flush 每个剩余的控制器、等待所有按 id 串行化的操作,最后关闭后端。 + +### 钩子接口(`PersistenceBackend<TornMarker>`) + +五个必需成员加一个可选的生命周期钩子,构成协调器与存储之间唯一的边界: + +- `name`——后端标签,用于 dispose 失败时的 `AggregateError`。 +- `loadStored(id)`——按 id 跨所有存储范围读取一个已存储前缀(JSONL 的所有 cwd bucket;SQLite 的 id 全局唯一)。恢复/加载、不修改状态的检查、存活会话接管与创建碰撞探测共用此查找。协调器会断言返回的 id,并在修复或发布状态之前拒绝已存储记录与存活会话的 cwd 不匹配。 +- `appendBatch(meta, events, isMaterialized)`——持久追加一个连续批次,在尚未物化时原子地惰性物化会话(物化写入与首批事件必须一起提交——崩溃不得留下一个已物化但为空的会话;这就是为什么没有单独的 `materialize` 钩子)。 +- `commitRepair(meta, tornMarker, closers)`——使崩溃修复持久化:截断损坏的尾部(当且仅当 `tornMarker !== undefined`)并追加 `closers`。**不要求原子性**——JSONL 合理地分两步 fsync(先截断再追加),SQLite 在一个事务中完成 DELETE+INSERT。用于 `load`(截断 + 合成 closers)和 live-adoption(仅截断,`closers = []`)。 +- `list()`——列出所有已存储的元数据。 +- `close?()`——可选的生命周期清理(SQLite 关闭 db 句柄;JSONL 省略),在 dispose effect 中于排空至完全停稳之后被 await,因此 close 失败不会掩盖排空错误。 + +### 不透明的 torn marker + +保持 seam 整洁的唯一设计选择:崩溃修复中「损坏尾部在哪里」的 token 对协调器是不透明的。协调器计算合成 closers(它拥有来自 `dsh-session` 的 `interruptedTurnClosers`),但它只测试 `tornMarker !== undefined` 并将值原样传回 `commitRepair`——从不检视其内容。每个后端选择自己的 marker 类型:JSONL 携带要截断到的字节偏移,以及从不完整最终帧中解码出的任何完整事件;SQLite 则携带要从其开始删除的 seq。协调器因此既不了解字节长度,也不了解帧恢复状态。 + +## 测试 + +共享的 `runPersistenceContract`(公开 API 契约)为每个后端运行,并证明在 `load` 执行恢复之前,`inspect` 会保持被中断的日志与修订版本不变。`runCoordinatorContract`(`tests/coordinator-contract.ts`)通过内存参考实现、JSONL 与 SQLite 覆盖接管、HMR、碰撞、会话与后端 dispose 排空,以及崩溃尾部修复。协调器专属测试覆盖立即执行的后续批次、存活控制器清理、同 id 链尾竞态、排空失败重试与关闭顺序。各后端自身的测试规格只保留存储机制。每个真实后端都有一个经由协调器的崩溃尾部修复测试,以覆盖不透明 marker 分支,因为契约中的崩溃用例会产生合成 closers,却不会产生 torn marker。 + +## 曾考虑的替代方案 + +- **后端继承的基类**——否决,改用组合:后端只暴露钩子,无法触及协调器的私有编排状态,且第三方后端仍可完全不使用协调器、直接实现抽象服务。 +- **更宽的钩子面**——每个候选钩子都被折叠掉:没有限定存储范围的实时查找,因为 `loadStored` 加上协调器的 cwd 检查即可维持碰撞边界;没有存储定位器泛型,因为经验证的 JSONL 元数据可还原其路径,而 SQLite 已按 id 绑定;没有单独的 `materialize` 钩子,因为首批事件必须与物化原子提交;没有单独的创建碰撞探测,因为它就是 `loadStored(id) !== undefined`;`list()` 也不经由协调器透传,因为列举不需要任何编排。 + +## 后果 + +协调器增加了一层间接、一个不透明的 torn marker 和脱离会话生命周期的退役任务,但将此前每个后端重复的、对正确性要求很高的编排逻辑集中到一处。会话 dispose 仍是仅观察事件,因此会话所有者不会等待持久化退役;协调器会收容失败、在存活控制器中保留待处理事件,并以后端 teardown 为完全停稳边界。其钩子面保持窄小:标识校验、接管、碰撞检查与不修改状态的检查共用 `loadStored`;物化保持在 `appendBatch` 内原子完成;列举绕过协调器。读模型使用 `inspect` 而非 `load`,因此观察已持久化但仍开放的轮次时,不会因提交中断 closers 而与新的存活所有者产生竞态。新后端只需实现存储原语,而无需复制立即写入生命周期。 diff --git a/.agents/notes/implemented/architecture/2026-06-20-branded-ids.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-20-branded-ids.i18n.yaml new file mode 100644 index 0000000000..04f7dcb1a3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-20-branded-ids.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-branded-ids.md: 7c0b7ca89418e8312ec728223dac519f70edc3ed +2026-06-20-branded-ids.zh.md: 8b41ad3c3c85690fb03b20a208f8460a1614477b diff --git a/.agents/notes/implemented/architecture/2026-06-20-branded-ids.md b/.agents/notes/implemented/architecture/2026-06-20-branded-ids.md index e7a3110fce..7c0b7ca894 100644 --- a/.agents/notes/implemented/architecture/2026-06-20-branded-ids.md +++ b/.agents/notes/implemented/architecture/2026-06-20-branded-ids.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-branded-ids.zh.md) + ## Problem The harness brands `CallId` (`packages/llm/llm/src/brand.ts`) and the shared agent/session `SessionId` (`packages/core/session/src/types.ts`) using the `Branded<B> = string & { readonly [BRAND]: B }` machinery (owned by the type-only `@deepseek-ai/dsh-brand` package at `packages/util/brand/` — see its [README](../../../../packages/util/brand/README.md)) and a zero-cost cast factory per type. `dsh-brand` also states the governing policy: *"Branding is for ids that cross package boundaries and could plausibly be confused; not every string needs a brand."* That policy is right; the problem is that it is only half-applied. Two gaps let a structurally-identical-but-semantically-wrong string slip through the type checker today. @@ -10,7 +12,7 @@ The harness brands `CallId` (`packages/llm/llm/src/brand.ts`) and the shared age The bash **owner token** is the related sub-case: `BashExecRequest.owner?: string` and `BashExecSpec.owner: string | undefined` (`packages/bash/bash/src/types.ts`) are documented as a deliberately *opaque* isolation key, but in every live caller the value IS the owning agent's shared `Agent.id`/`SessionId` (`callerToken = (exec) => exec.agent?.id` in `packages/bash/tool-bash/src/index.ts`) wearing a different seam-local name. It is compared for access control (`owner !== callerToken(exec)`), so a mismatched-but-well-typed string here is a cross-session isolation bug the type system currently cannot catch. This is the shared id alias covered by the [unified agent/session identity decision](../simplification/2026-06-20-unify-agent-and-session-id.md). -**Gap 2 — brand erosion at the seams of the *already-branded* IDs.** Even `CallId` and `SessionId` decay back to bare `string` at exactly the places confusion is most likely: registry/store key types and public method params. Representative sites include the session store, the agent registry (both keyed by the shared `SessionId`), `ToolPresenter`'s call-id map, ACP's session-id records and loading set, and the persistence coordinator. A brand that is dropped at a collection key buys nothing on lookups — the value of the existing brands is partly unrealized. +**Gap 2 — brand erosion at the seams of the *already-branded* IDs.** Even `CallId` and `SessionId` decay back to bare `string` at exactly the places confusion is most likely: registry/store key types and public method params. Representative sites include the session store, the agent registry (both keyed by the shared `SessionId`), tool-presentation call-id maps, ACP's session records, and the persistence coordinator. A brand that is dropped at a collection key buys nothing on lookups — the value of the existing brands is partly unrealized. ## Decision diff --git a/.agents/notes/implemented/architecture/2026-06-20-branded-ids.zh.md b/.agents/notes/implemented/architecture/2026-06-20-branded-ids.zh.md new file mode 100644 index 0000000000..8b41ad3c3c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-20-branded-ids.zh.md @@ -0,0 +1,69 @@ +# Agent Note: 在所有应有之处使用 branded ID + +Status: implemented + +[English](2026-06-20-branded-ids.md) | 中文 + +## 问题 + +harness 使用 `Branded<B> = string & { readonly [BRAND]: B }` 机制,为 `CallId`(`packages/llm/llm/src/brand.ts`)和 agent/会话共享的 `SessionId`(`packages/core/session/src/types.ts`)做 brand 处理;该机制由纯类型包(package) `@deepseek-ai/dsh-brand` 拥有,位于 `packages/util/brand/`,见其 [README](../../../../packages/util/brand/README.md),并为每个类型提供零开销的 cast 工厂。`dsh-brand` 还声明了治理策略:*「Branding 用于跨包边界且可能被混淆的 id;不是每个 string 都需要 brand。」* 这条策略是正确的;问题在于它只落实了一半。两处缺口使得结构相同但语义错误的 string 今天仍能通过类型检查器。 + +**缺口 1:bash seam 中未 brand 的跨边界 ID。** 后台 task id 是普通 `string`:`BashTask.id: string`(`packages/bash/bash/src/types.ts`),作为 `string` 贯穿整个执行器 seam(`packages/bash/bash/src/index.ts` 中的 `BashExecutor.get`/`ownerOf`/`readOutput`/`kill(id: string)`),再由面向模型的工具以 `string` 校验并传递(`validateTaskId`、`assertTaskAccess`、`packages/bash/tool-bash/src/index.ts` 中 `task_id` 的 schema 参数)。它由每执行器计数器生成——`packages/bash/bash-local/src/index.ts` 中的 `` `bash-${this.nextTaskId++}` ``——其形状与 `SessionId` 的默认值**完全相同,都是 `name-N`**(`packages/core/session/src/index.ts` 中的 `` `session-${++counter}` ``)。bash task id 和会话 id 在调用点轻易就能互换,而编译器毫无反应。这是用户询问的核心案例,并且它是面向模型的 id(模型会把 `task_id` 传回 `bash_output`/`bash_kill`),所以该混淆可由不受信任的输入触达。 + +bash **owner token** 是相关的子情形:`BashExecRequest.owner?: string` 和 `BashExecSpec.owner: string | undefined`(`packages/bash/bash/src/types.ts`)被文档描述为刻意*不透明*的隔离键,但在所有实际调用方中,该值就是所属 agent(智能体)共享的 `Agent.id`/`SessionId`(`callerToken = (exec) => exec.agent?.id`,位于 `packages/bash/tool-bash/src/index.ts`),只是披着另一个 seam 本地名称。它被用于访问控制比较(`owner !== callerToken(exec)`),因此一个不匹配但类型正确的 string 在此处就是跨会话隔离 bug,而当前类型系统无法捕获。这正是[统一 agent/session 标识决策](../simplification/2026-06-20-unify-agent-and-session-id.md)覆盖的共享 id 别名。 + +**缺口 2:*已经 brand* 的 ID 在 seam 处被侵蚀。** 就连 `CallId` 和 `SessionId` 也恰好在最容易混淆的地方退化为裸 `string`:注册表/store 键类型和公开方法参数。代表性位置包括会话存储、agent 注册表(二者都以共享的 `SessionId` 为键)、工具展示层的 call-id map、ACP 的会话记录,以及持久化协调器。在集合键处丢弃 brand,会让既有 brand 在查找时毫无价值;它们的价值只实现了一部分。 + +## 决策 + +纯类型变更。Brand 是零开销 cast;运行时行为、序列化、比较和协议格式(wire format)均不变。工作分三部分,全部遵循既有的「不是每个 string 都需要」策略。 + +- **为 bash task id 加 brand。** 在 `packages/bash/bash/src/types.ts`(*拥有*该 id 的包)中添加 `BashTaskId = Branded<'BashTaskId'>` 及其同名工厂,从 `@deepseek-ai/dsh-brand` 导入 `Branded`,方式与 `SessionId` 完全一致。brand 原语位于无依赖的 `dsh-brand` 工具包中,正是为了让 `dsh-bash` 仅依赖它就能为自己的 id 加 brand,而无需引入 `dsh-llm`(或 `dsh-session`)来获取 `Branded`。将其贯穿 `BashTask.id`、`BashExecutor` seam 方法(`get`/`ownerOf`/`readOutput`/`kill`)、`dsh-bash-local` 中的生成点(在创建时对计数器输出做一次 brand),以及 `dsh-tool-bash` 的校验/访问面(`validateTaskId` 返回 `BashTaskId`;`task_id` 在模型 string 到达的工具边界处被 brand)。 + +- **铸造独立的 `OwnerToken` brand。** 在 `packages/bash/bash/src/types.ts` 中添加 `OwnerToken = Branded<'OwnerToken'>`;将 `BashExecRequest.owner` / `BashExecSpec.owner` / `BashExecutor.ownerOf` 的类型标注为 `OwnerToken | undefined`。`dsh-tool-bash` 消费方在边界处将 agent 共享的 `id`(`SessionId`)cast 为 `OwnerToken`——这是两套词汇唯一交汇的地方。bash seam 从不导入 `dsh-session`。(理由见下一节。) + +- **阻止 brand 侵蚀。** 将既有 brand 传播到缺口 2 列出的 `Map` 键类型和公开方法参数中:`Map<SessionId, Session>`、`Map<SessionId, Agent>`、`get(id: SessionId)`、`Map<CallId, …>`、ACP 的 `SessionId` surface、协调器的 `Map<SessionId, …>`。这是 diff 中机械量最大的部分,也是让*既有* brand 在查找处真正发挥作用(而不仅仅标注在结构体字段上)的关键。 + +示意形状(工厂模式与已有的三个 brand 完全一致): + +```ts ignore-check +import type { Branded } from '@deepseek-ai/dsh-brand' + +/** A background bash task handle (generated `bash-N` by the local executor). */ +export type BashTaskId = Branded<'BashTaskId'> +export function BashTaskId(id: string): BashTaskId { + return id as BashTaskId +} + +/** A bash task's opaque isolation key — the consumer's owner identity, NOT the bash seam's. */ +export type OwnerToken = Branded<'OwnerToken'> +export function OwnerToken(id: string): OwnerToken { + return id as OwnerToken +} +``` + +## 曾考虑的替代方案 + +### 为什么不把 `owner` 类型标注为 `SessionId`? + +显而易见的捷径是直接把 `owner` 类型标注为 `SessionId`——它确实*总是*一个会话 id。我们否决这个方案。bash 执行器 seam 是能力 seam(接口 `dsh-bash`、实现 `dsh-bash-local`、消费方 `dsh-tool-bash`),其 owner token 被*明确记录为刻意不透明*:执行器「从不解释它(seam 中没有访问策略——那是消费方的职责)」(`packages/bash/bash/src/types.ts`)。把 seam 字段类型标注为 `SessionId`,会把 `dsh-session` 的词汇引入一个不应知道 owner token *含义*的包——这会让通用执行后端耦合会话模型,并违背不透明 token 的设计。取代 `dsh-bash-local` 的沙箱或远程执行器不应继承会话依赖。独立的 `OwnerToken` brand 使 seam 保持解耦:`dsh-bash` 只知道「owner 是某种带 brand 的不透明 token」,而已经决定访问策略的 `dsh-tool-bash` 消费方,是把其 `SessionId` cast 为 `OwnerToken` 的唯一边界。该 brand 仍带来安全收益(不能把 `BashTaskId` 或裸 string 传到 owner 位置),且不引入耦合。 + +## 不在范围内 / 可能的扩展 + +遵循「不是每个 string 都需要 brand」的策略,刻意保持窄范围。以下每项都是合理的未来 brand 候选,附带推迟理由而非承诺: + +- **`ModelId`**(`GenerateOptions.model`,`LlmService` 适配器注册表的键):一个真正的跨包查找键(config → agent → llm → 适配器);合理的下一个 brand,仅为控制本 Agent Note 的影响范围而暂不纳入。 +- **`ToolName`**(`ToolRegistry` 的键):由作者定义、人类可读,且很少与其他 id 混淆;最弱的候选,可能不值得加 brand。 +- **`ErrorCode`**(`HarnessError.code`):一个封闭词汇(`ABORTED`、`NO_ADAPTER`……),不是逐实例的 id;如果要做,string 字面量联合类型比 brand 更合适。 +- **数值序号**:轮次号、步骤号和事件 `seq` 是 `number` 而非 `string`,`Branded<string>` 不适用;可以用并行的 `number & { readonly [BRAND]: B }` 变体来 brand 它们,但它们是位置序号、很少跨边界传递,收益较低。 +- **带校验的构造**:brand 工厂是纯 cast,无运行时检查,且每个边界(ACP `sessionId`、提供方签发的 `call.id`、`dsh-llm-deepseek` 中的空字符串回退)今天都信任裸 string。一个在边界处对格式错误的输入抛异常的 `SessionId.parse()` / `isValid()` 配套工具确实是缺口,但它是*运行时行为*变更,有自己的设计问题(什么算「格式错误」?失败时怎么办?),应在独立 Agent Note 中处理,不应捆绑进这次纯类型变更。 + +## 验证 + +已落地的不变式:`BashTaskId` 和 `OwnerToken` 定义在 `dsh-bash` 中,并端到端贯穿执行器 seam、`dsh-bash-local` 生成点与 `dsh-tool-bash` 面向模型的 surface,且 `dsh-bash` 未添加对 `dsh-session` 的依赖;没有任何以范围内 brand id(`CallId`/`SessionId`/`BashTaskId`)为键的集合使用裸 `string`;公开方法参数和导出签名保留 brand;每个原始 string 进入的边界(提供方 call id、ACP 会话 id、模型提供的 `task_id`)都通过 cast 工厂构造 brand,而不是散落的 `as` cast。 + +## 后果 + +- **两个接口面的机械性改动。** 传播 brand 涉及 bash seam(接口 + 实现 + 消费方)以及 ACP 会话 id 接口和持久化协调器。改动面广但严重度低:遗漏的位置是编译错误而非静默 bug。变更可观察地为纯类型变更——无快照或 e2e 行为差异。它与[统一 agent/会话标识决策](../simplification/2026-06-20-unify-agent-and-session-id.md)相邻,因为二者都触及会话 id / owner-token 边界;`OwnerToken` 出于上述解耦理由仍与统一后的 id 保持独立。 +- **Brand 不做校验。** Brand 是混淆防护,不是正确性证明:一个*错误的* 会话 id 只要仍是合法的 string,就和以前一样能通过类型检查器。本 Agent Note 不关闭这个缺口(见「不在范围内」)——它只阻止这类*类别*错误:传入错误*种类*的 id。 +- **「在哪里停下」仍是判断题。** 为 `BashTaskId` 加 brand 但不为 `ToolName` 加,为 `OwnerToken` 加但不为 `ModelId` 加,是对哪些 string「可能被混淆」的品味判断。合理的评审者可能想要更多或更少;`brand.ts` 中的策略是裁决依据,本 Agent Note 倾向于面向模型或用于访问控制的 id。 diff --git a/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.i18n.yaml new file mode 100644 index 0000000000..a27551cd40 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-extract-example-app-packages.md: f2853db3f454d71572be003cfbf4f6dfd8377cdd +2026-06-20-extract-example-app-packages.zh.md: 58d3d95996b1dacbc12178b46524374429df71ed diff --git a/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.md b/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.md index 953a977c19..f2853db3f4 100644 --- a/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.md +++ b/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-extract-example-app-packages.zh.md) + ## Problem An example folder is supposed to be *thin* — the variable wiring of a demo, not the demo's machinery. Before this change it was thick. Each example carried a hand-rolled `start.ts` boot bootstrap, an infra preamble (`timer`, and — for the stdio demos — `logger` + `hmr`), nested includes of three shared YAML fragments (`base.yml` / `base-core.yml` / `acp-agent/acp-tail.yml`), and per-example `agent-loop`/persistence/system-prompt config. The actual app — the spine of services every agent needs — was spread across the leaf and those includes. @@ -40,7 +42,7 @@ The old `base*.yml`/`acp-tail.yml` includes already deduped the *config*, but a - Example directories contain only their config, README, and tests: `start.ts`, the infrastructure preamble, and the shared YAML includes are gone. - `demo:tui`, `demo:headless`, and `demo:acp` invoke the app-package bins. - Each new package has a README and per-file 100% coverage; each app package also has a keyless real-Loader-path bin smoke that catches export-shape failures described in [postmortem 0001](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md). -- The ACP replay transcript remains unchanged because the plugin set and load order did not change. +- The ACP replay suite boots through the app-package bin, so protocol wiring and assembled backend behavior cross the real Loader boundary. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.zh.md b/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.zh.md new file mode 100644 index 0000000000..58d3d95996 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.zh.md @@ -0,0 +1,57 @@ +# Agent Note: 将示例应用提取为独立包 + +Status: implemented + +[English](2026-06-20-extract-example-app-packages.md) | 中文 + +## 问题 + +示例目录本应是*精简的*——只包含演示的可变接线,而非演示的基础设施。在此次变更之前,它是臃肿的。每个示例都携带一份手写的 `start.ts` 启动引导、一段基础设施前导(`timer`,以及 stdio 演示所需的 `logger` + `hmr`(热模块替换))、三个共享 YAML 片段的嵌套引用(`base.yml` / `base-core.yml` / `acp-agent/acp-tail.yml`),还有各示例自身的 `agent-loop`/持久化/系统提示词配置。真正的应用——每个 agent(智能体)都需要的服务主干——散落在叶子配置和那些 include 中。 + +叶子配置还拥有耦合的前门。ACP(Agent Client Protocol)要求 stdout 纯净,并通过 `session/new` 创建 agent;终端应用和 Headless 应用则预创建 `main`,但进程 I/O 契约不同。防止错误组合的唯一屏障是文档中的文字警告,而三个 `start.ts` 文件重复着 Loader 引导和生命周期代码。 + +## 决策 + +每个示例现在**主要是对一个应用包(package)的调用**,沿着既有的[接口 / 实现 / 消费方 seam](2026-06-13-capability-seams.md) 拆分接线:**应用包拥有组合**,叶子 `cordis.yml` 只拥有**可替换的选择**(哪个 LLM(大语言模型)适配器、哪个 bash 执行器、模型、提示词、持久化根目录)。 + +- **`@deepseek-ai/dsh-agent-spine-demo`**([packages/examples/agent-spine-demo](../../../../packages/examples/agent-spine-demo))组合了不含提供方、不含执行器、不含 UI 的主干,并转发 agent loop(智能体循环)的 agent 列表配置。它对具体 loop 的依赖是有意为之,因为该包组合的是主干而非扩展主干;替换 loop 意味着提供另一个 bundle。 +- **`@deepseek-ai/dsh-tui-demo`**、**`@deepseek-ai/dsh-cli-demo`** 和 **`@deepseek-ai/dsh-acp-demo`** 各自内置其进程角色。TUI 包含全屏 UI 和预创建的 `main`;Headless 包含 one-shot driver 和预创建的 `main`;ACP 包含 bridge 且不预创建 agent。三者都包含 JSONL 持久化,并省略 stdout logger。 +- **`start.ts` 已移除。** 每个应用包都暴露一个 bin;`demo:*` 脚本调用它。Loader 引导、`.env` 加载和快速失败守卫位于共享的 [`@deepseek-ai/dsh-app-boot`](../../../../packages/ui/app-boot) 包(在逐文件覆盖率门禁下有单元测试——见[共享应用 bin 的启动胶水](../simplification/2026-07-04-share-app-bin-boot-glue.md));精简的自执行入口由 keyless 的 Loader 路径测试驱动。 +- **每个叶子 `cordis.yml` 精简为**后端、可选产品工具,以及一个承载应用配置的 app 条目。TUI 和 Headless 把模型/会话选择路由到预创建的 agent;ACP 把初始提供方/模型路由到 bridge。 +- **`base.yml`、`base-core.yml` 和 `acp-agent/acp-tail.yml` 已退役**——它们共享的主干现在位于 `dsh-agent-spine-demo` 中。 + +`bash-local` 和 LLM 适配器仍然是**叶子选择**:bundle 提供 `tool-bash`(消费方 schema),叶子选择执行器实现,因此沙箱执行器或回放适配器无需触碰应用即可替换。 + +### 实现修正:`hmr` 保留为叶子条目 + +提案最初将 `hmr` 列入交互式应用内置的前门集群。对照代码验证后发现,将 `hmr` 内置到应用包中会在两个方面与 Cordis 冲突,因此改为作为**叶子 `cordis.yml` 条目**交付: + +1. `@cordisjs/plugin-hmr` 是一个仅限 Loader、仅限子进程的开发插件——它需要活跃的 `loader` 服务及其内部模块访问权限,因此只能在真实的 `demo:*`/bin 子进程中运行,不能在进程内的单元/覆盖率测试层运行。 +2. 进程内测试层(vitest)甚至无法*导入* vendor 的 `hmr` 模块(其 class-decorator `@Inject` 形式在 Vite 的 transform 下会失败),因此一个 `apply` 静态导入了它的包永远无法满足其主函数的逐文件 100% 覆盖率门禁。 + +关键在于,`hmr` 不是 stdout 纯净隐患:ACP 配置中误加该条目不会破坏 JSON-RPC 帧。所有已交付应用都省略 stdout 控制台 logger;stdout 只归应用或协议 driver 所有。 + +## 曾考虑的替代方案 + +### 为什么不继续用共享 YAML include 来管理接线? + +旧的 `base*.yml`/`acp-tail.yml` include 已经去重了*配置*,但 YAML include 无法**封装**前门耦合——它只能在注释中描述,并信任每个叶子遵守。它也无法拥有 `bin`,因此启动胶水一直在三个 `start.ts` 文件中重复。包将「ACP 应用绝不向 stdout 输出日志」从文字警告变成了产物的属性:叶子中不存在可以写错的 logger 条目。 + +## 验证 + +- 示例目录只包含配置、README 和测试:`start.ts`、基础设施前导和共享 YAML include 已移除。 +- `demo:tui`、`demo:headless` 和 `demo:acp` 调用应用包的 bin。 +- 每个新包都有 README 和逐文件 100% 覆盖率;每个应用包还有一个 keyless 的真实 Loader 路径 bin 冒烟测试,用于捕获[事后分析 0001](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md) 中描述的导出形状故障。 +- ACP 回放套件通过应用包的 bin 启动,因此协议接线与组装后的后端行为都跨越真实的 Loader 边界。 + +## 后果 + +- **裸插件树的教学性。** 主干现在隐藏在 bundle 之后,查看完整树意味着打开 `dsh-agent-spine-demo`。应用包的 README 承担了这份教学职责。 +- **多了一层间接。**「这个演示加载了什么?」从扫描单个 YAML 变成了阅读一个包。 + +## 相关 + +- 取代[使共享示例基础配置与提供方无关](../../rejected/architecture/2026-06-20-providerless-example-base.md):一旦主干移入 `dsh-agent-spine-demo` 且 `base*.yml` 文件被删除,将 `base.yml` 重命名为无提供方核心便不再有意义。 +- 基于[能力 seam](2026-06-13-capability-seams.md)的接口/实现/消费方拆分——后端和展示层保持为叶子选择;主干是共享 bundle。 +- 与[将包重组为模块化层级结构](2026-06-20-package-hierarchy.md)互补:新的 app/core 包按该层级结构归入既有分组(`core` 放可复用的主干 bundle,`ui` 放应用特有的前门)。 +- 后续的[冗余 agent 移除](../simplification/2026-07-20-remove-stdio-and-echo-agents.md)拥有最终的 TUI/Headless 拆分,并移除行式与仅 mock 的叶子。 diff --git a/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.i18n.yaml new file mode 100644 index 0000000000..d44e3ffee9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-generic-long-running-tool-runtime.md: 0b901fcf928b900bd3a32f911e6e54a6a98076e2 +2026-06-20-generic-long-running-tool-runtime.zh.md: e2860e3a91c06ec5110cd671b288e35c5d117f5d diff --git a/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md b/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md index f3fe6373ea..0b901fcf92 100644 --- a/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md +++ b/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-generic-long-running-tool-runtime.zh.md) + ## Problem Background bash originally combined two responsibilities: the bash executor ran processes and also managed task ids, ownership, incremental reads, cancellation, completion listeners, and model-facing control tools. Adding background subagents required the same lifecycle and interaction contract. Implementing that contract independently for every long-running capability would duplicate isolation, cleanup, notification, and prompt behavior while teaching the model a different collect-and-stop protocol for each producer. @@ -67,7 +69,7 @@ A producer loaded without any control surface would let callers start work they ## Model-facing control surface -`dsh-tool-tasks` registers three kind-independent tools with generic ACP cards: +`dsh-tool-tasks` registers three kind-independent tools with generic UI cards: - `task_output(task_id, wait?, timeout_ms?)` reads output and always appends `[status: ...]`. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Reads are non-blocking unless `wait: true`, whose timeout is defaulted and capped by plugin config. A wait timeout reports the still-running status and does not stop the task. - `task_list()` returns caller-visible tasks as `<id> [<kind>] <status> — <label>`, or `(no background tasks)`. diff --git a/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.zh.md b/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.zh.md new file mode 100644 index 0000000000..e2860e3a91 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.zh.md @@ -0,0 +1,134 @@ +# Agent Note: 后台任务运行时(`ctx.tasks`)与通用任务控制工具 + +Status: implemented + +[English](2026-06-20-generic-long-running-tool-runtime.md) | 中文 + +## 问题 + +后台 bash 原本兼有两项职责:bash 执行器既运行进程,又管理 task id、所有权、增量读取、取消、完成监听器和面向模型的控制工具。新增后台 subagent 需要相同的生命周期与交互契约。如果每种长时间运行能力都独立实现该契约,就会重复隔离、清理、通知和提示词行为,还会让模型为每种生产方学习不同的收集与停止协议。 + +任务注册表、控制工具与完成通知共同构成一项 harness 功能。bash 和 subagent 只提供执行专属的钩子,不拥有通用任务行为。 + +## 决策 + +`tasks/` 包组拥有后台任务语义: + +- `@deepseek-ai/dsh-tasks` 将运行中的工作注册为 `ctx.tasks`,并拥有 task id、授权、快照、读取、取消、等待、完成监听器与清理。 +- `@deepseek-ai/dsh-tool-tasks` 暴露 `task_output`、`task_list` 和 `task_kill`,注入完成通知,并提供后台任务的系统提示词指导。 + +长时间运行工具是生产方。`dsh-tool-bash` 将 `BashProcess` 适配为增量输出与进程取消;`dsh-tool-subagent` 将子运行适配为最终输出与子运行释放。执行 seam 保持独立,不依赖会话或任务注册表。 + +`TaskService` 是一个具体的进程内服务。TODO(task-service-backend):当第二个后端明确所需生命周期后,将其公共契约与实现分离;systemd 驱动的运行时是一种可能方案,但本 PR(Pull Request)不臆测其持久性、重连、所有权或观察语义。 + +## 运行时契约 + +字面类型见[任务数据结构目录](../../../../docs/core-data-structures/tasks.md)。生产方调用 `ctx.tasks.start()`,传入 kind、label、可选的所属 `Agent`、可选的正数 `outputLimitBytes` 与一个 `run()` 函数。运行时会在调用 `run()` 前完成所有可能失败的预检工作,并且只调用一次。`run()` 返回钩子后,注册过程不会再执行可能失败的步骤而直接提交;生产方无法启动没有可收集 task id 的工作。 + +`outputLimitBytes` 是生产方拥有的呈现策略,而非注册表缓冲区。注册表校验该值,并将其原样投影到 `TaskSnapshot`;通用控制接口添加自身的状态或通知元数据后,再将该上限应用于完整的面向模型输出。省略该值时保持现有接口行为,因此运行时不会向无关的生产方类别施加隐式默认值。 + +面向模型的生产方会在规范成功值中暴露已提交的 id,通常为 `{ kind: 'background', taskId }`;Native 渲染仍可保留便于人类阅读的行文。预先被中止的后台调用会失败,而不是返回空操作,因为不存在可履行所承诺句柄的任务。一旦注册过程发布 id,取消就归任务自身的控制器与任务运行时所有:随后取消生产工具调用不得终止已发布的任务。`task_kill`、所有者资源释放和服务拆除会请求取消;前台执行仍与调用的 `exec.signal` 耦合。 + +生产方钩子定义三项职责: + +- `cancel(reason?)` 同步请求终止,具备幂等性,并且必须使 `done` 完成。 +- `done` 从不拒绝,并且仅在生产方释放任务资源后完成。 +- 可选的 `readOutput()` 返回下一个消费式输出增量。省略该钩子即声明这是最终输出任务,其终止结果来自 `TaskOutcome.output`。 + +状态包括 `running`、`stopping`、`completed`、`killed` 和 `failed`。退出码或停止原因等生产方专属信息放在 `detail` 中,注册表不解释这些信息。任务 kind 构成可合并扩展的字符串联合;task id 带品牌,并按 `<kind>-N` 生成,每个 kind 各有一个计数器。 + +运行时为 `done` 附加一个 continuation,记录第一个终止结果、解决等待方,并逐个调用完成监听器,同时隔离每个监听器的错误。首次结果优先的结算在资源销毁期间至关重要:如果 `cancel` 抛出,运行时会强制将记录标为失败,并警告工作可能遗留,而不是永远等待一个可能永不完成的 promise。后续生产方结果不能覆盖该诊断,也不能重复通知。`cancel` 返回后如果最终未使 `done` 完成,仍会阻塞资源销毁,因为运行时无法区分这种情况与缓慢但有效的停止。 + +任务注册不是生产方工具 fiber 的 effect。因此,重新加载工具或控制接口插件不会终止由 agent(智能体)和后端拥有的工作。任务服务自身释放时会取消所有实时任务,并等待遵守契约的生产方。 + +## 授权与所有者生命周期 + +task id 在运行时全局可见且可预测,因此注册表会授权每次访问。`get`、`read`、`wait` 和 `kill` 接受调用方 `Agent`;`list` 仅返回该调用方可见的任务。有所有者的任务仅允许对应的确切会话访问。无所有者任务向非 agent 调用方开放,并随任务服务一起终止。 + +快照存储所有者的品牌化 `SessionId` 以供授权,生命周期操作则保留确切的实时 `Agent` 实例。这两种身份用途不同:会话相等性授予访问权,精确对象身份决定清理和完成通知的接收方。复用 agent 或会话 id,不能将旧作用域的清理或通知重定向到替代实例。 + +某个所有者的第一个任务会向 `owner.ctx` 附加一个异步 effect。agent 作用域释放时会取消该所有者的实时任务、等待其终止记录,并移除其快照。该 effect 可跨生产方重载存续,并加入 agent 现有的完全停稳边界。任务服务保留 effect disposer,使服务重载可以在全局资源销毁后,从仍然存活的 agent 作用域中分离回调。 + +对于遵守契约的生产方,`AgentHandle.dispose()` 只在所属后台工作停止后解决。需要比 agent 存活更久的工作必须以无所有者方式启动;要跨运行时重启存续,则需另行设计持久任务。 + +## 服务接口 + +`TaskService` 提供: + +- `start(spec)`:经过预检的原子注册。 +- `get(id, caller?)` 和 `list(caller?)`:非消费式快照。 +- `read(id, caller?)`:消费式流增量或幂等的最终结果。 +- `kill(id, caller?, reason?)`:取消。 +- `wait(id, timeoutMs, caller?, signal?)`:有界的终止等待。 +- `onTaskDone(listener)`:effect 作用域内的观察,具有精确所有者投递和监听器隔离。 +- `attachSurface(name)`:控制接口可用性防线。 + +`wait` 在任务完成时返回终止快照,在等待超时时返回实时快照。中止一次等待只取消该次等待。如果结算已经将终止投递分配给该等待方,终止快照仍然优先。等待方在中止时同步注销,因此同一 tick 内的结算无法代表一个什么也未收到的读取方压制完成通知。 + +如果生产方加载时没有任何控制接口,调用方就能启动无法收集或停止的工作。因此,`dsh-tool-tasks` 在其整个生命周期内调用 `attachSurface()`;没有附加接口时,`start()` 会在生产方开始执行前失败。该检查发生在启动时而非插件加载时,因为兄弟插件可能并发激活。自定义的非模型接口可以自行附加,无需让注册表了解工具名称。 + +## 面向模型的控制接口 + +`dsh-tool-tasks` 注册三个与 kind 无关的工具,并使用通用 UI 卡片: + +- `task_output(task_id, wait?, timeout_ms?)` 读取输出,并始终追加 `[status: ...]`。流式任务只返回上次读取以来的输出;最终输出任务在结算后返回结果。除非指定 `wait: true`,否则读取不会阻塞;等待超时由插件配置提供默认值并限定上限。等待超时会报告仍在运行的状态,不会停止任务。 +- `task_list()` 将调用方可见的任务返回为 `<id> [<kind>] <status> — <label>`,没有任务时返回 `(no background tasks)`。 +- `task_kill(task_id, reason?)` 立即请求取消。可选的已记录原因会转发给生产方。终止任务报告现有状态;生产方的取消操作若抛出,调用便会失败,任务保持运行。 + +流式读取共享一个任务作用域内的消费游标,因为所属模型是预期读取方。UI 或多个独立读取方需要单独的非消费式观察 API;共享该游标会让读取方彼此消费对方的输出。 + +系统提示词要求模型保留 task id、在后台工作运行时继续处理独立工作而非忙轮询或重复启动同一任务、在给出最终答案前收集相关任务,并终止不再重要的工作。完成时,系统会向确切所有者的会话注入一条已记录的 `context/message`;它会成为下一个请求的持久上下文,但不会唤醒空闲的 agent。 + +当读取或等待交付终止任务、实时等待方在结算时认领了投递,或模型显式终止任务时,运行时将终止任务标为 `reported`。已报告的任务不会注入冗余的完成通知。监听器失败会独立记录,不会阻止后续监听器,也不会被等待方或资源销毁过程等待。当快照携带 `outputLimitBytes` 时,`dsh-tool-tasks` 会保持 UTF-8 边界,并复用生产方已有的截断标记,而不会重复添加。读取会为状态后缀预留空间并保留输出尾部;完成通知会先为稳定的 `background task <id>` 前缀与 `task_output` 指令预留空间,再截断可变的 kind、label、status、detail,乃至截断标记本身,因此 PTY 的最小上限仍能标识需要收集的任务。任务接口在策略有机会拒绝或短路分发之前,于最先执行的 pre-execute 监听器中解析调用方可见的生产方上限;随后通过任务定义最后一道的 `finalizeContent` 回调应用该上限,使规范化的工具错误、外层流水线失败与单文本策略结果都无法绕过该边界;经特意结构化的多块策略结果仍由策略拥有其形状与大小。 + +## 生产方显式启用 + +每个生产方通过带默认值的配置,自行决定其 schema 是否暴露 `run_in_background`。`dsh-tool-bash`、`dsh-tool-pty` 和每个 `dsh-tool-subagent` 实例都使用 `enableRunInBackground`,默认值为 true。禁用的实例会省略该参数;由于通用参数校验器允许未声明的键,它还会在执行时拒绝强制传入的后台参数。省略 schema 用于声明能力不可用;执行检查负责强制该约束。 + +`ctx.tasks` 不改写生产方 schema。bundle 只转发其所拥有生产方的配置。如果后台调用在没有附加接口的情况下到达 `start()`,运行时防线会在执行前使其失败。 + +## 生产方集成 + +bash seam 暴露 `resolve`、`run` 和 `start`。`start(spec)` 返回一个 `BashProcess`,提供增量读取、取消、退出事实以及不拒绝的完全停稳 promise。本地执行器只为自身释放时能终止并等待进程而保留实时句柄。前台调用方继续直接使用 `resolve` 和 `run`。 + +对于后台 bash,`dsh-tool-bash` 将调用方 agent 注册为所有者。其钩子将 `kill()` 映射为取消,将 `done` 映射为 completed 或 killed 的 `TaskOutcome`,并将 `readOutput()` 映射为进程的有界增量输出,以及溢出文件与沙箱通知。通用任务工具拥有 id、状态行、列表、等待和完成通知。 + +对于后台 subagent,`dsh-tool-subagent` 创建由任务拥有的 `AbortController`,并在任务 starter 内启动提供方。无论提供方就绪前后,取消都会中止同一个 signal。`done` 同时等待子运行结果和子运行释放,将已完成输出映射为最终结果,将中止映射为 `killed`,并将其他停止原因或基础设施失败映射为 `failed`。中间子历史保留在子会话中,不通过 `readOutput()` 暴露。 + +## 备选方案 + +### 按功能划分控制工具 + +为 bash 与 subagent 分别提供输出/停止工具,会重复 id、隔离、清理、通知和指导,并增加模型的 schema 与协议负担。统一运行时将执行专属行为保留在生产方中,而无需复制任务生命周期。 + +### 立即抽象任务运行时后端 + +当前 `TaskStart.run()` 契约传入进程内回调与确切的 `Agent` 对象。持久化后端会改变身份、重启、所有权与观察语义,因此在第二种实现出现前抽取接口,会固化错误的边界。 + +### 由消费方负责授权或清理事件 + +由消费方负责检查,会使每个新接口的隔离实现不一致或遗漏。广播清理事件会迫使每个监听器过滤所有 agent,且不提供注册 disposer。集中授权加一个所有者作用域内的 effect,为每个消费方提供相同防线,以及可等待、可移除的生命周期钩子。 + +### 阻塞输出或单独的等待工具 + +默认阻塞会在后台工作运行时串行化父任务。只等待而不读取会增加一次不返回有用信息的模型调用和 schema。`task_output(wait: true)` 显式表达阻塞,并将其与结果交付合并。 + +等待使用共享的 deadline 原语,而不使用通用工具超时策略。等待超时是一次成功的观察,会返回 `[status: running]`;通用策略会将它替换为超时错误。任务返回 task id 后,没有任何工具调用超时会控制任务生命周期。 + +### 由运行时拥有输出接收端 + +推送式接收端可以集中缓冲,但 bash 已经在执行器 seam 后拥有有界缓冲、截断与溢出文件。拉取格式化增量能够保留这一所有权。拥有存储的持久化后端可能足以支持重新审视生产方接口。 + +### 随机 id、提升或生命周期会话事件 + +授权而非不可猜测性才是访问边界,并且 id 不用于派生文件系统路径;顺序生成的品牌化 id 可保持 transcript(文本记录)易读。将前台任务提升为后台任务需要 SDK 并未规定的用户交互契约。启动、读取和通知已作为工具与上下文事件记录,因此专用任务会话事件会重复面向模型的事实。 + +## 测试 + +单元覆盖固定预检原子性、按 kind 分配的 id、输出上限的校验与投影、完整结果的 UTF-8 字节上限、流式与最终读取、等待超时与中止竞态、取消、首次结果优先的结算、监听器隔离、通知压制、所有者隔离、陈旧的所有者实例、所有者清理、服务资源销毁和无接口防线。生产方测试覆盖 bash 进程映射、subagent 启动取消、终止映射与释放。快照覆盖固定控制工具 schema 与提示词指导。 + +## 后果 + +bash 命令与 subagent 共享一套 id 词汇、列表、通知格式、提示词习惯和控制工具。新的长时间运行生产方只需实现执行钩子,而不必再实现一套注册表与工具族。[工具实操手册](../../../../docs/cookbook/adding-a-tool.md)将生产方指向本契约。 + +有所属后台 bash 会随其 agent 一起停止,不再比 agent 存活更久。后台进程没有执行器超时;调用方必须终止无关工作,或依赖所有者/服务释放。流式读取只支持一个消费方,完成通知不会唤醒空闲 agent;生产方的 `cancel` 返回后如果未使 `done` 完成,仍可能阻塞资源销毁。持久任务、独立观察游标和前台提升仍属于单独设计。 diff --git a/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.i18n.yaml new file mode 100644 index 0000000000..7db4f97aa4 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-package-hierarchy.md: 7cd07ff90225872f2a17b9a678e52fcee416b09a +2026-06-20-package-hierarchy.zh.md: 9ef89bd56144b39bb3240a22a2bb1e9216e24115 diff --git a/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.md b/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.md index 1ba3b94e8b..7cd07ff902 100644 --- a/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.md +++ b/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.md @@ -2,7 +2,9 @@ Status: implemented -The later [fold-stdio-helper](../simplification/2026-07-04-fold-stdio-ui-helper.md) decision superseded the original `support/ui-stdio` placement, and the [redundant-agent removal](../simplification/2026-07-20-remove-stdio-and-echo-agents.md) subsequently removed that surface entirely. The uniform depth-two hierarchy remains the decision owned here. +English | [中文](2026-06-20-package-hierarchy.zh.md) + +The later [fold-stdio-helper](../simplification/2026-07-04-fold-stdio-ui-helper.md) decision superseded the original `support/ui-stdio` placement, and the [redundant-agent removal](../simplification/2026-07-20-remove-stdio-and-echo-agents.md) subsequently removed that surface entirely. The [automation-only ACP decision](../simplification/2026-07-23-acp-automation-only-protocol.md) places ACP under `packages/acp/acp` instead of the human-UI group. The uniform depth-two hierarchy remains the decision owned here. ## Problem @@ -34,8 +36,9 @@ packages/ session-persistence/ session-persistence-jsonl/ session-persistence-sqlite/ - ui/ (product integration) + acp/ (product automation integration) acp/ + ui/ (human interaction and presentation) support/ (dev/test/example infrastructure) invariants/ ui-stdio/ @@ -47,7 +50,7 @@ packages/ - **Same-name nesting for capability families.** A family's interface package sits at `packages/<group>/<group>/` (`llm/llm`, `bash/bash`, `session-persistence/session-persistence`), with implementations and consumers as flat siblings. There is no extra `adapters/`/`impls/` sub-tier — every package is exactly depth 2, which keeps the workspace glob a clean `packages/*/*` and lets one `@deepseek-ai/dsh-*` tsconfig wildcard resolve every package (unique dir names make first-on-disk-wins unambiguous). - **`session` stays in `core/`; persistence is its own family.** The session log is core product API. Its storage backends form a parallel capability family (`session-persistence/`) mirroring `llm/` and `bash/`, rather than nesting under `core/session/`. - **`agent-loop` is in `core/`.** It is the one concrete implementation of the `agent` seam, but it ships as the harness's default product loop, so it lives with the core spine. Plugins still depend on the `agent` vocabulary, never on `agent-loop`, so the loop stays swappable. -- **`invariants` and `ui-stdio` are `support/`, not product.** `invariants` is dev-mode contract checking. `ui-stdio` was extracted from the examples for reuse and the coverage gate — it is example-coupled, so it sits in `support/` alongside `llm-replay` (the snapshot-test replay adapter). `acp` is the only `ui/` member because it is a real product surface (the ACP bridge an editor drives), structurally distinct from the readline demo helper. +- **Product automation and human UI are separate groups.** `acp` is a product transport under `acp/`, while commands, approvals, interaction, and presentation adapters live under `ui/`. Dev-only invariants and replay infrastructure remain under `support/`. ### Deduplicating the package lists @@ -68,7 +71,7 @@ Two doc-sync/hygiene gates keep the structure and its references honest, so the - **A third tier (`adapters/` / `impls/` under each family)** — rejected: uniform depth 2 keeps the workspace glob a clean `packages/*/*` and lets one `@deepseek-ai/dsh-*` tsconfig wildcard resolve every package. - **Nesting persistence under `core/session/`** — rejected: the storage backends form a parallel capability family mirroring `llm/` and `bash/`, while the session log itself stays core product API. -- **`ui-stdio` under `ui/`** — rejected: it is example-coupled dev support, not a product surface; `acp` is the only `ui/` member because an editor actually drives it. +- **`ui-stdio` under `ui/`** — rejected: it was example-coupled dev support, not a product surface. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.zh.md b/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.zh.md new file mode 100644 index 0000000000..9ef89bd561 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-20-package-hierarchy.zh.md @@ -0,0 +1,78 @@ +# Agent Note: 将包重组为模块化层级结构 + +Status: implemented + +[English](2026-06-20-package-hierarchy.md) | 中文 + +后续的[折叠 stdio helper](../simplification/2026-07-04-fold-stdio-ui-helper.md)决策取代了最初的 `support/ui-stdio` 放置方式,[冗余 agent 移除](../simplification/2026-07-20-remove-stdio-and-echo-agents.md)随后又彻底移除了该接口。[仅面向自动化的 ACP 决策](../simplification/2026-07-23-acp-automation-only-protocol.md)把 ACP 放在 `packages/acp/acp` 下,而不是面向人类的 UI 组。这里拥有的决策仍是统一的二层目录深度。 + +## 问题 + +`packages/` 原先是扁平的:18 个包(package)全部位于 `packages/<name>/`,从路径上完全看不出一个包属于核心产品 API、可替换的能力 seam、提供方适配器、产品集成,还是示例/测试支撑。包的 README 带着 `FIXME(package-hierarchy)`,`scripts/publint-all.ts` 带着 `TODO(package-inventory)`,标记的正是这个问题。核心包、提供方集成、能力 seam、示例 UI 支撑和仅用于快照的回放支撑看起来同样基础。 + +这不仅仅是外观问题。由于每个顶层包看起来都属于同一个公开接口,未来移除更加困难,而 publish/lint/doc 脚本不得不通过注释或手工维护的静态列表来编码意图,而不是从布局中直接读取。 + +## 决策 + +按模块角色将包分组,统一放在 `packages/<group>/<pkg>/` 深度。分组目录是纯容器(没有 `package.json`);每个包保留其 `@deepseek-ai/dsh-<pkg>` 名称——这是仓库结构与维护策略的调整,不是包的重命名。 + +```text +packages/ + core/ (product API spine) + session/ + system-prompt/ + tools/ + agent/ + agent-loop/ + llm/ (product — capability family) + llm/ + llm-deepseek/ + llm-pi-ai/ + bash/ (product — capability family) + bash/ + bash-local/ + tool-bash/ + session-persistence/ (product — capability family) + session-persistence/ + session-persistence-jsonl/ + session-persistence-sqlite/ + acp/ (product automation integration) + acp/ + ui/ (human interaction and presentation) + support/ (dev/test/example infrastructure) + invariants/ + ui-stdio/ + llm-replay/ +``` + +### 放置决策 + +- **能力族使用同名嵌套。** 一个族的接口包位于 `packages/<group>/<group>/`(`llm/llm`、`bash/bash`、`session-persistence/session-persistence`),实现和消费方作为扁平兄弟并列。不设额外的 `adapters/`/`impls/` 子层——每个包恰好在深度 2,这使 workspace glob 保持简洁的 `packages/*/*`,并让一条 `@deepseek-ai/dsh-*` tsconfig 通配符即可解析所有包(唯一的目录名使 first-on-disk-wins 无歧义)。 +- **`session` 留在 `core/`;持久化独立成族。** 会话日志是核心产品 API。其存储后端构成一个平行的能力族(`session-persistence/`),与 `llm/` 和 `bash/` 对称,而非嵌套在 `core/session/` 下。 +- **`agent-loop` 在 `core/` 中。** 它是 `agent` seam 唯一的具体实现,但作为 harness 的默认产品循环交付,因此与核心主干同处。插件仍然依赖 `agent` 的词汇,从不依赖 `agent-loop`,所以循环仍可替换。 +- **产品自动化与面向人类的 UI 是两个独立分组。** `acp` 是位于 `acp/` 下的产品传输层,而命令、审批、交互和展示适配器位于 `ui/` 下。仅开发用的 invariants 与回放基础设施仍留在 `support/` 中。 + +### 去重包列表 + +包列表此前在五个地方重复枚举。统一的深度 2 布局使大部分可以被推导: + +- `tsconfig.base.json` 通过一条 `@deepseek-ai/dsh-*` `paths` 通配符(每个分组列一个候选)映射所有包,取代了逐包条目。聚合配置(`tsconfig.host.json`、`tsconfig.client.json`)复用该源映射,并携带显式 project references 以保持包/vendor 类型检查边界完整。(这里引入了一个细节:路径候选中包含 `/*/`,朴素的正则注释剥离器会将其误认为块注释——`scripts/doc-typecheck.ts` 正是因此通过 TypeScript 解析器读取 JSONC 配置,而非手动剥离注释。) +- `scripts/publint-all.ts` 通过读取层级结构(`packages/<group>/<pkg>`)推导列表,解决了 `TODO(package-inventory)`。 +- 聚合配置的 project `references` 仍为显式列表——TypeScript project references 没有通配符形式。从 manifest(元数据清单)生成这些引用留作后续工作(见[通过发现机制获取包清单](../../proposed/process/2026-06-20-discover-package-inventory.md))。 + +### 新增的护栏 + +两道 doc-sync/hygiene 门禁确保结构及其引用保持正确,使本次重组所需的手动检查无需日后重复: + +- `scripts/verify-package-paths.ts` 标记 Markdown 或 `.ts` 注释/字符串中的 `packages/<path>` 引用,如果该引用无法解析**且**某个路径段命名了一个真实存在的包,即指向已移动包的陈旧路径。如果路径命名的包在任何地方都不存在(前瞻性提案),则不予标记,因此该门禁在 proposed/implemented/rejected 中统一适用。 +- `scripts/check-workspace-constraints.ts` 断言 `packages/<group>/<pkg>` 形状:分组目录不带 `package.json`,且没有包扁平地位于根层或嵌套更深。分组名称保持开放——添加新分组无需修改门禁;只有深度 2 的形状是固定的。 + +## 曾考虑的替代方案 + +- **第三层(每个族下设 `adapters/`/`impls/`)**:否决。统一深度 2 使 workspace glob 保持简洁的 `packages/*/*`,并让一条 `@deepseek-ai/dsh-*` tsconfig 通配符即可解析所有包。 +- **将持久化嵌套在 `core/session/` 下**:否决。存储后端构成一个平行的能力族,与 `llm/` 和 `bash/` 对称,而会话日志本身属于核心产品 API。 +- **`ui-stdio` 放在 `ui/` 下**:否决。它曾是与示例耦合的开发支撑,不是产品接口。 + +## 后果 + +本次重组在一次协调的变更中搅动了 import、workspace glob、文档链接、构建引用和包路径。这种变动在发布前是可接受的(依据 AGENTS.md 中「基础优先于爆炸半径」的立场),因为它阻止了扁平布局将支撑包固化为产品契约,且这是一次性成本:通配符 `paths`、glob 推导的 publint 列表和形状门禁意味着新增一个包无需额外的结构性编辑。 diff --git a/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.i18n.yaml new file mode 100644 index 0000000000..e72b100327 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-21-mandatory-app-attribution-headers.md: a8ffe91c431cdc7907626bbc3eaf8096035777de +2026-06-21-mandatory-app-attribution-headers.zh.md: 5529a42dddf4615ee1054b4d1dee36b077800d7d diff --git a/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md b/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md index fdd98b89cb..a8ffe91c43 100644 --- a/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md +++ b/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-21-mandatory-app-attribution-headers.zh.md) + ## Problem LLM provider requests should identify the product making them. That is useful for provider-side support, abuse investigation, compatibility debugging, and traffic analytics. Before this Agent Note the harness only partially did this: the hand-rolled DeepSeek adapter sent a hand-copied `User-Agent` constant (`packages/llm/llm-deepseek/src/adapter.ts`), while the pi-ai-backed twin sent no harness-owned headers at all (`packages/llm/llm-pi-ai/src/adapter.ts`). New adapters could therefore omit attribution silently, and a library-backed adapter could drift from the hand-rolled adapter even though [the twin-adapter Agent Note](2026-06-13-twin-llm-adapters.md) exists to keep the provider seam honest across both implementations. diff --git a/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.zh.md b/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.zh.md new file mode 100644 index 0000000000..5529a42ddd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.zh.md @@ -0,0 +1,84 @@ +# Agent Note: 对提供方请求强制携带 `User-Agent` 归属标识 + +Status: implemented + +[English](2026-06-21-mandatory-app-attribution-headers.md) | 中文 + +## 问题 + +LLM(大语言模型)提供方请求应当标识发出请求的产品。这对提供方侧的技术支持、滥用调查、兼容性调试和流量分析都有价值。在本 Agent Note 之前,harness 只做了部分工作:手写的 DeepSeek 适配器发送了一个手动复制的 `User-Agent` 常量(`packages/llm/llm-deepseek/src/adapter.ts`),而基于 pi-ai 的孪生适配器则完全不发送 harness 自有的头部(`packages/llm/llm-pi-ai/src/adapter.ts`)。因此新适配器可以悄无声息地省略归属标识,而基于库的适配器也可能与手写适配器产生偏差——尽管[孪生适配器 Agent Note](2026-06-13-twin-llm-adapters.md) 的存在正是为了让两种实现在提供方 seam 上保持诚实。 + +直接触发因素来自 OpenRouter 的[应用归属](https://openrouter.ai/docs/app-attribution)文档。OpenRouter 根据 `HTTP-Referer` 加上 display/category 头部来创建应用页面和排名。这有价值,但它不是 HTTP 标准中的应用身份机制。风险在于:把 OpenRouter 的精确头部集当作通用标准来采纳,然后将提供方特有的头部泄漏到直连 DeepSeek 的请求、未来的 OpenAI/Anthropic/Vertex 适配器、测试服务器或无限期记录未知字段的代理中。 + +## 调研 + +- **OpenRouter 的机制是提供方特有的。** 其当前文档说明应用归属通过 `HTTP-Referer`(必需)、`X-OpenRouter-Title` 和 `X-OpenRouter-Categories` 来追踪;`X-Title` 仅为向后兼容而接受。其 API 参考称这些头部为可选,并说它们使应用在 OpenRouter 上可被发现。这是一份具体的 OpenRouter 契约,而非 IETF 或 OpenAI 兼容 API 标准。 +- **在 agent 工具生态中,`HTTP-Referer` 是一种 OpenRouter 感知的约定,而非通用 agent 约定。** 它足够常见,以至于 OpenRouter SDK 和示例直接暴露它,面向 OpenRouter 的框架通常需要一种方式来透传它。但 ACP(Agent Client Protocol)等 agent 协议在自己的 initialize 消息中协商名称、版本和能力,而模型提供方请求仍需 HTTP 层面的身份标识。因此「在 agent 世界中被接受」意味着「被 OpenRouter 集成所识别」,而非「可跨 agent 运行时或提供方移植」。 +- **编程 agent 在 `User-Agent` 中标识产品和版本。** 公开实现在环境细节和提供方特有的附加头部上各有不同,但产品身份是共同契约;不存在通用的精确格式。 +- **标准化的通用客户端身份头部是 `User-Agent`。** RFC 9110 第 10.1.5 节将 `User-Agent` 定义为用户代理软件身份,说明它用于互操作性报告和分析,并说用户代理应当在每个请求中发送它(除非被配置为不发送)。这是唯一直接对应「哪个产品在发出此 HTTP 请求」的标准头部。 +- **`Referer` 是标准的,但 OpenRouter 的 `HTTP-Referer` 不是标准字段。** RFC 9110 第 10.1.3 节将 `Referer` 定义为获取目标 URI 的来源 URI,并用大量篇幅讨论隐私限制。OpenRouter 则要求 `HTTP-Referer`,将其用作应用 URL 标识符。该名称和含义是 OpenRouter 特有的,尽管它形似标准 `Referer` 头部的 CGI 环境变量形式。 +- **`From` 是标准的,但不适合作为强制默认值。** RFC 9110 第 10.1.2 节将 `From` 定义为负责用户代理的人的电子邮件地址。机器人代理应当发送它以便服务器联系运营者,但非机器人代理出于隐私和安全策略考虑不应在未经用户显式配置的情况下发送。harness 可以后续支持运营者联系方式,但不得凭空捏造或全局强制要求。 +- **请求体中的 `user` 或 `metadata` 字段不是应用归属。** 部分模型 API 暴露稳定的终端用户标识符、请求元数据、标签或项目/账户头部。这些对滥用监控、内部计费、仪表盘或链路追踪有用,但它们要么标识的是终端用户而非产品,要么是提供方特有的 body schema,要么不保证能通过 OpenAI 兼容网关透传。它们不能替代静态的应用身份头部。 +- **SDK 遥测头部标识的是 SDK,而非应用。** 官方和第三方 SDK 常发送库/版本头部。这些帮助 SDK 维护者调试其客户端,但除非应用显式提供产品归属层,否则它们不能标识 harness 作为应用。 +- **pi-ai 有一流的头部钩子。** `@earendil-works/pi-ai` 的 `StreamOptions.headers` 将调用方头部最后合并(覆盖提供方默认值),因此基于库的适配器无需包装或上游改动即可满足与手写适配器相同的协议格式契约。mock 服务器测试套件对两个适配器都断言头部到达了线路。 + +## 决策 + +在 LLM 适配器边界,提供方请求归属是强制的,且仅使用标准 `User-Agent` 头部。规则:每个生产 LLM 适配器在每个提供方 HTTP 请求上发送一个静态、非机密的应用身份,且每个适配器都有测试证明 `User-Agent` 到达了线路(mock 服务器断言收到的头部;对于基于库的适配器,通过库的头部钩子馈入同一个 mock 服务器断言)。 + +本 Agent Note **不**实现 OpenRouter 应用归属。`HTTP-Referer`、`X-OpenRouter-Title`、`X-Title` 和 `X-OpenRouter-Categories` 是 OpenRouter 特有的产品展示头部,不是提供方无关的模型请求归属。它们可以后续由 OpenRouter 适配器或显式 OpenRouter 模式提出,附带自己的隐私/产品决策、测试和文档。在此之前,即使请求指向 OpenRouter,也只发送本 Agent Note 定义的共享 `User-Agent` 归属。 + +提供方无关的身份由 `dsh-llm`(`packages/llm/llm/src/attribution.ts`)拥有,而非各适配器。`AppIdentity` 仅包含构建 `User-Agent` 所需的公开产品事实,默认的 `APP_IDENTITY` 确定了提案中留待决定的值: + +- `User-Agent` 的产品 token:`deepseek-harness`(与 Agent Note 之前的线路值及仓库/组织身份保持连续性) +- 版本:通过 `createRequire` 从所属包的 manifest 读取,绝不手动复制常量 +- 应用 URL:`https://github.com/deepseek-ai/deepseek-harness-sdk`——计划中的公开主页;`attribution.ts` 中的 `FIXME` 标记在该仓库实际存在之前阻塞发布 + +默认值是强制的且非空。白标部署通过向 `attributionHeaders(identity)` 传入自己的 `AppIdentity` 来覆盖——覆盖 seam 就是函数参数,在有消费方需要之前不做部署配置管道——省略时回退到 harness 默认值而非抑制归属。没有逐请求 API 允许模型、用户提示词、会话 id、cwd、用户邮箱、API key 所有者或本地机器身份影响这些字段。 + +线路映射(`attributionHeaders`;代码中头部名称小写——HTTP 字段名在线路上不区分大小写): + +| 目标 | 映射 | +|---|---| +| 所有基于 HTTP 的适配器 | `User-Agent: {product}/{version} (+{url})`——括号中的 `+url` 注释符合 RFC 9110 保守的 product/comment 语法。 | +| 直连 DeepSeek 端点 | `User-Agent`;除非 DeepSeek 文档化了等效契约,否则不发送 OpenRouter 特有头部。 | +| OpenRouter 端点 | 目前仅 `User-Agent`。本 Agent Note 下不发送 `HTTP-Referer`、`X-OpenRouter-Title`、`X-Title` 或 `X-OpenRouter-Categories`。 | +| 未来提供方 | 仅 `User-Agent`,除非后续提供方特有的 Agent Note 接受额外头部。不要类比复用 `HTTP-Referer`。 | + +端点检测不在本 Agent Note 范围内,因为此处不接受任何端点特有的映射。如果后续支持 OpenRouter,检测必须是显式的:要么是专门的 OpenRouter 提供方包,要么是显式的 `provider: 'openrouter'` / `attributionTarget: 'openrouter'` 配置,而非任意路径片段或模型名称。 + +## 验证 + +已落地的契约: + +- `dsh-llm` 为 `LlmAdapter` 作者文档化了强制的 `User-Agent` 归属契约(`LlmAdapter` JSDoc、包 README,以及 `docs/core-data-structures/llm-streaming.md` 的适配器契约章节)。 +- 共享辅助函数(`attributionHeaders` / `userAgent`)从包元数据构建应用身份和标准 `User-Agent` 值,适配器无需手动复制版本常量。 +- `dsh-llm-deepseek` 在每个请求上发送共享的 `User-Agent`,其 mock 服务器套件断言精确值。 +- `dsh-llm-pi-ai` 通过 pi-ai 的 `StreamOptions.headers` 钩子发送相同的 `User-Agent`,其 mock 服务器套件断言精确值。 +- 本 Agent Note 下没有适配器发送 OpenRouter 特有的归属头部(`HTTP-Referer`、`X-OpenRouter-Title`、`X-Title`、`X-OpenRouter-Categories`)。 +- 没有应用归属字段携带机密、本地路径、会话 id、提示词文本、模型输出、用户邮箱或逐用户的稳定标识符。 +- 适配器 README 声明了 `User-Agent` 归属策略,并明确避免将 OpenRouter 应用归属记录为已实现的行为。 + +## 曾考虑的替代方案 + +**现在就实现 OpenRouter 应用归属。** 本 Agent Note 否决。发送 `HTTP-Referer` 加 `X-OpenRouter-Title` 可以满足 OpenRouter 排名,但这些头部是提供方特有的产品功能,不是本 Agent Note 试图标准化的提供方无关的模型请求归属。支持它们应当是后续显式的 OpenRouter 适配器/模式决策,而非隐藏在首个共享归属辅助函数中。 + +**向所有提供方发送 OpenRouter 头部。** 否决。这会把一份自定义的 OpenRouter 契约当作通用标准,并向未要求这些字段的提供方发送语义误导的头部。还有风险将 `HTTP-Referer` 当作通用应用 URL 字段使用,尽管标准 HTTP 已有 `User-Agent` 用于产品身份、`Referer` 用于不同的浏览上下文概念。 + +**仅使用提供方账户/项目身份。** 否决。组织/项目头部、API key、云账户和计费项目标识的是谁付费或谁拥有请求,而非哪个应用在发送流量。它们也不暴露公开的应用标题/类别,无法帮助 OpenRouter 等网关构建应用排名。 + +**终端用户 `user`/`metadata` 字段。** 本 Agent Note 否决。这些对滥用监控和客户支持有价值,但描述的是请求背后的人或租户。应用归属必须是静态的产品身份,且可安全地在每个请求上发送。 + +**仅配置启用的归属。** 否决。默认关闭的设置正是适配器不断漂移的原因。策略是强制默认归属加可覆盖的公开值,而非可选归属。 + +**以产品命名的 token(`deepseek-harness-sdk`)。** 曾考虑用于 `User-Agent` token,因为产品名是 DeepSeek Harness SDK。`deepseek-harness` 因连续性胜出:它是提供方从本代码库已经看到的身份,与组织/仓库身份和包 scope 一致,且在展示文案承载产品名的同时保持线路归属稳定。 + +## 后果 + +**提供方看到流量来自 harness。** 这正是目的,但意味着此前混在通用 SDK 流量中的部署变得可识别。缓解措施:仅发送静态公开产品数据,并允许 fork/白标部署传入自己的 `AppIdentity`。 + +**应用 URL 指向一个尚不存在的仓库。** `deepseek-ai/deepseek-harness-sdk` 是计划中的公开主页;在它创建之前,该 URL 是一个悬空承诺。常量上的 `FIXME` 标记阻塞发布,不允许带着未解决的问题出门(见 `docs/development.md` 标记语义)。 + +**不同客户端库的头部支持有差异。** 手写适配器直接设置头部;基于 pi-ai 的适配器依赖 pi-ai 继续尊重 `StreamOptions.headers`(最后合并覆盖提供方默认值)。线路级 mock 服务器测试是守卫:如果 pi-ai 升级后不再投递该头部,套件会变红。这对抽象施加了有益的压力:一个无法设置强制头部的提供方适配器不能完整实现 harness 的 LLM 契约。 + +**OpenRouter 排名尚未受益。** `User-Agent` 是提供方无关的 HTTP 身份的正确基线,但它不会创建 OpenRouter 应用页面或排名,因为 OpenRouter 要求 `HTTP-Referer` 来实现该产品功能。这是有意为之:公开应用市场参与是一个独立的产品决策,不是强制请求归属的前提。 diff --git a/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.i18n.yaml new file mode 100644 index 0000000000..70ec051143 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-24-web-capability-seam.md: 4f4e821fec9494fe9ea96894267707d9dd202e4d +2026-06-24-web-capability-seam.zh.md: d7c07a8ae0365c321120102a0af401d85d7e2eae diff --git a/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md b/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md index b3dad98f18..4f4e821fec 100644 --- a/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-24-web-capability-seam.zh.md) + ## Problem The harness needs model-facing web tools without binding the model contract to one vendor's API shape. Search is the immediate pressure point: supporting both Exa search and Perplexity search from the start — two deliberately different provider shapes (Exa returns a flat `results[]` of `{title, url, highlights, publishedDate}`; Perplexity returns a generated answer plus citations) — is what proves the normalized seam does not just mirror one vendor. Fetch is a separate capability: an anonymous public HTTP(S) fetch backend has transport, security, redirect, decoding, and size-limit concerns that are not the same as provider-backed search. @@ -75,6 +77,8 @@ Provider packages depend only on `dsh-web` and Cordis. They own credentials, end `ctx.web` is a provider registry plus a provider-selecting execution surface. The registry half stays close to `LlmService`: a `Map<id, provider>` per capability kind, `registerSearchProvider` / `registerFetchProvider` methods that return disposers, duplicate ids that throw `WebError`, and execution-time resolution that throws when the selected provider is absent or unusable. The authoritative signatures live in `packages/web/web/src/types.ts`; the seam's shape: ```ts +import type { WebFetchRequest, WebFetchResult, WebSearchRequest, WebSearchResult } from '@deepseek-ai/dsh-web' + interface WebSearchProvider { readonly id: string available(): boolean @@ -206,18 +210,18 @@ The seam request deliberately does not include a per-call timeout, `format`, `pr HTTP status is part of the fetched resource state, not automatically a tool failure. A successful network fetch of a `404` or `500` response returns `WebFetchResult` with the status code and a bounded decoded body when the content type is supported. `WebError` is for failures to safely retrieve or represent the resource: invalid or blocked URL, redirect policy violation, timeout, abort, response too large, unsupported content type, provider failure, or network failure. ```ts -interface WebFetchRequest { +export interface WebFetchRequest { readonly url: string } -interface WebFetchResult { +export interface WebFetchResult { readonly url: string readonly statusCode: number readonly body: WebFetchBody readonly truncated: boolean } -type WebFetchBody = +export type WebFetchBody = | { readonly kind: 'html'; readonly content: string } | { readonly kind: 'text'; readonly content: string } ``` diff --git a/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.zh.md new file mode 100644 index 0000000000..d7c07a8ae0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.zh.md @@ -0,0 +1,336 @@ +# Agent Note: Web 能力 seam——稳定的工具覆盖多个提供方 + +Status: implemented + +[English](2026-06-24-web-capability-seam.md) | 中文 + +## 问题 + +harness 需要面向模型的 web 工具,但不能将模型契约绑定到某一家厂商的 API 形状上。搜索是当前的压力点:从一开始就同时支持 Exa 搜索和 Perplexity 搜索——两种刻意不同的提供方形状(Exa 返回扁平的 `results[]`,每项包含 `{title, url, highlights, publishedDate}`;Perplexity 返回一段生成式回答加引用列表)——正是用来证明归一化的 seam 并非只是镜像某一家厂商。Fetch 是另一项独立能力:匿名公开 HTTP(S) fetch 后端涉及传输、安全、重定向、解码和大小限制等关注点,与提供方支撑的搜索并不相同。 + +面向模型的接口必须保持稳定,而后端可以更换。更换搜索提供方不应改变模型发起查询的方式;更换 fetch 实现不应改变模型请求 URL 的方式。反过来,提供方包也不应仅仅因为自己有额外的提供方特有旋钮就暴露自己的面向模型工具 schema。 + +如果把搜索和 fetch 直接放进 `dsh-tool-web`,面向模型的工具就要同时承担提供方选择、后端请求映射、传输策略、结果归一化、提示词引导、展示和 schema 注册。让每个提供方注册自己的工具则有相反的问题:工具的可用性、名称、描述和参数将取决于恰好加载了哪些提供方包,提供方特有字段会泄漏到模型契约中。 + +还有一个提供方选择的问题。现有的 `tool-bash` 和 `tool-fs` 可以依赖 Cordis 的 `inject`,因为只有一个后端服务键。Web 有两项独立能力(`search` 和 `fetch`),每项能力可能有多个提供方。`inject: ['web']` 能证明 seam 存在,但不能证明存在可用的搜索或 fetch 提供方,也无法定义多个提供方注册时谁胜出。 + +## 决策 + +Web 访问是一个一等能力 seam,遵循[能力 seam Agent Note](2026-06-13-capability-seams.md): + +1. `@deepseek-ai/dsh-web`(`packages/web/web`)拥有 `ctx.web`、提供方注册、提供方选择、共享的请求/结果词汇,以及 web 特有的错误。 +2. 提供方包实现具体后端并向 `ctx.web` 注册能力,例如 `@deepseek-ai/dsh-web-search-exa`、`@deepseek-ai/dsh-web-search-perplexity`、`@deepseek-ai/dsh-web-search-deepseek` 和 `@deepseek-ai/dsh-web-fetch-local`。 +3. `@deepseek-ai/dsh-tool-web`(`packages/web/tool-web`)拥有面向模型的 `web_search` 和 `web_fetch` 工具 schema、提示词段落、参数校验、结果格式化,以及通过 `ctx.web` 实现的工具展示。 + +提供方不注册工具。提供方注册能力。`dsh-tool-web` 是面向模型的名称、描述、提示词引导、JSON Schema、展示的唯一所有者。 + +搜索和 fetch 是两个独立工具,但属于同一个 web 访问 seam。`ctx.web` 为两个并行注册表统一拥有提供方选择、abort/错误词汇和部署配置。它们的请求 schema 和提供方逻辑保持独立;共享的服务是触达 web 的产品边界。 + +`dsh-tool-web` 在产品启用了相应工具且 `ctx.web` seam 存在时注册面向模型的 web 工具。后端可用性是执行时关注点,而非 schema 注册时关注点: + +- `web_search` 在产品/应用启用了 web 搜索时注册,`web_fetch` 在启用了 web fetch 时注册。 +- 工具绝不会仅仅因为其选定的提供方缺失、配置错误、缺少凭证、存在歧义或暂时不可用就被注销。 +- 提供方在执行时解析,当选定的能力无法运行时返回结构化的 `WebError`。 + +这使模型 schema 保持稳定,而不将插件加载顺序、凭证状态或 HMR(热模块替换)时序纳入面向模型的契约。如果 web 搜索已启用但不存在可用的搜索提供方,`web_search` 仍然可见,执行时以结构化的 `WebError`(如 `WEB_PROVIDER_UNAVAILABLE` 或 `WEB_PROVIDER_CONFIGURED_UNAVAILABLE`)失败。如果某个提供方在 `dsh-tool-web` 之后出现,下一次执行即可使用它而无需更改 schema。如果某个提供方在调用过程中消失,执行以结构化的 `WebError` 失败,而不是静默选择另一个提供方或回退到 `UNKNOWN_TOOL`。 + +该 seam 刻意不暴露任何观察面——没有注册表变更事件,也没有聚合的能力状态查询。不可用性是调用方通过执行观察到的事实:`search()`/`fetch()` 在调用时解析提供方,并抛出命名了失败原因的结构化 `WebError`。[观察面 Agent Note](../simplification/2026-07-04-drop-unconsumed-web-observation-surface.md) 记录了这一判断:基于调用的派生选择与基于启用的注册使得没有消费方需要变更信号或独立于执行和错误路由的可用性探测;未来的提供方状态面板会重新引入它实际消费的最小信号或查询。 + +## 包拓扑 + +由三个包构成的接口/实现/消费方拆分沿用 bash 和 filesystem 的模式,但*接口*包更接近 LLM(大语言模型) seam。`LlmService`(`packages/llm/llm/src/index.ts`)是一个按名称键控的提供方注册表:`registerAdapter(models, adapter)` 将适配器存入 `Map`、返回 disposer、对重复键抛出 `DUPLICATE_ADAPTER`、在解析时抛出 `NO_ADAPTER`。`ctx.web` 沿用该注册表形状,但有两种能力类别和更丰富的选择策略(配置的提供方 id,或在恰好只有一个可用提供方注册时自动选择),因此执行时抛出的 `WebError` 能解释搜索或 fetch 能力为何无法运行。 + +依赖方向与 bash 和 filesystem 一致: + +```text +@deepseek-ai/dsh-tool-web --depends on--> @deepseek-ai/dsh-web <--depends on-- @deepseek-ai/dsh-web-search-exa + consumer interface implementation + <--depends on-- @deepseek-ai/dsh-web-search-perplexity + implementation + <--depends on-- @deepseek-ai/dsh-web-search-deepseek + implementation + <--depends on-- @deepseek-ai/dsh-web-fetch-local + implementation +``` + +运行时,提供方包向 `ctx.web` 注册能力;`tool-web` 向 `ctx.tools` 注册稳定的工具并通过 seam 执行: + +```mermaid +flowchart LR + exa["@deepseek-ai/dsh-web-search-exa"] -->|registerSearchProvider| web["@deepseek-ai/dsh-web / ctx.web"] + perplexity["@deepseek-ai/dsh-web-search-perplexity"] -->|registerSearchProvider| web + deepseek["@deepseek-ai/dsh-web-search-deepseek"] -->|registerSearchProvider| web + fetchLocal["@deepseek-ai/dsh-web-fetch-local"] -->|registerFetchProvider| web + toolWeb["@deepseek-ai/dsh-tool-web"] -->|search/fetch| web + toolWeb -->|ctx.tools.register| webSearch["tool: web_search"] + toolWeb -->|ctx.tools.register| webFetch["tool: web_fetch"] +``` + +`@deepseek-ai/dsh-web` 仅依赖 Cordis 和底层 harness 支持。它声明 `ctx.web`、提供方接口、请求/结果类型、提供方可用性契约和错误码。它不导入工具、agent、会话、LLM 或提供方包。 + +提供方包仅依赖 `dsh-web` 和 Cordis。它们拥有凭证、端点、协议格式映射、解析和 `WebError` 转换,使用平台 `fetch`。每个提供方注入共享服务并注册后端;只有 `dsh-web` 拥有 `ctx.web` 键。提供方私有的协议形状不会产生对 `ctx.llm` 或 Cordis HTTP 服务的依赖。 + +`@deepseek-ai/dsh-tool-web` 依赖 `@deepseek-ai/dsh-web`、`@deepseek-ai/dsh-tools`、`@deepseek-ai/dsh-system-prompt` 和 Cordis。它从不导入具体的提供方包。 + +## `ctx.web` 契约 + +`ctx.web` 是一个提供方注册表加上一个带提供方选择的执行面。注册表部分与 `LlmService` 保持接近:每种能力类别一个 `Map<id, provider>`,`registerSearchProvider`/`registerFetchProvider` 方法返回 disposer,重复 id 抛出 `WebError`,执行时解析在选定提供方缺失或不可用时抛出异常。权威签名见 `packages/web/web/src/types.ts`;seam 的形状: + +```ts +import type { WebFetchRequest, WebFetchResult, WebSearchRequest, WebSearchResult } from '@deepseek-ai/dsh-web' + +interface WebSearchProvider { + readonly id: string + available(): boolean + search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult> +} + +interface WebFetchProvider { + readonly id: string + available(): boolean + fetch(request: WebFetchRequest, signal?: AbortSignal): Promise<WebFetchResult> +} + +interface WebService { + registerSearchProvider(provider: WebSearchProvider): () => void + registerFetchProvider(provider: WebFetchProvider): () => void + + search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult> + fetch(request: WebFetchRequest, signal?: AbortSignal): Promise<WebFetchResult> +} +``` + +可选的 signal 是执行控制,而非业务输入:`tool-web` 直接传递 `exec.signal`,使轮次取消、工具超时和 agent dispose(资源释放)能到达提供方的网络请求、流读取器和高开销解码。seam 不传递 `ToolExecution`——否则 `dsh-web` 就要依赖 `dsh-tools`。 + +提供方 id 是稳定字符串,在各自的能力类别内唯一。注册重复的搜索提供方 id 或重复的 fetch 提供方 id 会失败,而非静默替换旧提供方。提供方注册返回 disposer,沿用现有的 `ctx.tools.register()`/`ctx.systemPrompt.section()` 模式:变更包裹在 `ctx.effect()` 中,注册随贡献它的 fiber 一起拆除。 + +## 提供方可用性与选择 + +提供方可用性与能力选择是两个独立概念,但都保持最小化。提供方仅报告该具体实现是否可用,通过廉价的本地检查(如凭证是否存在、端点配置是否可解析)。提供方的 `available()` 禁止发起网络调用。 + +`LlmService` 完全没有状态类型:可用性通过注册表成员资格加解析时抛出来表达。`ctx.web` 遵循同样的纪律。seam 不暴露聚合的能力状态查询——`search()`/`fetch()` 在每次调用时根据配置的提供方 id、已注册的提供方和每个提供方廉价的本地 `available()` 布尔值派生选择结果,选择失败就是执行时抛出的结构化 `WebError`。需要知道某项能力能否运行的调用方通过执行并路由该错误来获知;没有任何东西作为可变服务状态存储。 + +该布尔值是选择的输入,而非健康系统。`tool-web` 从不直接调用提供方的 `available()`——它进入 seam 的唯一路径是 `search()`/`fetch()`——因此选择策略只有一个所有者。 + +选择不得依赖注册顺序。Cordis 加载顺序、配置排列和 HMR 时序不是产品语义。 + +| 情况 | 执行行为 | +|---|---| +| 配置的提供方 id 已注册且 `available() === true` | 运行该提供方 | +| 配置的提供方 id 未注册 | 以 `WEB_PROVIDER_CONFIGURED_MISSING` 失败 | +| 配置的提供方 id 已注册但不可用 | 以 `WEB_PROVIDER_CONFIGURED_UNAVAILABLE` 失败 | +| 未配置提供方 id,且该类别恰好有一个已注册且可用的提供方 | 运行该唯一提供方 | +| 未配置提供方 id,且该类别无已注册提供方 | 以 `WEB_PROVIDER_UNAVAILABLE` 失败 | +| 未配置提供方 id,且该类别有多个可用提供方已注册 | 以 `WEB_PROVIDER_AMBIGUOUS` 失败,而非按注册顺序选择 | +| 未配置提供方 id,且有提供方存在但均不可用 | 以 `WEB_PROVIDER_UNAVAILABLE` 失败 | + +「唯一提供方自动选择」规则面向测试、演示和简单部署。产品配置设置显式提供方 id: + +```yaml +- id: web + name: '@deepseek-ai/dsh-web' + config: + searchProvider: exa + fetchProvider: local-http + +- id: web-search-exa + name: '@deepseek-ai/dsh-web-search-exa' + +- id: web-search-perplexity + name: '@deepseek-ai/dsh-web-search-perplexity' + +- id: web-search-deepseek + name: '@deepseek-ai/dsh-web-search-deepseek' + +- id: web-fetch-local + name: '@deepseek-ai/dsh-web-fetch-local' + +- id: tool-web + name: '@deepseek-ai/dsh-tool-web' +``` + +运维覆盖走同一条显式选择路径:`DSH_WEB_SEARCH_PROVIDER=perplexity` 等同于配置 `searchProvider: perplexity`,而非 `dsh-tool-web` 内部的隐式优先级链。 + +`ctx.web.search()` 和 `ctx.web.fetch()` 在执行时按上述选择规则解析提供方。如果选定的能力不可用,它们抛出带有结构化代码的 `WebError`,如 `WEB_PROVIDER_UNAVAILABLE`、`WEB_PROVIDER_CONFIGURED_MISSING`、`WEB_PROVIDER_CONFIGURED_UNAVAILABLE` 或 `WEB_PROVIDER_AMBIGUOUS`。如果未显式配置提供方且不存在可用提供方,执行错误是通用的 `WEB_PROVIDER_UNAVAILABLE` 情况;刻意不提供对每个不可用提供方的诊断汇总。 + +## 搜索请求与结果 schema + +面向模型的 `web_search` 工具很小。唯一的面向模型参数是: + +- `query`:必填字符串。 + +`max_results` 不暴露给模型。它是 `dsh-tool-web` 层的决策:工具设定结果上限——`searchMaxResults` 插件配置,默认 `8`(与 OpenCode 的 Exa 默认值对齐),类似 `dsh-tool-fs` 的 `readLimit`——并作为 `WebSearchRequest` 上的 `maxResults` 传给 seam。将其排除在模型 schema 之外意味着模型只需提问,产品控制返回多少上下文;该字段日后可以提升为面向模型的参数而不破坏 seam。 + +`maxResults` 沿工具 → seam → 提供方流动,上限在返回路径上强制执行: + +- `dsh-tool-web` 拥有该值并将其放在 `WebSearchRequest.maxResults` 上。 +- `ctx.web` 将请求原样传递给选定的提供方。 +- 当提供方的 API 支持结果数量控制时(Exa 的 `numResults`),提供方在请求层应用 `maxResults`,作为成本/延迟优化。 +- `ctx.web` 在结果上强制执行上限:如果提供方返回的 source 数量超过 `maxResults`——因为其 API 没有结果数量控制(Perplexity)或忽略了提示——seam 将 `sources[]` 截断到 `maxResults` 并在返回前将 `WebSearchResult.truncated` 设为 `true`。这使上限成为面向模型层可以依赖的单一跨提供方保证,而非每个提供方都必须记得遵守的东西。 + +seam 请求不携带提供方特有的控制——没有 Perplexity 模型选择、搜索时效性、域名过滤器、Exa `livecrawl`、Exa `type`、区域提示、生成式回答预算或搜索深度。只有当某个字段具有提供方无关的语义,且工具 schema 和选定的提供方都能诚实地遵守时,才会添加。 + +```ts +interface WebSearchRequest { + readonly query: string + /** Upper bound on returned sources; the seam truncates to it. Omitted = no bound. `dsh-tool-web` always sets it. */ + readonly maxResults?: number +} + +interface WebSearchResult { + readonly content?: string + readonly sources: readonly WebSearchSource[] + readonly truncated: boolean +} + +interface WebSearchSource { + readonly url: string + readonly title?: string + readonly snippet?: string + readonly publishedAt?: string +} +``` + +`content` 是可选的提供方生成的回答文本、搜索上下文或摘要。`sources[]` 是可移植的引用面。source 必有 URL;title、snippet 和 `publishedAt` 可选,因为并非每个提供方都返回它们。`title` 不是必填:Perplexity 风格的引用可能只提供 URL,强制适配器编造标题会让 seam 说谎。`dsh-tool-web` 渲染 `title ?? hostname(url)` 风格的回退标签用于展示。`publishedAt` 是可选的发布/抓取时间戳,为 ISO-8601 字符串——Exa 在每条结果上以 `publishedDate` 返回它,Perplexity 在搜索结果上返回 `date`,因此它是真实的提供方数据而非派生值;seam 以字符串形式传递,日期解析留给消费方。 + +Exa 搜索将提供方扁平 `results[]` 的每一项映射为 `WebSearchSource`:`url` ← `url`、`title` ← `title`、`snippet` ← 第一个 `highlights[]` 条目(没有 highlight 的条目没有可移植的 snippet,被丢弃)、`publishedAt` ← `publishedDate`。Exa 不返回提供方生成的回答,因此 `content` 省略。Perplexity 搜索将 `choices[0].message.content` 映射为 `content`,并优先使用结构化的顶层 `search_results[]` 作为 `sources[]`——`url` ← `url`、`title` ← `title`、`snippet` ← `snippet`(常为空)、`publishedAt` ← `date`——仅在 `search_results` 缺失时回退到纯 URL 的 `citations[]` 数组(这些 source 只有 `url`)。如果提供方返回的结构化字段少于 seam 支持的,适配器省略那些可选字段。 + +完整页面获取仍是 `web_fetch(url)` 的职责。搜索 snippet 是发现上下文,不是获取到的页面正文。 + +## Fetch 请求与结果 schema + +`web_fetch` 的实现是一个匿名公开 HTTP(S) fetch 提供方 `local-http`。它从具体 URL 获取字节,应用下述基本传输卫生措施(仅 http/https、拒绝 URL 中的凭证、字节/时间上限、跨源重定向阻断),解码文本内容,并仅返回最小的模型可用结果:最终 URL、状态码、正文和截断标志。它不携带浏览器 cookie、编辑器凭证、git 凭证、内部认证令牌,也不隐式访问私有服务。(完整的 SSRF/私有网络阻断推迟——见[推迟工作](#deferred-work)。) + +seam 请求比 OpenCode 的面向模型工具更小: + +- `url`:必填 HTTP(S) URL。 + +seam 请求刻意不包含逐调用超时、`format`、`prompt` 或提供方特有的提取控制。取消通过直接的可选执行信号实现,fetch 提供方拥有一个部署配置的超时兜底。`format` 是对已获取资源的展示决策;`prompt` 是更高层的 LLM 摘要指令;Firecrawl、Exa、Tavily 或 Parallel 等提取 API 可能不暴露具体的 HTTP 响应。如果产品日后需要提供方支撑的页面提取,那是一个独立的 `web_extract` 能力或对本 seam 的刻意扩展——提取语义绝不通过将每个 HTTP 字段设为可选来偷渡进 `web_fetch`。 + +HTTP 状态码是已获取资源状态的一部分,不自动构成工具失败。成功的网络获取一个 `404` 或 `500` 响应会返回带有状态码和有界解码正文(当内容类型受支持时)的 `WebFetchResult`。`WebError` 用于无法安全获取或表示资源的失败:无效或被阻断的 URL、重定向策略违规、超时、abort、响应过大、不支持的内容类型、提供方失败或网络失败。 + +```ts +export interface WebFetchRequest { + readonly url: string +} + +export interface WebFetchResult { + readonly url: string + readonly statusCode: number + readonly body: WebFetchBody + readonly truncated: boolean +} + +export type WebFetchBody = + | { readonly kind: 'html'; readonly content: string } + | { readonly kind: 'text'; readonly content: string } +``` + +`WebFetchResult.url` 是允许的重定向之后的最终 URL。请求 URL 已在 `WebFetchRequest` 中,因此没有单独的 `requestedUrl`/`finalUrl` 对。 + +`WebFetchBody` 是封闭的可辨识联合类型,因为正文类别需要 seam、提供方和工具三方协调变更,而非独立的插件扩展。穷举 switch 使新类别在每个渲染器处编译失败,直到被处理。独立的对象分支为类别特有字段留出空间。 + +提供方负责安全的资源获取:URL 校验、HTTP 传输、重定向策略、超时、abort 传播、字节上限、字符集解码、内容类型分类和二进制拒绝。`dsh-tool-web` 负责展示:HTML 转 Markdown、HTML 转纯文本、面向模型的截断格式化,以及未来的摘要。 + +fetch 提供方的资源控制: + +- 仅接受 `http:` 和 `https:` URL;拒绝 URL 中的凭证。 +- 强制执行最大 URL 长度、响应字节上限、解码正文字符上限、超时和重定向跳数上限。 +- Abort 信号传播到网络获取和高开销解码。 +- 仅自动跟随同源重定向;跨源重定向以 `WEB_REDIRECT_BLOCKED` 失败,要求一次新的工具调用,从而触发新的提供方/权限决策。(Claude Code 的 WebFetch 使用同样的模型——它不自动跟随跨主机重定向,而是将重定向目标返回给模型以发起新调用。) +- 请求携带显式的产品 User-Agent,而非静默伪装浏览器。 + +SSRF/私有网络防护(阻断私有、回环、链路本地、多播及其他非公开目的地,通过先 DNS 解析再验证 IP 来防御 rebinding,并在重定向的每一跳重新验证)**推迟**——见[推迟工作](#deferred-work)。在其落地之前,`web_fetch` 是一个 SSRF 原语,不得在能触达敏感内部网络目标的部署中启用。 + +## 工具消费方行为 + +`dsh-tool-web` 拥有两个 `ToolDefinition`:`web_search` 和 `web_fetch`。它拥有面向模型的 JSON Schema、snake_case 参数名、提示词段落、结果渲染为 `ContentBlock[]`、`presentCall` 和 `presentResult`。 + +`dsh-tool-web` 禁止枚举提供方或直接调用提供方的 `available()`。它进入 seam 的唯一路径是 `ctx.web.search()`/`ctx.web.fetch()`。这将提供方选择保持在单一层;否则工具包可能判定某个提供方可用,而执行时解析出不同的状态。 + +工具注册是最小化的稳定同步:插件启动时,`dsh-tool-web` 的 `Config`(`search?: boolean`、`fetch?: boolean`,均默认 `true`)启用或禁用每个 web 工具;已启用的工具通过基于 effect 的注册表以 fiber 作用域的 disposer 注册;任何工具都不会仅因其选定的提供方缺失、不可用或存在歧义而被 dispose;dispose `tool-web` fiber 时自动拆除其注册。 + +提供方可用性变化影响执行结果和诊断信息,而非面向模型的 schema 是否存在。如果产品完全不需要 web 工具,在配置中禁用 `dsh-tool-web` 或单个 web 工具即可;如果需要 web 工具但后端配置有误,模型在执行时看到结构化的工具错误。 + +提示词引导解释了语义分工——`web_search` 用于发现和获取当前信息,`web_fetch` 用于模型需要特定 URL 内容的场景——提示词和工具结果告诉模型用 Markdown 链接引用相关 URL。 + +面向模型的输出以文本为先,因为工具结果是 `ContentBlock[]`,但 seam 的产出保持结构化,以便 UI 展示和未来的适配器无需解析渲染后的文本。 + +## 错误 + +`dsh-web` 定义 `WebError extends HarnessError`,带有稳定的错误码,仅覆盖调用方可能合理分支的状态: + +- `WEB_PROVIDER_UNAVAILABLE` +- `WEB_PROVIDER_CONFIGURED_MISSING` +- `WEB_PROVIDER_CONFIGURED_UNAVAILABLE` +- `WEB_PROVIDER_AMBIGUOUS` +- `WEB_DUPLICATE_PROVIDER` +- `WEB_INVALID_URL` +- `WEB_BLOCKED_URL` +- `WEB_REDIRECT_BLOCKED` +- `WEB_FETCH_TOO_LARGE` +- `WEB_FETCH_TIMEOUT` +- `WEB_ABORTED` +- `WEB_UNSUPPORTED_CONTENT_TYPE` +- `WEB_PROVIDER_ERROR` + +`WEB_DUPLICATE_PROVIDER` 在 `registerSearchProvider`/`registerFetchProvider` 发现该能力类别中已有相同 id 时同步抛出(类似 `LlmService` 的 `DUPLICATE_ADAPTER`);它是注册时的编程错误而非执行结果,但共享 `WebError` 码空间,使调用方看到统一的分类体系。`WEB_PROVIDER_ERROR` 是提供方自身失败通过 seam 浮出的兜底码,包括 `web-fetch-local` 中的网络/传输失败(DNS、连接拒绝、TLS);刻意不设单独的 `WEB_NETWORK` 码——提供方设置描述性消息,使模型和日志能区分网络失败与提供方 API 失败。 + +工具执行让这些错误流经 `ToolRegistry.execute()`,后者已将 `HarnessError` 转换为带结构化元数据的错误工具结果。模型得到可读的错误消息;钩子、测试和 UI 代码可以根据稳定的错误码路由。 + +## 测试 + +每一层在自己的 seam 处固定:`dsh-web` 中的注册/选择/截断/abort 契约与 `WebError` 码;每个提供方基于录制的 fixture(测试前置数据)的请求/响应映射(Perplexity fixture 包含纯 URL 引用,以保持可选 source 字段的诚实性),加上每个真实提供方的自跳过带密钥冒烟测试;`web-fetch-local` 中的真实本地 HTTP 行为;`dsh-tool-web` 中通过真实工具注册表的启用驱动注册、结构化执行错误和结果格式化。一个真实 Loader 冒烟测试守护两种导出形状([事后分析 0001](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md)):`dsh-web` 是默认导出的服务,而提供方和 `tool-web` 是命名空间插件,误加 `export default` 会丢失 `inject`。 + +## 曾考虑的替代方案 + +### 让每个提供方注册自己的面向模型工具 + +这与最灵活的提供方插件系统一致:每个提供方可以暴露其完整的原生 schema。在 harness 中被否决,因为它将面向模型的名称、描述、提示词引导和结果格式化的所有权交给了提供方包。多个搜索提供方会产生重复的工具名或提供方特有的工具名,模型将学到后端细节而非稳定的产品能力。 + +### 将提供方调度直接放在 `dsh-tool-web` 中 + +这类似 OpenCode 的本地 web 搜索:一个稳定的 `websearch` 工具在内部调度到 Exa 或 Parallel。对于小型产品路径可以接受,但作为 harness 基础是错误的。工具包将拥有提供方选择、凭证、请求映射、传输、响应解析和展示,使得在不将 Exa 和 Perplexity 的差异烘焙进工具 schema 的情况下难以添加它们。 + +### 将搜索和 fetch 拆为两个 seam(`dsh-search`、`dsh-fetch`) + +很有吸引力,因为两半不共享请求 schema 和业务逻辑,各自能干净地映射到 bash/fs 的三包模板上,且 `WebService` 上的 `Search`/`Fetch` 方法对重复也会消失。否决,因为共享的机制——提供方 id 注册表、不依赖注册顺序的选择策略、abort 传播、`WebError` 分类体系,以及面向产品的「这个 harness 如何触达 web」配置面——是真实存在的,否则会在两个几乎相同的 seam 之间重复。一个 `ctx.web` 中间层给产品一个统一的注入和配置对象,给提供方选择一个唯一的所有者。代价是并行的 `searchX`/`fetchX` 方法对,这是有意接受的。 + +### 选择第一个注册的提供方 + +否决。注册顺序不是产品策略。它可能随配置顺序、插件加载、HMR 或重构而变化。提供方选择必须是显式的,或仅在恰好只有一个可用提供方时自动选择。 + +### 将 Firecrawl/Exa/Tavily/Parallel 提取视为 fetch + +在第一版中否决。这些提供方通常返回提取或摘要后的内容,而非具体的 HTTP 响应。如果产品需要提取,日后设计 `web_extract` 或刻意扩展 fetch seam。 + +### 镜像 Claude Code 的 `url + prompt` WebFetch 形状 + +在 seam 层面否决。`prompt` 将 fetch 变成 LLM 摘要,并将公开 web 获取耦合到模型提供方。harness seam 应当确定性地获取和解码;`dsh-tool-web` 日后可以将摘要作为展示模式提供,而无需让 `ctx.web` 依赖 `ctx.llm`。 + +## 后果 + +**搜索 schema 刻意精简。** Exa 和 Perplexity 都暴露了有用的提供方特有控制;只有当某个控制能以提供方无关的方式定义、且工具注册和提供方执行都能诚实遵守时,才会添加。 + +**Perplexity 引用可能稀疏。** 一条引用可能只有 URL。将 `title` 和 `snippet` 设为可选使 seam 保持诚实,但意味着 `tool-web` 需要渲染回退标签。 + +**稳定的工具注册将配置错误推迟到执行时。** 当产品启用了 web 访问时,保持工具可见是正确的;但期望 web 搜索可用的产品应用应当醒目地浮出结构化的 `WEB_PROVIDER_CONFIGURED_MISSING`/`WEB_PROVIDER_CONFIGURED_UNAVAILABLE`/`WEB_PROVIDER_AMBIGUOUS` 失败,使用户不会在模型调用工具后才发现配置问题。 + +**提供方状态可能在启动后变化。** 一个工具可能在步骤开始时组装的请求中可见,但在执行前失去其提供方。执行路径重新解析并以结构化错误失败。 + +**Fetch 是网络边界,不仅仅是只读工具。** `web_fetch` 能触达敏感网络目标或通过 URL 外泄数据。仅交付基本传输卫生措施(仅 http/https、拒绝凭证、字节/时间上限、跨源重定向阻断);SSRF/私有网络阻断推迟(见[推迟工作](#deferred-work)),因此在其落地之前,`web_fetch` 不得在能触达内部目标的环境中启用。 + +**大量 web 内容可能损害上下文质量。** 提供方强制执行字节/字符上限并报告 `truncated`;`tool-web` 格式化有界的模型输出,附带清晰的继续或后续引导。 + +## 推迟工作 + +- `web_fetch` 的 SSRF/私有网络防护:阻断私有、回环、链路本地、多播及其他非公开目的地,使 `web_fetch` 不再是 SSRF 原语。正确实现不仅仅是 URL 字符串检查——需要先 DNS 解析再连接到已验证的 IP(防御 DNS rebinding/TOCTOU)、跨重定向的每跳重新验证,以及 IPv6 边缘处理(私有范围、IPv4 映射地址)。所调研的参考实现均未做 IP 级阻断(OpenCode 做前缀检查后直接 fetch;Claude Code 依赖集中式主机名黑名单加「私有 URL 会失败」的提示词),因此没有可复制的实现,且这是 harness 唯一的 SSRF 防线——值得一次专门的设计/spike。在其落地之前,`web_fetch` 只能在无法触达敏感内部目标的部署中启用。 +- `pdf` `WebFetchBody` 类别:`local-http` 提供方将可文本提取的 PDF 解码(尽力而为、有上限、`truncated`)为 `{ kind: 'pdf'; content; pageCount? }` 分支,`tool-web` 渲染它。这是 fetch 而非 `web_extract`——PDF 获取是具体的 HTTP 200 加确定性的本地解码,不是提供方侧对非 HTTP 资源的提取。添加它是跨 `dsh-web`(声明分支)、提供方(解码 + 将「二进制拒绝」收窄为「拒绝二进制,但可文本提取的 PDF 除外」;需要 OCR 的扫描/图片 PDF 不在范围内)和 `tool-web`(渲染)的协调变更。封闭的 `WebFetchBody` 联合类型使消费方在新分支被处理之前编译失败。 +- 提供方支撑的提取作为独立的 `web_extract` 能力,而非静默扩展 `web_fetch`。 +- 推迟的权限系统落地后的权限策略集成。 +- `query` 和 `maxResults` 之外的提供方无关搜索控制,待 Exa 和 Perplexity 都能诚实遵守时再添加。 + +## 开放问题 + +- 产品应用包是否应在启动时探测 web 配置(当 web 被显式配置时将 `WEB_PROVIDER_CONFIGURED_MISSING`、`WEB_PROVIDER_CONFIGURED_UNAVAILABLE` 和 `WEB_PROVIDER_AMBIGUOUS` 视为致命错误),还是将配置错误留到首次执行时浮出? +- 推迟的权限系统落地后,公开 web 访问的权限策略应放在哪里:`tools/execute` 上的专用 web 权限插件、提供方配置,还是两者兼有? diff --git a/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.i18n.yaml new file mode 100644 index 0000000000..614868ada0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-26-file-context-as-event-gate.md: 4700222aa2e0f91d9f355495c228e2eb92825f55 +2026-06-26-file-context-as-event-gate.zh.md: 21c8706bcc14790a5092fa59e03bce329049760a diff --git a/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.md b/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.md index 3f34cf3559..4700222aa2 100644 --- a/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.md +++ b/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-26-file-context-as-event-gate.zh.md) + ## Problem [The split-fs-seam Agent Note](../simplification/2026-06-26-fsspec-style-fs-seam.md) put `ctx.fileContext` between the model-facing tools and the `ctx.fs` provider: `dsh-tool-fs` injects `fileContext` and routes every `read`/`write`/`edit` through its methods. That makes `fileContext` **in-path and mandatory**. The tool cannot reach `ctx.fs` without it, the policy layer owns the fs I/O and the read windowing, and a deployment that does not want observed-state policy cannot simply drop the package — `dsh-tool-fs` would fail to resolve `ctx.fileContext`. diff --git a/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.zh.md b/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.zh.md new file mode 100644 index 0000000000..21c8706bcc --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.zh.md @@ -0,0 +1,171 @@ +# Agent Note: 将 `dsh-fs-policy` 改为事件门控插件,而非方法接口 + +Status: implemented + +[English](2026-06-26-file-context-as-event-gate.md) | 中文 + +## 问题 + +[拆分文件系统 seam Agent Note(agent 决策记录)](../simplification/2026-06-26-fsspec-style-fs-seam.md) 在面向模型的工具与 `ctx.fs` 提供方之间放置了 `ctx.fileContext`:`dsh-tool-fs` 注入 `fileContext`,并将每次 `read`/`write`/`edit` 路由到它的方法。这使得 `fileContext` **位于关键路径上且不可省略**。工具不经过它就无法访问 `ctx.fs`,策略层掌控着 fs I/O 和读取窗口,而一个不需要观测状态策略的部署也无法简单地移除该包——`dsh-tool-fs` 会因无法解析 `ctx.fileContext` 而失败。 + +这把三件本应可分离的事情耦合在了一起: + +1. **工具做什么**——解析路径、读取窗口、写入/编辑文件。这是工具的职责,只需要 `ctx.fs`。 +2. **新鲜度/观测策略**——「编辑前必须先读」、「写入/编辑必须基于你读到的版本」。这是 `dsh-fs-policy` 插件的职责。 +3. **观测状态的记录**——一个副作用,永远不应阻止工具正常运行。 + +由于工具调用的是 `fileContext` 方法,移除策略层就是一个破坏性变更,而非优雅地失去一个*附加*能力。策略层对工具的运行是承重性的,而非可选的收紧。 + +## 决策 + +反转控制流。**`dsh-tool-fs` 成为执行器,直接调用 `ctx.fs`**;**`dsh-fs-policy` 成为门控 + 记录插件**,通过事件参与,从不通过工具调用的方法,也不注册 `ctx.fileContext` 服务。 + +```text +tool dsh-tool-fs executor: resolves, reads windows, writes/edits via ctx.fs; + emits fs policy events; renders results +policy dsh-fs-policy plugin: listens to fs/write-intent + + fs/edit-intent (single-slot waterfall) and fs/observed + (emit) events; adds observed-state + freshness. +provider seam dsh-fs ctx.fs: text IO + ATOMIC mutation primitives whose version + guard is OPTIONAL; owns the fs policy event vocabulary +provider dsh-fs-local local implementation of ctx.fs +``` + +该模型是叠加式的:裸 `ctx.fs` 执行原子化、无约束的文本 I/O,而 `dsh-fs-policy` 叠加观测状态、先读后编辑和版本守卫。因此移除策略层后工具仍可用,只是不受约束。正式发布的 agent 配置会加载策略;裸模式的存在是为了让策略在服务边界保持可选,而非作为正常部署姿态。 + +`dsh-tool-fs` 不再注入 `fileContext`。它注入 `fs` 和 `tools`/`systemPrompt`。 + +## 策略由提供方 CAS 强制执行,而非 `dsh-fs-policy` 的 stat + +`dsh-fs-policy` 强制执行「你必须基于你读到的版本来写入/编辑」,**自身从不调用 `stat` 或比较版本**。它将观测到的版本作为 CAS 基准提供,让提供方的 mutation 临界区检测陈旧性: + +- 「你读过这个文件吗?」是 `dsh-fs-policy` 在本地决定的唯一事项——一次 `WeakMap` 查找,无 I/O。无记录 ⇒ `FS_NOT_OBSERVED`。 +- 「你读到的版本是否仍为最新?」由 **`ctx.fs.editText`/`writeText` 内部**决定,在执行 read-match-rename 的同一个原子锁中完成。`dsh-fs-policy` 将 `vObserved` 作为期望值传入;如果文件已变更,提供方抛出 `FS_STALE_VERSION`。 + +这是有意为之的。如果 `dsh-fs-policy` 在其 waterfall(瀑布式事件)处理器中 stat 并比较版本,该检查与工具实际写入之间会存在 TOCTOU 间隙——文件可能在此期间变化,因此该检查只是一个虚假保证,提供方的锁无论如何都要兜底。将版本检查放在提供方的临界区中既无竞态又无额外 `stat`。所以 `dsh-fs-policy` **不做**任何文件系统 I/O;「必须基于最近一次读取」的保证由 CAS *实现*,`dsh-fs-policy` 只负责选择基准(`vObserved`)并对先前观测进行门控。 + +## 提供方契约变更:版本守卫变为可选 + +为使裸提供方不受约束,其两个 mutation 上的版本守卫变为**可选**——传入则守卫,省略则无条件执行: + +```ts ignore-check +// writeText: expected is now optional. The FsWriteIntent union is UNCHANGED. +writeText(target: FsTarget, content: string, expected?: FsWriteIntent, signal?: AbortSignal): Promise<FsWriteOutcome> +// undefined → unconditionally create-or-overwrite (bare default) +// createIfAbsent → create only, reject an existing file (dsh-fs-policy, unobserved) [unchanged] +// replaceIfVersion → overwrite only at the observed version, else FS_STALE_VERSION [unchanged] + +// editText: expected becomes optional (was the required { version: FsVersion }). +editText(target: FsTarget, edit: FsEditRequest, expected?: { version: FsVersion }, signal?: AbortSignal): Promise<FsEditOutcome> +// undefined → unconditionally replace literal text in the current content (bare default); +// a missing target still reports FS_STALE_VERSION +// { version } → edit only at that version, else FS_STALE_VERSION (the current behavior) +``` + +`FsWriteIntent` 联合类型本身不变——第三种「无条件」状态通过*省略* `expected` 来表达,因此两个 mutation 共享同一种对称形状(`expected?`:省略 = 无守卫,传入 = 有守卫)。这对 `dsh-fs-policy` 使用的有守卫路径保持完全向后兼容;只有之前不可能出现的「无守卫」情况是新增的,且它是裸提供方的默认行为。无论哪种情况,mutation 仍在后端的 per-target 锁内运行,因此无条件写入/编辑仍是原子的(不会产生撕裂文件);「无条件」去掉的是*版本*前置条件,而非原子性。`editText` 在有守卫和无守卫路径上都将缺失目标报告为 `FS_STALE_VERSION`,保持一个统一的编辑失败码表示「此刻无法编辑该目标」。 + +## 事件词汇(由 `dsh-fs` 拥有) + +事件定义在 `@deepseek-ai/dsh-fs` 中,而非 `dsh-fs-policy` 中。这是解耦契约所迫:`dsh-tool-fs` 是发射方,因此它必须引用事件类型,且即使 `dsh-fs-policy` 不再提供方法服务,它也必须能编译通过。`dsh-fs` 是 `dsh-tool-fs` 和 `dsh-fs-policy` 都已依赖的包,因此它是唯一能让发射方和策略监听方共享词汇而不让发射方依赖策略插件的归属地。 + +这些事件携带既有的 `dsh-fs` 词汇(`FsTarget`、`FsVersion`、`FsWriteIntent`)加一个不透明的 actor——不携带面向模型的概念(行窗口、行号或渲染后的页脚不会泄漏到此层)。 + +**两个 `fs/*` 决策事件是单槽、先到先得的 waterfall。** `dsh-fs-policy` 不调用 `next()` 直接返回,因此在默认部署中它占据该槽位;更早注册或使用 `prepend` 的监听器会替代该策略。权限、审计和沙箱关注点仍留在可组合的 `tools/execute` waterfall 上。 + +actor 在 `dsh-fs` 中类型为 `object`——一个纯粹的不透明载体,提供方 seam 从不读取或收窄它。owner 的推导(`actor.agent?.session`)和 `{ agent?: { session? } }` 结构形状完全留在 `dsh-fs-policy` 内部,由其在监听器中将 `object` actor 收窄为该形状。`dsh-fs` 拥有事件名和 fs 词汇;它不拥有策略层的运行时 owner 结构。 + +```ts +import type { FsTarget, FsVersion, FsWriteIntent } from '@deepseek-ai/dsh-fs' + +interface Events { + /** + * Single-slot decision: produce the write expectation for the next + * ctx.fs.writeText. The default returns undefined (unconditional create-or- + * overwrite — the bare provider). The policy listener returns createIfAbsent + * (unobserved) or { kind: 'replaceIfVersion', version: vObserved } (observed). + * The listener does NOT call next(): one decision, not a composable chain. @mode waterfall + */ + 'fs/write-intent'(target: FsTarget, actor: object | undefined, next: () => FsWriteIntent | undefined | Promise<FsWriteIntent | undefined>): Promise<FsWriteIntent | undefined> + /** + * Single-slot decision: produce the optional version guard for the next + * ctx.fs.editText. The default returns undefined (unconditional edit of the + * current content — the bare provider; no stat). The policy listener returns + * { version: vObserved }, or throws FS_NOT_OBSERVED if the actor is unset or + * has not observed the target. Does NOT call next(): one decision. @mode waterfall + */ + 'fs/edit-intent'(target: FsTarget, actor: object | undefined, next: () => { version: FsVersion } | undefined | Promise<{ version: FsVersion } | undefined>): Promise<{ version: FsVersion } | undefined> + /** + * Record that an actor observed a target at a version, after a successful + * read/write/edit. Fire-and-forget (plain emit). Listeners MUST be + * synchronous, side-effect-only recorders (`dsh-fs-policy`'s is a WeakMap + * write); the tool does not guard the emit, so a throwing listener surfaces as + * the tool's isError result. No listener ⇒ nothing recorded. + * @mode emit + */ + 'fs/observed'(target: FsTarget, version: FsVersion, actor: object | undefined): void +} +``` + +`fs/*` 决策事件是**由工具分发的无绑定 waterfall**(类似 `agent/request`,由循环分发且无 `this`),而非服务绑定的 waterfall(如 `llm/stream`)。分发者是 `dsh-tool-fs` 插件,它不是一个服务。 + +## 工具契约(`dsh-tool-fs`) + +工具保留其面向模型的 schema(`read`/`write`/`edit`,逐字节不变)和提示词段落。提示词引导仍以策略优先,因为加载 fs 工具的部署预期也会加载 `dsh-fs-policy`:模型仍被告知在覆写或编辑前先读取,任何声称「后端」要求如此的措辞应修正为 fs-policy 插件要求如此。裸提供方回退不改变提示词立场。 + +`dsh-tool-fs` 获得从旧 `fileContext` 方法服务迁移来的执行器职责,包括**读取渲染**(`read-render.ts`:`buildWindow` + `formatReadOutput`、`READ_MAX_BYTES`、`READ_MAX_LINE_LENGTH`、`FileReadOutcome`/`FileTextLine`,以及 `read.ts` 中的 `STREAM_MIN_SIZE`),这些现在是工具的渲染细节,因为读取已由工具拥有。这些读取渲染类型和辅助函数移入 `dsh-tool-fs`;策略插件不得继续作为工具的类型依赖。 + +`dsh-tool-fs` 是一个注册全部三个工具(`read`/`write`/`edit`)的单一根插件,与 `dsh-tool-bash` 相同。它注入 `fs`(加 `tools`/`systemPrompt`),从不注入 `fileContext`。(最初的提案还将每个工具作为 `/read`/`/write`/`/edit` 子路径插件暴露,供聚焦部署使用;实现时被放弃——没有消费方需要单工具部署,且子路径发布迫使引入兄弟工具包都不需要的定制 `tsdown`/`tsconfig`/`files`/workspace-constraint 处理。每工具的注册辅助函数(`applyReadTool`/`applyWriteTool`/`applyEditTool`)仍作为根插件组合的内部模块保留。) + +通过让 waterfall 惰性产出期望值来最小化 `stat` 预算——裸默认返回 `undefined`(无守卫),从不 stat: + +- **read**——一次 `stat`(类型 + 大小路由 + 版本),然后 `readText`/`streamText`,然后 `buildWindow`,然后 `emit('fs/observed', target, info.version, exec)`。旧 `fileContext.read` 中读后确认的 `stat` 被移除;在路由 stat 和读取之间竞争的写入者最多只能使*后续*有守卫的编辑误报 `FS_STALE_VERSION`(为安全起见拒绝写入:模型会重新读取;由于 `editText` 会在其锁内复查,模型绝不会基于错误版本写入)。 +- **write**——`expectation = await ctx.waterfall('fs/write-intent', target, exec, () => undefined)`,然后 `ctx.fs.writeText(target, content, expectation)`,然后 `emit('fs/observed', target, outcome.version, exec)`。无论是否有 `dsh-fs-policy`,**工具内零 stat**。 +- **edit**——`expectation = await ctx.waterfall('fs/edit-intent', target, exec, () => undefined)`,然后 `ctx.fs.editText(target, edit, expectation)`,然后 `emit('fs/observed', target, outcome.version, exec)`。两种情况下**工具内零 stat**:裸默认为 `undefined`(无条件编辑),因此工具从不 stat 来制造基准。如果目标不存在,提供方即使在无守卫路径上也报告 `FS_STALE_VERSION`。 + +工具在每次分发时将 `exec`(工具执行上下文)作为 `actor` 参数传入,以便 `dsh-fs-policy` 推导其观测状态的 owner。工具不知道策略插件是否存在:它始终在 `next` thunk 中提供裸默认行为,而 `dsh-fs-policy` 在默认部署中会在 thunk 运行前短路它。 + +**`fs/observed` 在操作成功后触发。** 其监听器必须是同步、不抛异常的记录器;工具不对 plain emit 做保护,因此抛异常的监听器会在 mutation 已成功后报告失败。异步或可失败的观测需要另一份事件契约。 + +## 策略插件契约(`dsh-fs-policy`) + +`dsh-fs-policy` 是插件,不是服务。它不注册 `ctx.fileContext`,没有公开方法面,不暴露 `read`/`write`/`edit`/`resolve` 方法。它通过 `ctx.on()` 注册三个监听器(每个返回一个 disposer 用于 HMR)。它维护观测状态 `WeakMap<owner, Map<targetKey, { version }>>`,以及结构化的 owner 推导(将事件中不透明的 `object` actor 收窄为自己的 `{ agent?: { session? } }` 形状),但不注入 `fs`——每个处理器只操作自己的 `WeakMap`,从不操作 `ctx.fs`。 + +- `fs/write-intent` 监听器:`prior = getObserved(owner, key)`;返回 `prior ? { kind: 'replaceIfVersion', version: prior.version } : { kind: 'createIfAbsent' }`。它不调用 `next()`:完全占据单一决策槽位。 +- `fs/edit-intent` 监听器:`prior = getObserved(owner, key)`;如果无 `owner` 或无 `prior`,抛出 `FS_NOT_OBSERVED`;否则返回 `{ version: prior.version }`。同样不调用 `next()`。 +- `fs/observed` 监听器:`record(owner, key, version)`。 + +一条观测状态条目是**先前观测记录**:成功的 `read`、`write` 或 `edit` 都会 emit `fs/observed` 并记录 `{ version }`,因此条目的存在意味着「此 owner 在此版本观测过此目标」,而非狭义的「已读取过」。这使得 create-then-edit 或 edit-then-edit 序列无需中间重新读取即可工作:mutation 将记录的版本刷新为自身的结果,因此下一次编辑的基准就是它刚产出的版本。`FS_NOT_OBSERVED` 只拒绝完全没有任何先前观测的编辑。owner 从 `{ agent?: { session? } }` 结构化推导;dispose 时丢弃所有状态(HMR 安全)。 + +`dsh-fs-policy` 现在是一个纯策略/记录插件,没有服务面——它只通过事件 seam 影响外界。这正是移除 `dsh-tool-fs` 方法耦合的关键。 + +## 裸提供方行为(无 `dsh-fs-policy`) + +这不是预期的部署姿态——加载 fs 工具的配置预期也会加载 `dsh-fs-policy`。它是工具不再耦合于策略方法服务后所存在的无约束提供方下限。当 `dsh-fs-policy` 不存在时,每个 `fs/*` waterfall 落入其 `undefined` 默认值,`fs/observed` 无监听器: + +- **read** 行为不变(它从不需要策略;只是 emit 了一个现在无人监听的 `fs/observed`)。 +- **write** 无条件 create-or-overwrite:`expected` 为 `undefined`,因此 `writeText` 无论文件是否存在、无论当前版本如何都直接写入。无先读要求,无版本检查。 +- **edit** 无条件替换文件当前内容中的字面文本:`expected` 为 `undefined`,因此 `editText` 无版本守卫、无先读要求地匹配并重写(`FS_EDIT_NOT_FOUND`/`FS_AMBIGUOUS_EDIT` 仍适用——它们关乎字面匹配,而非新鲜度)。缺失目标仍报告 `FS_STALE_VERSION`,与有守卫编辑路径的「此刻无法编辑该目标」错误码一致。 + +两个 mutation 仍是原子的(后端的 per-target 锁是无条件的)。仅仅是*不存在*(而非丢失)的是 `dsh-fs-policy` 本会叠加的策略:观测状态、先读后编辑和版本守卫的写入/编辑。加载 `dsh-fs-policy` 后,其监听器返回有守卫的 `expected` 值而非 `undefined`,从而叠加这些约束;裸提供方本身无需任何变更。 + +## 取代关系 + +本 Agent Note 修正——而非推翻——[拆分文件系统 seam Agent Note](../simplification/2026-06-26-fsspec-style-fs-seam.md)。四层拆分、提供方契约和新鲜度*策略*均保留。变更的是**工具与策略层之间的耦合方式**:强制性方法服务变为插件拥有的事件门控,fs I/O + 读取窗口从 `fileContext` 上移至 `dsh-tool-fs`。拆分文件系统 seam Agent Note 中关于 `dsh-tool-fs` 注入 `fileContext` 以及 `fileContext` 拥有 `read`/`write`/`edit` 的描述已在同一变更中更新。 + +## 验证 + +测试固定了两条路径:无 `dsh-fs-policy` 时,根工具插件对 `dsh-fs-local` 启动,read、create、overwrite 和未读 edit 均成功;有策略时,未读 edit 返回 `FS_NOT_OBSERVED`,未读 overwrite 被 `createIfAbsent` 门控。策略决定后,后注册的 intent 监听器不会被触达。陈旧编辑通过提供方 CAS 失败,而策略不执行 `stat`;工具预算在两条路径上保持 read 一次 `stat`,write 或 edit 均为零次。面向模型的 schema 逐字节不变,因此快照不变。 + +## 曾考虑的替代方案 + +- **保留 `ctx.fileContext` 作为关键路径上的方法服务**——[拆分文件系统 seam Agent Note](../simplification/2026-06-26-fsspec-style-fs-seam.md) 最初落地的形态;否决,因为工具无法在没有策略层的情况下运行,使策略对基本操作是承重性的,而非可选的收紧。 +- **策略侧版本检查**(`dsh-fs-policy` 在其 waterfall 处理器中 stat 并比较版本)——否决,因为该检查与工具实际写入之间存在 TOCTOU 间隙;提供方的 mutation 临界区是唯一无竞态的位置,因此策略只选择 CAS 基准并对先前观测进行门控。 +- **每工具 `/read`/`/write`/`/edit` 子路径插件**——实现时放弃:没有消费方需要单工具部署,且子路径发布迫使引入兄弟工具包都不需要的定制 `tsdown`/`tsconfig`/`files`/workspace-constraint 处理;每工具的注册辅助函数仍作为根插件组合的内部模块保留。 + +## 后果 + +- **事件间接层取代方法调用。** 一次 waterfall + emit 不如 `await ctx.fileContext.edit(...)` 直接。收益是移除了工具到策略的方法依赖,同时保留默认策略插件;代价是多一套事件词汇需要学习。通过保持三个事件的窄小范围并在每个事件上记录 default-thunk 语义来缓解。 +- **策略事件位于存储 seam 中。** `dsh-fs` 增加了两个版本决策事件和一个记录事件,尽管它「只是存储」。这是解耦的代价(发射方不能依赖策略插件)。这些事件只携带 `dsh-fs` 词汇加一个不透明的 `object` actor,不携带面向模型的概念,因此 seam 不沾染行窗口/观测策略类型,也不沾染 agent/会话所有者结构。 +- **单一策略占位者,按约定先到先得。** `fs/write-intent`/`fs/edit-intent` 槽位恰好容纳一个决策者;先注册(或 `prepend`)的监听器获胜,其余被短路。`dsh-fs-policy` 占据该槽位是部署约定,而非事件系统强制的不变式——一个先注册的第二决策者会绕过它。这是可接受的,因为第二个 fs 版本策略决策者是配置错误,而非功能。如果未来出现*分层* fs 版本策略的需求,那是一个新 Agent Note(可组合的值传递 seam),而非在这些事件上静默添加第二个监听器。分层的权限/审计/沙箱拦截已有其归属:`tools/execute`。 +- **移除读后确认 stat** 使后续*有守卫*的编辑在 read/write 竞争下偶尔为安全起见拒绝写入(`FS_STALE_VERSION` → 重新读取)。这是丢失的 UX 便利,绝非正确性漏洞;提供方锁仍阻止基于错误版本的写入。 +- **裸提供方不做先读后写/编辑,也不做版本检查。** 没有 `dsh-fs-policy` 的部署允许模型无条件覆写或编辑任何已有文件。这正是保持工具独立于策略服务的有意含义:安全纪律存在于 `dsh-fs-policy` 插件中。省略它的部署是有意选择无约束的文件系统;对于发布 fs 工具的配置而言,这不是预期的姿态。 diff --git a/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.i18n.yaml new file mode 100644 index 0000000000..51d0eb9a78 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-30-bash-stdin-env-trusted-plugin-surface.md: 284cd45a66294dbc9e8207a1e00e9642d32d4e58 +2026-06-30-bash-stdin-env-trusted-plugin-surface.zh.md: 9486f8c35c5060150b072fb673acca5d4167ec1a diff --git a/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md b/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md index cc1de3c53e..284cd45a66 100644 --- a/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md +++ b/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-30-bash-stdin-env-trusted-plugin-surface.zh.md) + ## Problem The hooks subsystem runs external hook commands the way Claude Code and Codex do: a hook is a shell command that receives its event payload as **JSON on stdin** and reads context from a handful of **environment variables** (`CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, `PLUGIN_ROOT`, …). The harness already has a perfectly good command runner behind the `ctx.bash` capability seam ([dsh-bash](../../../../packages/bash/bash) → [dsh-bash-local](../../../../packages/bash/bash-local)), with process-group kills, output truncation/spill, and a credential scrub. Reusing it for hook execution means a hook bridge does not re-implement subprocess plumbing — but the seam had no way to write stdin or set extra env. This Agent Note adds those two inputs. diff --git a/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.zh.md b/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.zh.md new file mode 100644 index 0000000000..9486f8c35c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 在 bash seam 上支持 stdin 与额外 env + +Status: implemented + +[English](2026-06-30-bash-stdin-env-trusted-plugin-surface.md) | 中文 + +## 问题 + +钩子子系统以 Claude Code 和 Codex 的方式运行外部钩子命令:钩子是一条 shell 命令,通过 **stdin 上的 JSON** 接收事件载荷,并从若干**环境变量**(`CLAUDE_PROJECT_DIR`、`CLAUDE_PLUGIN_ROOT`、`PLUGIN_ROOT`……)读取上下文。harness 已经在 `ctx.bash` 能力 seam 后面有一个完善的命令执行器([dsh-bash](../../../../packages/bash/bash) → [dsh-bash-local](../../../../packages/bash/bash-local)),具备进程组终止、输出截断/溢出处理和凭证擦除功能。复用它来执行钩子意味着钩子桥接层无需重新实现子进程管道——但该 seam 此前无法写入 stdin 或设置额外 env。本 Agent Note 添加这两个输入。 + +`stdin` 和 `env` 不构成新的模型能力,因为普通 shell 语法已经能提供两者。环境凭证由 `dsh-bash-local` 的子环境擦除机制保护,而非靠隐藏这些 seam 字段;模型工具参数是静态 JSON,不会展开 shell 变量。因此这些字段服务于受信的进程内调用方(如钩子桥接层),它们需要传递结构化输入和 `CLAUDE_*` 变量,而不必将其嵌入模型可见的 shell 文本。环境变量规则见 [defensive-patterns.md](../../../../docs/defensive-patterns.md)。 + +## 决策 + +在 `BashExecRequest`(模型/插件侧请求)和 `BashExecSpec`(`run`/`start` 所作用的已解析 spec)上**同时**添加 `stdin?: string` 与 `env?: Record<string, string>`,并在 `dsh-bash-local` 中贯穿它们:`resolve()` 原样传递,`run()`/`start()` 将其传给 `runBash`,后者把字节写入子进程的 stdin 并合并额外 env。 + +三个有意为之的选择: + +1. **模型侧工具不暴露 `stdin` 和 `env`。** Shell 语法已覆盖这些需求,重复参数只会增加接口面而不带来权限隔离。工具仅从声明的模型参数、signal 和 owner 构建请求;受信的进程内调用方可以直接设置 seam 字段。harness 自有变量使用[托管环境决策](../feature/2026-07-10-agent-session-identity-and-log-location.md)规定的独立 `dshEnv` 通道,因此普通 `env` 无法替换它们。 + +2. **`env` 在凭证擦除之后合并,因此调用方显式设置的条目即使具有凭证形态的名称也会胜出。** 后续的托管命名空间决策保留 `DSH_*`:环境条目会被移除,普通 `env` 无法设置它们,受信的 `dshEnv` 最后合并。完整顺序为 `scrub(process.env, including DSH_*)` → `ENV_OVERRIDES` → 普通 `env` → `dshEnv`。 + +3. **`stdin`/`env` 在已解析 spec 上是 required-absent-OK(普通 optional),而非像 `owner` 那样 required-but-nullable。** `owner` 之所以是 required-but-nullable,是因为*静默*缺失的 owner 会产生一个无主、跨会话可读的任务——一个安全隐患,显式的 `undefined` 可以防范。`stdin`/`env` 没有这种风险:缺失意味着「无 stdin / 无额外 env」,这是安全的常规情况(所有模型驱动的调用都如此)。因此它们保持普通 optional,与 `signal` 一致。 + +`dsh-bash-local` 仅在有字节需要写入时才创建 stdin 管道;否则 fd 0 仍为 `/dev/null`,保持先前行为。它写入字节后关闭管道。子进程未读取即退出时产生的 `EPIPE` 被忽略,因为命令退出码和输出决定结果。 + +## 曾考虑的替代方案 + +**可配置的环境秘密擦除。** 否决,属于推测性需求。受信调用方可以在擦除之后显式提供所需值,无需削弱默认的环境保护。 + +## 后果 + +钩子桥接层通过既有的 bash seam 传递 JSON 载荷和钩子特定变量,保留其进程组终止、截断和溢出行为。模型接口面不变,bash 工具仍是模型调用请求构建的唯一所有者。相关词汇定义见 [bash 数据结构参考](../../../../docs/core-data-structures/bash.md)。 diff --git a/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.i18n.yaml new file mode 100644 index 0000000000..c446db0d3f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-30-event-domain-semantics.md: 1f3452cce0235718c35d71577d7013f3e647648c +2026-06-30-event-domain-semantics.zh.md: ec2da7786e80fb6a0df9ff338d77a50e7b3ef569 diff --git a/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.md b/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.md index 56c3fdf231..1f3452cce0 100644 --- a/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.md +++ b/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-30-event-domain-semantics.zh.md) + ## Problem The harness extends the agent loop through a Cordis event taxonomy (see [the microkernel event-taxonomy Agent Note](2026-06-11-microkernel-event-taxonomy.md)). As that taxonomy grew, the line between the three event domains blurred: @@ -18,13 +20,13 @@ This vocabulary is the foundation for interception decisions, the durable `hook/ **Three domains, one job each, with a single boundary rule.** -- **`session/*` — the durable, replayable FACT log.** Owns `SessionEventMap`; every entry is JSON-only (no live objects). One `session/event` emit per append, plus the `session/flush` parallel durability checkpoint. It is also the live transcript feed: a consumer that wants to render or react to what happened subscribes here, so live rendering and `session/load` replay share one path. +- **`session/*` — the durable, replayable FACT log.** Owns `SessionEventMap`; every entry is JSON-only (no live objects). One `session/event` emit per append, plus the `session/flush` parallel durability checkpoint. It is also the live transcript feed: a consumer that wants to render or react to what happened subscribes here, so live rendering and replay projections share one path. - **`agent/*` — the LIVE runtime surface.** Always carries the live `Agent`. Two shapes: INTERCEPTION waterfalls (`agent/request`, `agent/step-result`, `agent/turn-continuation`) that mutate or veto, and TRANSIENT emits (`agent/status`, `agent/error`, `agent/created`/`agent/disposed`, `agent/queued`) that notify with the `Agent` in hand. Turn and step BOUNDARIES are NOT here — they are durable session events read off `session/event`, and so are the token stream (`assistant/chunk`) and mid-turn steering (`steering/message`). - **`tools/*` — the tool registry + execution seam.** **The boundary rule:** a durable, replayable fact is a `SessionEvent`; a live interception or a transient/live-object signal is an `agent`/`tools` Cordis event. A turn or step boundary is a durable fact, so it lives in the session log and is read off the `session/event` feed — it is NOT mirrored as an `agent/*` emit. -**Applying the rule to the boundary twins:** all four boundary mirrors — `agent/turn-start`, `agent/turn-end`, `agent/step-start`, `agent/step-end` — are **REMOVED**. No production consumer needs the live `Agent` at a boundary: the ACP bridge settles from `session/event` `turn/end` plus `agent/status`, and the only turn-mirror consumer (`dsh-ui-stdio`, a disposable test REPL) renders boundaries from `session/event` while retaining its live target object for the fixed `main` label. The step mirrors were removed first (they had no consumer at all); the turn mirrors followed once ui-stdio was migrated — see [the remove-boundary-mirror-events Agent Note](../simplification/2026-06-20-remove-agent-boundary-mirror-events.md), which owns that decision. Removing the emits also simplifies the loop's `closeStep`/`closeTurn` (one append each, no paired emit). +**Applying the rule to the boundary twins:** all four boundary mirrors — `agent/turn-start`, `agent/turn-end`, `agent/step-start`, `agent/step-end` — are **REMOVED**. No production consumer needs the live `Agent` at a boundary: the ACP bridge correlates its in-flight prompt with the exact `session/event` `turn/start`/`turn/end` pair, and other transcript consumers likewise derive boundaries from the durable stream. See [the remove-boundary-mirror-events Agent Note](../simplification/2026-06-20-remove-agent-boundary-mirror-events.md), which owns that decision. Removing the emits also simplifies the loop's `closeStep`/`closeTurn` (one append each, no paired emit). ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.zh.md b/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.zh.md new file mode 100644 index 0000000000..ec2da7786e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 事件域语义——会话是事实日志,agent 是运行时表面 + +Status: implemented + +[English](2026-06-30-event-domain-semantics.md) | 中文 + +## 问题 + +harness 通过 Cordis 事件分类体系扩展 agent loop(智能体循环)(见[微内核事件分类体系 Agent Note](2026-06-11-microkernel-event-taxonomy.md))。随着该分类体系的增长,三个事件域之间的界限变得模糊: + +- `session/*` 承载持久的、事件溯源的日志(`SessionEventMap`)。 +- `agent/*` 承载运行时实时信号,向插件传递 `Agent` 句柄。 +- `tools/*` 承载工具注册表与执行 seam。 + +两个问题促使我们固定语义。第一,若干轮次/步骤边界同时作为持久的 `SessionEvent`(`turn/start`、`turn/end`、`step/start`、`step/end`)和镜像的 `agent/*` emit(`agent/turn-start`、`agent/turn-end`、`agent/step-start`、`agent/step-end`)存在。消费方对同一事实有两个真源,每次生命周期变更都必须同时更新两处。第二,即将到来的钩子子系统需要一个连贯且有文档的订阅表面——插件作者(以及基于其上构建的 Claude Code / Codex 钩子桥接)必须在不阅读循环代码的情况下知道应该监听会话事件还是 agent 事件,以及原因。 + +这套词汇是拦截决策、持久的 `hook/*` 日志,以及 Claude Code 和 Codex 桥接的基础。 + +## 决策 + +**三个域,各司其职,以一条边界规则统一。** + +- **`session/*`——持久的、可回放的事实日志。** 拥有 `SessionEventMap`;每条记录仅含 JSON(无活对象)。每次追加触发一次 `session/event` emit,加上 `session/flush` 并行持久性检查点。它同时也是实时 transcript(文本记录)源:想渲染或响应已发生事件的消费方在此订阅,因此实时渲染与回放投影共享同一路径。 +- **`agent/*`——运行时实时表面。** 始终携带活的 `Agent`。两种形态:拦截 waterfall(瀑布式事件)(`agent/request`、`agent/step-result`、`agent/turn-continuation`)可变更或否决;瞬态 emit(`agent/status`、`agent/error`、`agent/created`/`agent/disposed`、`agent/queued`)在持有 `Agent` 的情况下通知。轮次和步骤边界不在此处——它们是持久的会话事件,从 `session/event` 读取;token 流(`assistant/chunk`)和中途 steering(中途引导)(`steering/message`)同理。 +- **`tools/*`——工具注册表与执行 seam。** + +**边界规则:** 持久的、可回放的事实是 `SessionEvent`;实时拦截或瞬态/活对象信号是 `agent`/`tools` Cordis 事件。轮次或步骤边界是持久事实,因此存在于会话日志中并从 `session/event` 源读取——不会被镜像为 `agent/*` emit。 + +**将规则应用于边界镜像:** 全部四个边界镜像——`agent/turn-start`、`agent/turn-end`、`agent/step-start`、`agent/step-end`——被**移除**。没有生产消费方需要在边界处获取活的 `Agent`:ACP 桥接将其进行中的提示词与精确对应的 `session/event` `turn/start`/`turn/end` 事件对关联,其他 transcript 消费方同样从持久流派生边界。见[移除边界镜像事件 Agent Note](../simplification/2026-06-20-remove-agent-boundary-mirror-events.md),该决策由它负责。移除 emit 也简化了循环的 `closeStep`/`closeTurn`(各只需一次 append,无需配对 emit)。 + +## 后果 + +- 循环不再 emit 任何边界镜像;`closeStep` 仅追加 `step/end`,`closeTurn` 仅追加 `turn/end`。`Session.append` 负责 post-commit observer 隔离,因此抛出异常的边界 observer 无法改变轮次结果或饿死后续消费方;接受或内部校验失败仍会在边界进入日志之前逃逸。 +- 之前通过已移除 emit 观察边界的测试,现在观察持久的 `turn/start`/`turn/end`/`step/start`/`step/end` 会话事件——它们固定的行为(边界顺序、步骤计数)不变;只是读取的源移到了规范源。那些测试*抛出异常的轮次边界 emit 监听器*的用例被删除,因为该代码路径不再存在(没有 emit 可供抛出)。按照 [AGENTS.md「测试记录行为,而非黄金真相」](../../../../AGENTS.md),行为与其测试一同迁移(或一同消亡)。 +- 循环仅在 `append('step/start')` 返回后才标记步骤已打开(`stepOpen = true`)。内部分发校验在日志推入之前运行,可能在不打开步骤的情况下拒绝;post-commit `session/event` observer 的失败被隔离在 `Session.append` 内部。因此该标记精确表示已提交的、欠一个后续 `step/end` 的边界。 +- 完整实现见[简化 Agent Note「停止将持久边界镜像为 agent 事件」](../simplification/2026-06-20-remove-agent-boundary-mirror-events.md):全部四个边界镜像被移除,所有消费方从 `session/event` 读取边界。`agent/steering`(不是边界镜像)不在该 Agent Note 范围内,由其后续 Agent Note [移除 `agent/steering` 镜像 emit](../simplification/2026-07-04-remove-agent-steering-mirror.md) 单独移除——它镜像的是持久的 `steering/message`。 +- Cordis 事件目录(`docs/cordis-catalog/events.md`)重新生成以移除镜像事件。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.i18n.yaml new file mode 100644 index 0000000000..e48cfbacb6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-02-fs-per-session-cwd.md: d3f54e89e735016a373fa14c60123c681b3e7adf +2026-07-02-fs-per-session-cwd.zh.md: ae732a3e4dacc3d4b800044aad60df3f3ce17cc0 diff --git a/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md b/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md index 0a6d9b85b1..d3f54e89e7 100644 --- a/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md +++ b/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md @@ -2,11 +2,13 @@ Status: implemented +English | [中文](2026-07-02-fs-per-session-cwd.zh.md) + ## Problem -The ACP bridge gives every session its own workspace: `session/new` records the editor's project directory as `SessionHeader.cwd`, and `dsh-tool-bash` defaults each bash call's `workdir` to the calling agent's `session.header.cwd` (see [the per-session cwd Agent Note work in `packages/ui/acp`](../../../../packages/ui/acp) and `resolveWorkdir` in `dsh-tool-bash`). So a bash command in session A runs in A's project, and in session B runs in B's — one server process, N workspaces. +The ACP bridge gives every session its own workspace: `session/new` records the automation client's project directory as `SessionHeader.cwd`, and `dsh-tool-bash` defaults each bash call's `workdir` to the calling agent's `session.header.cwd` (see [the ACP package](../../../../packages/acp/acp) and `resolveWorkdir` in `dsh-tool-bash`). So a bash command in session A runs in A's project, and in session B runs in B's — one server process, N workspaces. -Filesystem resolution used one plugin-load cwd while bash used the session project directory. Relative paths therefore disagreed whenever the editor project differed from the server launch directory; snapshots hid the bug by making those paths identical. +Filesystem resolution used one plugin-load cwd while bash used the session project directory. Relative paths therefore disagreed whenever the automation client's project differed from the server launch directory; snapshots hid the bug by making those paths identical. A valid absolute cwd can itself have two apparent parents: when it contains `symlink/..`, filesystem lookup follows the symlink before applying `..`, while `path.resolve()` erases both components lexically. Resolving sandbox policy lexically while launching bash from the raw cwd granted the unrelated lexical parent, denied writes in the real workspace, and let filesystem tools resolve relative paths into the wrong directory. @@ -17,7 +19,7 @@ An ordinary symlink cwd exposes the same distinction when the requested relative Thread the caller's session cwd into path resolution, exactly as `dsh-tool-bash` already does for `workdir`. When either the cwd or the requested path contains a parent segment, resolve the cwd to its native filesystem identity before any lexical join; ordinary cwd spellings stay stable for display when no traversal makes their identity observable. Reuse the resolved sandbox-policy root for mutations and sandboxed bash calls so one call has one workspace identity. The **caller** (the tool) supplies the cwd; the provider does not read a session or agent. - `FileSystem.resolve` accepts `resolve(path: string, opts?: { cwd?: string; signal?: AbortSignal }): Promise<FsTarget>`. `opts.cwd` is the base a RELATIVE `path` resolves against; an absolute `path` ignores it; omitting `opts.cwd` uses the backend's own default. `opts.signal` cancels resolution when the backend performs I/O. The options object keeps both caller-owned resolution controls together without positional growth. -- `dsh-fs-local.resolve` uses `resolveLocalTarget(opts?.cwd ?? this.config.cwd, path)`. `config.cwd` stays the default for a caller that supplies none (non-ACP / no-session use, and the single-session stdio demo where `process.cwd()` IS the workspace). +- `dsh-fs-local.resolve` uses `resolveLocalTarget(opts?.cwd ?? this.config.cwd, path)`. `config.cwd` stays the default for a caller that supplies no session cwd. - `dsh-tool-fs`'s `read`/`write`/`edit` derive the session cwd through a shared `sessionCwd(exec, requestedPath)` helper (`exec.agent?.session.header.cwd`, mirroring bash's `resolveWorkdir`) and pass it to `resolve`. The helper uses native realpath semantics when a parent segment in either value could cross a symlink while retaining ordinary spellings otherwise; a sandboxed mutation reuses the complete policy's `workspaceRoot`; a non-agent / headerless caller yields `undefined`, so the backend applies its default. ## Alternatives considered @@ -30,7 +32,7 @@ The default lives in ONE place — the provider's `config.cwd`. `sessionCwd` ret ## Consequences -- In the ACP demo the fs tools and bash now agree on each session's workspace; an editor can open any project folder and both tool families act on it. +- In the ACP demo the fs tools and bash agree on each session's workspace; an automation client can select any absolute project directory and both tool families act on it. - A session cwd containing `symlink/..`, or an ordinary symlink cwd paired with a parent-traversing relative path, resolves from the same physical workspace for bash, filesystem tools, and the sandbox grant; the lexical parent receives no grant. - No change to `FsTarget` identity: `targetKey` is still the realpath of the resolved absolute path, so observed-state keying and symlink identity are unaffected — a correct per-session cwd produces the same key bash targets. - Backward compatible: every existing `resolve(path)` call (all in tests) keeps working; the new argument is optional. diff --git a/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.zh.md b/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.zh.md new file mode 100644 index 0000000000..ae732a3e4d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 相对文件系统路径按调用方的会话 cwd 解析 + +Status: implemented + +[English](2026-07-02-fs-per-session-cwd.md) | 中文 + +## 问题 + +ACP(Agent Client Protocol)桥接层为每个会话提供独立的工作区:`session/new` 将自动化客户端的项目目录记录为 `SessionHeader.cwd`,`dsh-tool-bash` 将每次 bash 调用的 `workdir` 默认设为调用方 agent(智能体)的 `session.header.cwd`(见 [ACP 包](../../../../packages/acp/acp)与 `dsh-tool-bash` 中的 `resolveWorkdir`)。因此会话 A 中的 bash 命令在 A 的项目目录执行,会话 B 中的在 B 的项目目录执行——一个服务器进程,N 个工作区。 + +文件系统解析使用的是插件加载时的 cwd,而 bash 使用的是会话的项目目录。因此,当自动化客户端的项目目录与服务器启动目录不同时,相对路径的解析结果就会不一致;快照测试因为让这两个路径相同而掩盖了这个 bug。 + +一个有效的绝对 cwd 本身可能看起来有两个父目录:当它包含 `symlink/..` 时,文件系统查找会先跟随符号链接再应用 `..`,而 `path.resolve()` 会从词法上抹掉这两个组件。如果用词法解析沙箱策略却从原始 cwd 启动 bash,就会把权限授予无关的词法父目录、拒绝真实工作区内的写入,并让文件系统工具把相对路径解析进错误目录。 + +普通的符号链接 cwd 在请求的相对路径包含 `..` 时也暴露同一区别:进程从符号链接的物理目标开始遍历,`path.resolve(cwd, path)` 却从其词法拼写开始遍历。因此,对于同一个模型提供的路径,read 会选择与 bash 或沙箱化 mutation 不同的文件。 + +## 决策 + +将调用方的会话 cwd 传入路径解析,与 `dsh-tool-bash` 对 `workdir` 的处理方式完全一致。当 cwd 或请求路径任一包含父目录段时,在任何词法 join 之前把 cwd 解析为原生文件系统标识;没有遍历会使标识可观察时,则保留普通 cwd 拼写以供展示。mutation 和沙箱化 bash 调用复用解析后的沙箱策略根目录,使一次调用只有一个工作区标识。**调用方**(即工具)提供 cwd;提供方不读取会话或 agent。 + +- `FileSystem.resolve` 接受 `resolve(path: string, opts?: { cwd?: string; signal?: AbortSignal }): Promise<FsTarget>`。`opts.cwd` 是相对 `path` 解析时的基准目录;绝对 `path` 忽略它;省略 `opts.cwd` 则使用后端自身的默认值。后端执行 I/O 时,`opts.signal` 可以取消解析。options 对象把调用方拥有的两个解析控制项放在一起,避免位置参数继续增长。 +- `dsh-fs-local.resolve` 使用 `resolveLocalTarget(opts?.cwd ?? this.config.cwd, path)`。`config.cwd` 仍作为调用方未提供会话 cwd 时的默认值。 +- `dsh-tool-fs` 的 `read`/`write`/`edit` 通过共享的 `sessionCwd(exec, requestedPath)` 辅助函数(`exec.agent?.session.header.cwd`,与 bash 的 `resolveWorkdir` 对应)获取会话 cwd,并传给 `resolve`。只要任一值中的父目录段可能跨越符号链接,该辅助函数就使用原生 realpath 语义,否则保留普通拼写;沙箱化 mutation 复用完整策略的 `workspaceRoot`;非 agent/无 header 的调用方得到 `undefined`,后端因此应用其默认值。 + +## 曾考虑的替代方案 + +### 为何由调用方(而非提供方)提供 cwd + +提供方 seam 不得依赖 `dsh-agent`/`dsh-session`——它是一个文本存储后端,沙箱或远程实现同样满足该接口,而这些实现没有「agent 会话」的概念。工具已经接收了 `ToolExecution`(`exec`),其中携带 agent,因此工具是将 `exec → cwd` 投影并向提供方传递一个纯字符串的正确位置。这遵循「包(package)边界处显式优于隐式」的约定:基准目录作为显式参数传入,提供方据此行动,而非让提供方越界去读取它不应知晓的会话。这也与 `dsh-tool-bash` 一一对应,使两个面向模型的文件操作接口以相同方式解析路径。 + +默认值只存在于一个地方——提供方的 `config.cwd`。`sessionCwd` 在没有会话时返回 `undefined` 而非 `process.cwd()`,因此工具永远不会自行制造一个提供方本应自行选择的基准目录。 + +## 后果 + +- 在 ACP 演示中,fs 工具与 bash 对每个会话的工作区达成一致;自动化客户端可以选择任意绝对项目目录,两类工具都在该目录下操作。 +- 对于包含 `symlink/..` 的会话 cwd,或普通符号链接 cwd 搭配含父目录遍历的相对路径,bash、文件系统工具和沙箱授权都会从同一个物理工作区解析;词法父目录不会获得授权。 +- `FsTarget` 的标识不变:`targetKey` 仍为解析后绝对路径的 realpath,因此 observed-state 键控与符号链接标识不受影响——正确的每会话 cwd 产生与 bash 目标相同的 key。 +- 向后兼容:所有现有的 `resolve(path)` 调用(均在测试中)继续正常工作;新参数是可选的。 +- 单会话 stdio 演示不受影响:它不提供会话 cwd(其 agent 的会话没有 `cwd`),因此解析回退到 `config.cwd = process.cwd()`,即工作区本身。 diff --git a/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.i18n.yaml new file mode 100644 index 0000000000..e6d8d8570a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-02-result-time-applied-hunk-diffs.md: 55e1612aacd9070ede2f0079c73c30975e1bd5cf +2026-07-02-result-time-applied-hunk-diffs.zh.md: 6fe0032a507af2915bdf79a43578082785411479 diff --git a/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.md b/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.md index ce0f146b39..55e1612aac 100644 --- a/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.md +++ b/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.md @@ -2,9 +2,11 @@ Status: implemented +English | [中文](2026-07-02-result-time-applied-hunk-diffs.zh.md) + ## Problem -The [tagged render-intent union](2026-07-02-tool-render-intent-union.md) gave `dsh-tool-fs` write/edit a `card:'diff'` at CALL time, derived purely from the tool's args: write ⇒ `{oldText:null, newText:content}` (the whole new file), edit ⇒ `{oldText:old_string, newText:new_string}` (the bare replaced snippet). An editor renders that as an inline diff, but it is a **context-free** diff — the bare `old_string`→`new_string` with no surrounding lines, and a `replace_all` that touched five scattered sites still renders as one snippet pair. +The [tagged render-intent union](2026-07-02-tool-render-intent-union.md) gives `dsh-tool-fs` write/edit a `card:'diff'` at call time, derived purely from the tool's args: write ⇒ `{oldText:null, newText:content}` (the whole new file), edit ⇒ `{oldText:old_string, newText:new_string}` (the bare replaced snippet). A UI can render that as an inline diff, but it is a **context-free** diff — the bare `old_string`→`new_string` with no surrounding lines, and a `replace_all` that touched five scattered sites still renders as one snippet pair. Driving `claude-agent-acp`'s own ACP bridge shows what a full editor diff looks like: after the mutation applies, it emits a SECOND `tool_call_update` whose diff is the **applied hunk with ±3 context lines** (and one hunk per changed site for `replace_all`), reconstructed from the tool's `structuredPatch`. That result-time hunk is what makes Zed show the change *in place* in the file rather than as a floating snippet. Our tools stopped at the call-time snippet; the completed result carried only the plain "updated successfully" text, no diff. @@ -27,11 +29,11 @@ This remains the general shape ("a tool projects durable result presentation"), Per the [capability-seam split](2026-06-13-capability-seams.md), the storage backend returns only **storage facts** and the model-facing tool owns **presentation**: - `dsh-fs` widens `FsEditOutcome` with `{ before: string; after: string }` and `FsWriteOutcome` with `{ before: string | null; after: string }` (`before: null` ⇒ a create, or an existing-but-undiffable binary/non-UTF-8 file). The local backend already holds both texts at write time; it returns them as raw LF-normalized text, with **no diff/UI concept** entering the seam. -- `dsh-tool-fs` returns canonical before/after mutation facts and projects contextual hunks as `meta: { diffs: FileDiff[] }`. Successful mutations always complete with a diff card because ACP result content replaces the pending card: creates or unchanged overwrites fall back to an args-derived whole-file diff, while edits use applied hunks. Failed mutations carry no diff metadata and render their error normally. +- `dsh-tool-fs` returns canonical before/after mutation facts and projects contextual hunks as `meta: { diffs: FileDiff[] }`. Successful mutations complete with a diff view: creates or unchanged overwrites fall back to an args-derived whole-file diff, while edits use applied hunks. Failed mutations carry no diff metadata and render their error normally. -### 3. The bridge renders a `diff` result card +### 3. UI transports render a `diff` result view -`ToolResultView` gains a `DiffResultView { card:'diff'; title?; diffs: FileDiff[] }`; the bridge's result-side `switch (view.card)` gets a `diff` arm emitting the `{type:'diff'}` `ToolCallContent` blocks (mirroring the call-side arm). An ACP `tool_call_update.content` REPLACES the call's content in an editor, so the result diff **supersedes** the call-time snippet (and keeps the model-facing result text from clobbering it) — the two-update sequence (call snippet, then result diff) matches `claude-agent-acp` exactly. +`ToolResultView` includes `DiffResultView { card:'diff'; title?; diffs: FileDiff[] }`. TUI and JSON-RPC/Web consumers switch on the same tagged view and replace the pending call's context-free snippet with the applied result hunk. The [automation-only ACP bridge](../simplification/2026-07-23-acp-automation-only-protocol.md) does not carry tool presentation. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.zh.md b/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.zh.md new file mode 100644 index 0000000000..6fe0032a50 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.zh.md @@ -0,0 +1,57 @@ +# Agent Note: 结果时刻的 applied-hunk diff 用于文件变更 + +Status: implemented + +[English](2026-07-02-result-time-applied-hunk-diffs.md) | 中文 + +## 问题 + +[带标签的 render-intent 联合类型](2026-07-02-tool-render-intent-union.md)为 `dsh-tool-fs` 的 write/edit 在调用时刻提供 `card:'diff'`,纯粹从工具参数推导:write ⇒ `{oldText:null, newText:content}`(整个新文件),edit ⇒ `{oldText:old_string, newText:new_string}`(裸替换片段)。UI 可以将其渲染为行内 diff,但这是一个**无上下文**的 diff:裸的 `old_string`→`new_string` 没有周围行,而一次触及五个分散位置的 `replace_all` 仍然渲染为一对片段。 + +在对接 `claude-agent-acp` 自身的 ACP(Agent Client Protocol) bridge 时可以看到完整编辑器 diff 的样子:变更应用后,它发出第二个 `tool_call_update`,其 diff 是**带 ±3 行上下文的 applied hunk**(`replace_all` 的每个变更位置各一个 hunk),由工具的 `structuredPatch` 重建。这个结果时刻的 hunk 正是让 Zed 在文件中*原位*显示变更(而非浮动片段)的关键。我们的工具止步于调用时刻的片段;完成后的结果只携带纯文本「updated successfully」,没有 diff。 + +障碍在于一个 seam 边界:`presentResult(args, result)` 是 **`args` + 面向模型的 `result`(`{content, isError}`)的纯函数**——它在实时流式输出和会话日志回放中都会运行,因此必须具备回放确定性且不能做 I/O。它看不到文件的前后内容,而 `FsEditOutcome`/`FsWriteOutcome` 只携带替换计数和版本号,没有文本。因此无法计算——甚至无法携带——applied hunk 给 presenter。 + +## 决策 + +添加一个**持久化的、工具私有的展示通道**,使工具的 `execute` 能附加一个结果时刻的渲染载荷并在回放中存活,并用它来携带 applied-hunk diff。 + +### 1. 规范工具输出上的可回放展示投影(core) + +原始实现允许 `execute` 返回 `{ content, meta }`。[规范工具输出契约](2026-07-20-canonical-tool-output-contract.md)取代了这种编写形态:每个工具如今返回一个由 schema 声明的 JSON 值,`output.render(args, value)` 从中派生面向模型的内容块,可选的 `output.presentationMeta(args, value)` 则派生可回放的 UI 数据。 + +`presentationMeta` 是工具自有的 `JsonValue`,core 会持久化它,但不解释其中的字段。`Session.append` 将它与事件的其余部分一并校验,回放再把存储的载荷传回 `presentResult`;因此展示无需 I/O 或重新计算即可复现。规范值本身只存在于执行期间,不会加入会话格式。 + +这仍是通用形态(「工具投影持久化的结果展示」),而非 fs 特有;任何工具都可以使用。 + +### 2. 工具计算 hunk;后端返回 before/after(fs) + +按照 [capability-seam 拆分](2026-06-13-capability-seams.md),存储后端只返回**存储事实**,面向模型的工具拥有**展示**: + +- `dsh-fs` 将 `FsEditOutcome` 扩展为包含 `{ before: string; after: string }`,将 `FsWriteOutcome` 扩展为包含 `{ before: string | null; after: string }`(`before: null` 表示创建,或已存在但不可 diff 的二进制/非 UTF-8 文件)。本地后端在写入时已持有两份文本;它以原始 LF 规范化文本返回,**不让任何 diff/UI 概念进入 seam**。 +- `dsh-tool-fs` 返回规范的变更前/后事实,并将上下文 hunk 投影为 `meta: { diffs: FileDiff[] }`。成功的变更以 diff 视图完成:创建或无变化的覆写回退到由参数推导的整文件 diff,而编辑使用 applied hunk。失败的变更不携带 diff 元数据,正常渲染其错误信息。 + +### 3. UI 传输层渲染 `diff` 结果视图 + +`ToolResultView` 包含 `DiffResultView { card:'diff'; title?; diffs: FileDiff[] }`。TUI 与 JSON-RPC/Web 消费方在同一个带标签的视图上做 switch,用 applied 结果 hunk 替换待定调用的无上下文片段。[仅面向自动化的 ACP 桥接层](../simplification/2026-07-23-acp-automation-only-protocol.md)不承载工具展示。 + +## 曾考虑的替代方案 + +**手写或 vendor diff 算法。** 上下文 hunk 有已知的边界情况,因此 `dsh-tool-fs` 使用带类型的 [`diff`](https://www.npmjs.com/package/diff) 包,并在一个模块中规范化 `structuredPatch` 输出。仓库的 vendor 策略适用于框架源码,而非每个叶子工具库。 + +## 后果 + +`tool/result` 事件携带工具私有的 `meta` 载荷;它属于磁盘格式词汇的一部分,由 `Session.append` 在运行时限制为 JSON。任何工具都可以投影持久化的结果展示,无需再改 core。diff 卡片在会话重载和快照回放时免费复现:它从日志中读回,从不重新计算。代价:覆写操作在内存中同时持有旧文本和新文本以计算仅用于 UI 的 hunk(`TODO(overwrite-diff-bound)`),且 `dsh-tool-fs` 引入了一个小型、知名的运行时依赖。 + +## 非目标 + +- **实时增量 diff 流式输出。** hunk 在变更完成后一次性计算;没有逐键 diff。 +- **对二进制/非 UTF-8 覆写做 diff。** 此类文件的 `before` 为 `null`(没有文本 diff 基础);写入仍然成功,结果渲染整文件 diff(`oldText: null`)而非上下文 hunk。 +- **重命名/移动 diff。** 仅限单个已解析路径的内容 diff。 +- **限制覆写 diff 基础的大小。** 覆写操作将整个旧文件读入内存以计算上下文 hunk(加上已持有的新内容),因此非常大的文本覆写会为仅 UI 用途的 diff 分配两份文本。未来的改进可以设定预读上限,超过阈值时回退到整文件/无上下文 diff;在读取位置以 `TODO(overwrite-diff-bound)` 跟踪。 + +## 相关 + +- 补全了[带标签的 render-intent 联合类型](2026-07-02-tool-render-intent-union.md)中作为非目标列出的最后一项表示差异——该 Agent Note 的「非目标」一节已更新,记录 applied-hunk diff 在此处交付。 +- 基于[文件系统 capability seam](2026-06-17-filesystem-capability-seam.md)(before/after 是后端返回的存储事实)和[事件溯源会话](2026-06-11-event-sourced-sessions.md)(`meta` 载荷持久化在 `tool/result` 事件上,因此回放可复现卡片)。 +- `meta` 通道有意设计为通用的:未来的工具(结构化搜索、数据表结果)可以附加自己的持久化结果展示而无需再改 core。 diff --git a/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.i18n.yaml new file mode 100644 index 0000000000..9871c7a528 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-02-tool-render-intent-union.md: 6cfd8921decbe16343f963574edd52173c2f8698 +2026-07-02-tool-render-intent-union.zh.md: d0414c5f15995192df898e968d054933f82d2ab4 diff --git a/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md b/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md index 9d7fac0471..6cfd8921de 100644 --- a/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md +++ b/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md @@ -2,6 +2,10 @@ Status: implemented +English | [中文](2026-07-02-tool-render-intent-union.zh.md) + +> The render-intent union remains current for UI transports; its ACP mapping is superseded by [ACP as an automation-only protocol](../simplification/2026-07-23-acp-automation-only-protocol.md). + ## Problem A tool declares how its calls render in a UI (an editor's tool-call card) through two callbacks, `presentCall`/`presentResult` on `ToolDefinition`, returning `ToolCallPresentation` / `ToolResultPresentation` with an optional `ToolTerminal` sub-shape. These grew incrementally into a **bag of optional fields**: `title`, `kind`, `rawInput`, `content`, `locations`, `terminal` on the call; `title`, `content`, `terminal` on the result; `cwd`/`output`/`exitCode`/`signal` on `ToolTerminal`. The split of responsibility is muddy: @@ -10,7 +14,7 @@ A tool declares how its calls render in a UI (an editor's tool-call card) throug - Which combinations are *valid* is unwritten: a `terminal` call that also sets `content` means "description above the card"; a generic call that sets `terminal` is meaningless but representable. The type permits nonsense. - There is no way to express the one file-tool affordance an editor most wants — a **diff card** (`{path, oldText, newText}`, which Zed renders as an inline diff / new-file preview). `ToolCallPresentation.content` is the *LLM* `ContentBlock[]` vocabulary (text/image), so a tool literally cannot ask for a diff. -The existing `FIXME(tool-presentation)` in `packages/core/tools/src/index.ts` named the fix: "redesign the type so a tool declares its render INTENT once (e.g. a tagged union over card kinds) rather than a bag of optional fields the bridge stitches together." The rejected Agent Note [Collapse tool-owned UI presentation](../../rejected/simplification/2026-06-20-generic-tool-rendering.md) deferred it explicitly: rich rendering "should return later as a tagged render-intent union after there are at least two real tools and two real consumers to validate the vocabulary." That bar is now met — two producer families (`dsh-tool-bash`, `dsh-tool-fs`) and two consumers (the ACP bridge live path + the snapshot replay path). +The existing `FIXME(tool-presentation)` in `packages/core/tools/src/index.ts` named the fix: "redesign the type so a tool declares its render INTENT once (e.g. a tagged union over card kinds) rather than a bag of optional fields the bridge stitches together." The rejected Agent Note [Collapse tool-owned UI presentation](../../rejected/simplification/2026-06-20-generic-tool-rendering.md) deferred it explicitly: rich rendering "should return later as a tagged render-intent union after there are at least two real tools and two real consumers to validate the vocabulary." That bar is met by multiple producer families plus the TUI and host/client-runtime (Web) consumers. ## Decision @@ -37,8 +41,8 @@ interface TerminalResultView { card: 'terminal'; title?: string; output?: string ### Why a tagged union beats the field-bag - **Invalid states become unrepresentable.** A generic card cannot carry terminal output; a terminal card cannot carry a diff. The old bag permitted all of these. -- **The bridge switches instead of stitching.** One arm per card kind, each producing exactly the wire shape that card needs, rather than reconciling five optional fields whose interactions are undocumented. -- **`diff` is a first-class intent.** `dsh-tool-fs` write/edit declare `card:'diff'`; the bridge emits an ACP `{type:'diff', path, oldText, newText}` `ToolCallContent` (already in the SDK's `ToolCallContent` union, previously unused by the bridge). This is the affordance the redesign unlocks. +- **Consumers switch instead of stitching.** One arm per card kind produces exactly the view that card needs, rather than reconciling five optional fields whose interactions are undocumented. +- **`diff` is a first-class intent.** `dsh-tool-fs` write/edit declare `card:'diff'` with `{path, oldText, newText}`, allowing capable UIs to render an inline change without tool-name special cases. ### Producer mapping @@ -54,10 +58,6 @@ interface TerminalResultView { card: 'terminal'; title?: string; output?: string `presentCall`/`presentResult` remain pure functions of `args` (+ the result for `presentResult`) — they run on live streaming AND session-log replay, so they must be replay-deterministic. Every view is derived from args alone: write's diff is new-file style (`oldText:null`) because the tool has no old content at call time; edit's diff is `old_string`→`new_string`. -## Relative-path display titles - -`claude-agent-acp` relativizes a file card's title path against the session cwd (`toDisplayPath`) — `Read src/foo.ts`, not `/abs/proj/src/foo.ts` — while keeping `locations[]`/`diff.path` **raw** (the editor opens the real path). Our `presentCall` is pure/args-only and cannot see the session cwd, so this relativization happens at the **bridge**, which already threads the session cwd into tool-call rendering (the same cwd it uses to resolve a terminal card's header). The bridge relativizes the title only, by an exact structured replace of the known `locations[0].path`/`diffs[0].path` substring — generic over the file-card kinds, never special-casing tool names. - ## Alternatives considered - **Delete tool-owned presentation entirely** — [the rejected collapse proposal](../../rejected/simplification/2026-06-20-generic-tool-rendering.md); its own verdict deferred to exactly this union once two real tools and two real consumers existed, and that bar is now met. @@ -76,5 +76,4 @@ A new render intent is a compile-breaking change at the bridge switch — delibe - Supersedes the deferral in [Collapse tool-owned UI presentation](../../rejected/simplification/2026-06-20-generic-tool-rendering.md) (rejected — "wait for two real tools and two real consumers, then a tagged render-intent union"). That bar is now met; this is that union. - Extended by [Result-time applied-hunk diffs](2026-07-02-result-time-applied-hunk-diffs.md), which adds a persisted `meta` channel so write/edit emit a result-time `DiffResultView` — the applied change (a contextual hunk with context lines / one per `replace_all` site, or a whole-file diff for a create) — on top of this union's call-time diff card. -- Folds `ToolTerminal` into the `terminal` views described by [ACP terminal and tool-call rendering](../feature/2026-06-18-acp-terminal-and-tool-rendering.md) (the `_meta` terminal-card convention and capability gate are unchanged; only the harness-side presentation type changes). -- The ACP SDK's `Diff` / `ToolCallContent` types back the new `diff` card. +- Folds `ToolTerminal` into the tagged `terminal` views used by current UI transports. diff --git a/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.zh.md b/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.zh.md new file mode 100644 index 0000000000..d0414c5f15 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.zh.md @@ -0,0 +1,79 @@ +# Agent Note: 用于工具调用展示的带标签 render-intent 联合类型 + +Status: implemented + +[English](2026-07-02-tool-render-intent-union.md) | 中文 + +> render-intent 联合类型对 UI 传输层仍然有效;其 ACP 映射已被 [ACP 作为仅面向自动化的协议](../simplification/2026-07-23-acp-automation-only-protocol.md)取代。 + +## 问题 + +工具通过 `ToolDefinition` 上的两个回调 `presentCall`/`presentResult` 声明其调用在 UI(编辑器的工具调用卡片)中如何渲染,返回 `ToolCallPresentation` / `ToolResultPresentation`,并带有一个可选的 `ToolTerminal` 子结构。这些类型在增量演进中变成了一个**可选字段的集合**:调用侧有 `title`、`kind`、`rawInput`、`content`、`locations`、`terminal`;结果侧有 `title`、`content`、`terminal`;`ToolTerminal` 上有 `cwd`/`output`/`exitCode`/`signal`。职责划分模糊不清: + +- 调用侧和结果侧的 `terminal` 字段重叠,bridge 需要将每次调用的 `content` 块、`terminal` 块和 `rawInput` 用临时条件逻辑拼接在一起。 +- 哪些组合是*合法的*没有文档说明:一个设置了 `content` 的 `terminal` 调用意味着「卡片上方的描述」;一个设置了 `terminal` 的 generic 调用毫无意义但类型上可表达。类型允许无意义的状态存在。 +- 无法表达编辑器最需要的文件工具能力:**diff 卡片**(`{path, oldText, newText}`,Zed 将其渲染为内联 diff / 新文件预览)。`ToolCallPresentation.content` 使用的是 *LLM(大语言模型)* 的 `ContentBlock[]` 词汇(text/image),工具根本无法请求 diff 展示。 + +`packages/core/tools/src/index.ts` 中已有的 `FIXME(tool-presentation)` 指出了修复方向:「重新设计类型,让工具一次性声明其渲染意图(例如按卡片种类的带标签联合类型),而非一堆由 bridge 拼接的可选字段。」被否决的 Agent Note [折叠工具拥有的 UI 呈现](../../rejected/simplification/2026-06-20-generic-tool-rendering.md)明确推迟了此事:富渲染「应当在至少有两个真实工具和两个真实消费方验证词汇之后,以带标签 render-intent 联合类型的形式回归。」该条件已由多个生产者族,加上 TUI 与宿主/客户端运行时(Web)这些消费方满足。 + +## 决策 + +用一个**以 `card` 为标签的可辨识联合类型**替代可选字段集合。工具为每次调用/结果声明一个渲染意图;bridge 根据标签分发。 + +```ts ignore-check +type FileLocation = { path: string; line?: number } +type FileDiff = { path: string; oldText: string | null; newText: string } // oldText null ⇒ new file + +// presentCall → ToolCallView +type ToolCallView = GenericCallView | TerminalCallView | DiffCallView +interface GenericCallView { card: 'generic'; title: string; kind?: ToolCallKind; rawInput?: unknown; content?: ContentBlock[]; locations?: FileLocation[] } +interface TerminalCallView { card: 'terminal'; title: string; description?: string; cwd?: string } +interface DiffCallView { card: 'diff'; title: string; diffs: FileDiff[]; locations?: FileLocation[] } + +// presentResult → ToolResultView +type ToolResultView = GenericResultView | TerminalResultView +interface GenericResultView { card: 'generic'; title?: string; content?: ContentBlock[] } +interface TerminalResultView { card: 'terminal'; title?: string; output?: string; exitCode?: number; signal?: string } +``` + +`card` 在每个变体上都是**必填**的——真正的判别式,而非可选默认值。bridge 执行 `switch (view.card) { case 'generic': … case 'terminal': … case 'diff': … default: assertNever(view) }`。该联合类型是**封闭的**(遵循 [switch 穷举约定](../../../../AGENTS.md)):第四种渲染意图(表格、图表)无论如何需要新的 bridge 代码来渲染,因此一个由插件添加但被 bridge 静默丢弃的变体,比编译错误更糟糕。新增变体会在 bridge 的 switch 处中断编译——这正是我们想要的信号。 + +### 为什么带标签联合类型优于字段集合 + +- **无效状态变得不可表达。** generic 卡片不能携带终端输出;terminal 卡片不能携带 diff。旧的字段集合允许所有这些组合。 +- **消费方分发而非拼接。** 每种卡片一个分支,精确产出该卡片所需的视图,而非调和五个交互关系未文档化的可选字段。 +- **`diff` 成为一等意图。** `dsh-tool-fs` 的 write/edit 声明带 `{path, oldText, newText}` 的 `card:'diff'`,让有能力的 UI 无需针对工具名做特殊处理即可渲染行内变更。 + +### 生产者映射 + +- `dsh-tool-fs` read → `generic`(`kind:'read'`,附带一个 follow-along `location`);write → `diff`(`oldText:null`);edit → `diff`(`oldText:old_string || null`,`newText:new_string ?? ''`)。这与 `claude-agent-acp` 的 `toolInfoFromToolUse` 中 Read/Write/Edit 各分支逐字段对应。 +- `dsh-tool-bash` foreground → `terminal` 调用 + `terminal` 结果;`run_in_background` → `generic`。通用 `task_*` 控制工具拥有各自的 generic 卡片。 +- `dsh-tool-todo` → `generic`。 + +### 终端回退的归属 + +`TerminalResultView` 只携带 `output`/`exitCode`/`signal`。不具备终端能力的 UI 需要一个围栏 ` ```console ` 文本回退;该推导移至 **bridge**(在无能力路径上将 `output` 包裹在围栏代码块中),而非由工具双重编码。这使 bash 工具的结果保持单一结构化形状,并逐字节保留既有的能力门控行为。 + +### 纯函数性保持不变 + +`presentCall`/`presentResult` 仍然是 `args`(`presentResult` 还有 result)的纯函数——它们在实时流式输出和会话日志回放中都会运行,因此必须具备回放确定性。每个 view 仅从 args 推导:write 的 diff 是新文件风格(`oldText:null`),因为工具在调用时没有旧内容;edit 的 diff 是 `old_string`→`new_string`。 + +## 曾考虑的替代方案 + +- **完全删除工具自有的展示**:即[被否决的 collapse 提案](../../rejected/simplification/2026-06-20-generic-tool-rendering.md);其自身的结论正是推迟到两个真实工具和两个真实消费方存在后再做此联合类型,该条件现已满足。 +- **可合并扩展的联合类型**(`ContentBlockMap` 模式):否决。新的渲染意图无论如何需要新的 bridge 代码来渲染,因此一个被 bridge 静默丢弃的插件添加变体,比封闭联合类型在 bridge 的 `assertNever` switch 处引发的编译错误更糟糕。 +- **保留可选字段集合**:即「问题」一节所剖析的现状:无效状态可表达、字段交互无文档、且完全无法请求 diff 卡片。 + +## 后果 + +新的渲染意图会在 bridge 的 switch 处引发编译中断——这是有意为之:渲染代码必须先于卡片种类存在。无效的卡片/字段组合现已不可表达,bash 回退推导归 bridge 所有,工具只返回一个结构化形状。第四种卡片(表格、图表)的门槛是在同一个变更中编写其 bridge 分支。 + +## 非目标 + +- **实时增量 `terminal_output_delta` 流式输出**与**命令分类**:终端渲染 Agent Note 自身推迟的后续工作,本 Agent Note 不涉及。 + +## 相关 + +- 取代[折叠工具拥有的 UI 呈现](../../rejected/simplification/2026-06-20-generic-tool-rendering.md)(已否决——「等两个真实工具和两个真实消费方,然后做带标签 render-intent 联合类型」)中的推迟决定。该条件现已满足;本 Agent Note 即为那个联合类型。 +- 被[结果时已应用 hunk 差异](2026-07-02-result-time-applied-hunk-diffs.md)扩展:后者添加了一个持久化的 `meta` 通道,使 write/edit 在结果时输出 `DiffResultView`(应用后的变更:带上下文行的 contextual hunk / 每个 `replace_all` 位点一个,或创建时的整文件 diff),叠加在本联合类型的调用时 diff 卡片之上。 +- 将 `ToolTerminal` 折入当前 UI 传输层使用的带标签 `terminal` 视图。 diff --git a/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.i18n.yaml new file mode 100644 index 0000000000..0a8c0d62fa --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-03-filesystem-directory-listing-seam.md: c7db576ff3c7a56622f90a4400bd9297c9591bef +2026-07-03-filesystem-directory-listing-seam.zh.md: 75ee6851127ca6d8c3fc60a66115d521d4627cdc diff --git a/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.md b/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.md index d40c50695d..c7db576ff3 100644 --- a/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-03-filesystem-directory-listing-seam.zh.md) + ## Problem `@deepseek-ai/dsh-fs` is the provider seam for filesystem access, with local and future non-local backends behind the same `ctx.fs` contract. Before this change it could resolve paths, stat targets, read text, stream text, write text, and edit text. That was enough for model-facing file tools, but not for non-model-facing consumers that need to enumerate directories without importing `node:fs`. diff --git a/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.zh.md new file mode 100644 index 0000000000..75ee685112 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.zh.md @@ -0,0 +1,53 @@ +# Agent Note: 为文件系统 seam 添加直接目录列举能力 + +Status: implemented + +[English](2026-07-03-filesystem-directory-listing-seam.md) | 中文 + +## 问题 + +`@deepseek-ai/dsh-fs` 是文件系统访问的提供方 seam,本地后端与未来的非本地后端共享同一个 `ctx.fs` 契约。在本次变更之前,它能解析路径、stat 目标、读取文本、流式读取文本、写入文本和编辑文本。这对面向模型的文件工具已经足够,但对于需要枚举目录而又不想直接导入 `node:fs` 的非模型侧消费方来说还不够。 + +直接的压力来自 skill(技能)加载:读取单个 `SKILL.md` 已经可以走 `ctx.get('fs')`,但发现哪些 skill 根目录包含 `<name>/SKILL.md` 或 `<name>.md` 仍需要目录枚举。如果仅在 `dsh-skill` 中添加目录列举,要么保留对 Node 的直接依赖,要么在文件系统提供方栈之外发明一个一次性的本地辅助函数。 + +本决策只添加提供方能力,不涉及面向模型的 `ls`/`list` 工具或 skill 发现机制的变更。那些消费方需要独立的 UX、提示词与策略决策。 + +## 决策 + +在 `@deepseek-ai/dsh-fs` 中添加 `FileSystem.listDir(target, signal?)`。 + +`listDir` 仅列举一层目录。它以稳定的名称顺序返回直接子项,包含以下字段: + +- `name`:子项的 basename; +- `type`:`file`、`directory` 或 `other`; +- `target`:已解析的子项 `FsTarget`; +- `version`:可用时返回的轻量元数据; +- `size`:可用时返回的常规文件大小。 + +它从不读取文件内容。递归遍历、glob 匹配、分页、搜索、文件监听和面向模型的渲染均有意不在范围内。 + +本地后端通过 `readdir({ withFileTypes: true })`、`resolveLocalTarget` 以及元数据 `stat`/`realpath` 探测来实现。结果顺序是确定性的(`name.localeCompare`),以保持未来消费方的提示词/列表输出稳定,并提高前缀缓存复用率。 + +损坏或已消失的子项可以表示为 `type: 'other'`(不带 `version`/`size`);它们不会中止整个列举。在列举目录或解析/探测子项元数据时遇到权限或后端 I/O 故障,则以结构化的 `FsError` 错误码使整个列举失败: + +- `FS_NOT_FOUND`:目标不存在; +- `FS_NOT_DIRECTORY`:目标存在但不是目录; +- `FS_PERMISSION_DENIED`:权限不足; +- `FS_IO_ERROR`:其他后端 I/O 故障; +- `FS_ABORTED`:调用被中止。 + +## 曾考虑的替代方案 + +**在添加 seam 的同时添加面向模型的 list 工具。** 否决。其提示词、schema 和渲染契约与提供方原语相互独立。 + +**让每个消费方自行枚举目录。** 否决。这会将 `dsh-skill` 等产品包绑定到 Node/本地文件系统行为上,绕过策略/远程/沙箱后端。 + +**让 `listDir` 支持递归或 glob 形式。** 暂时否决。skill 根发现只需要直接子项,而简单的单层列举是未来消费方可以安全组合的最小后端契约。 + +**跳过元数据解析失败的子项。** 否决。API 承诺返回已解析的子项 target,因此解析子项时的权限/IO 故障属于契约失败。损坏或已消失的子项是例外,因为它们仍可在不声称拥有一个活跃已解析文件的前提下被表示。 + +## 后果 + +每个文件系统后端现在必须多实现一个提供方原语。这是 harness 尚未发布时有意为之的基础工作,但也意味着未来的沙箱/远程后端需要定义等价的直接子项列举行为。 + +该能力仍停留在提供方层面。在消费方落地之前,ACP(Agent Client Protocol)/模型会话仍需使用 `bash` 等既有工具来列举目录。缺少面向模型的 `listdir` 工具是预期行为,而非接线错误。 diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml new file mode 100644 index 0000000000..1f232965a5 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-05-prompt-variables-and-tool-guidance-ownership.md: 94f5fa409e7b539b48750d12576c7a342a30c9ba +2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md: f1379e143a94a3ae3a07b3120c6f0b9fc8561fe9 diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md index cdd37091a2..94f5fa409e 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md) + ## Problem The assembled system prompt had four defects, all of one family: facts the harness already knows were restated by hand somewhere else, and drifted. diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md new file mode 100644 index 0000000000..f1379e143a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md @@ -0,0 +1,72 @@ +# Agent Note: 提示词变量与工具指导归属 + +Status: implemented + +[English](2026-07-05-prompt-variables-and-tool-guidance-ownership.md) | 中文 + +## 问题 + +组装后的系统提示词存在四个缺陷,同属一类:harness 已知的事实在别处被手工重述,然后漂移。 + +**模型无法知道自己的名字。** `AgentOptions.model` 驱动每个请求,但没有任何提示词文本携带它——也不可能携带:`dsh-system-prompt` 中的 section 是上下文全局的,而模型名称是 per-agent 的,`assemble()` 根本不接受任何 per-agent 输入。 + +**工具指导是 leaf YAML 中的手写行文。** bash/subagent/todo_write 的使用指导存放在 coding-agent 和 ACP persona 字符串里——两份漂移的副本(ACP 那份已经被删减)——而 `dsh-tool-fs` 和 `dsh-tool-web` 则通过 `ctx.systemPrompt.section()` 贡献各自的指导。加载或卸载一个工具插件意味着手动编辑每个部署的 persona;两份 YAML 都带着一条 `FIXME(config-comments)` 为这种分裂的症状道歉,旧终端欢迎横幅也手动枚举了工具集。 + +**Persona 渲染在工具指导之后。** agent loop(智能体循环)将 `agent.options.systemPrompt` 字符串拼接在已组装的 section 之后,于是模型先读到「Use the read tool…」再读到「You are a coding agent」——与 identity-first 约定(Claude Code、Codex)相反,且是 section 流水线之外的第二条组合路径。 + +**Fork 工具的描述是假的。** `dsh-tool-subagent` 硬编码了一段为 spawn 语义编写的描述——「a separate agent that works in its own context … it does not see this conversation」——而 `subagent_fork` 实例(其子 agent 继承父级已完成的轮次)拿到了同样的措辞;YAML 行文在带外纠正了这个谎言。小问题:`PromptSection.name` 文档标注为「(diagnostics / dedup)」,但重复项被静默接受。 + +## 决策 + +**一条原则:提示词中的每个事实恰好有一个归属方。** 模型名称和工作区是配置/会话事实 → harness 将它们暴露为变量,persona 引用它们。每个工具的语义和何时使用 → 工具的 `description`。description 无法承载的跨调用习惯 → 工具包(package)的提示词 section。harness 来源标识 → 静态的 `harness:identity` section。部署角色与行为 → 部署的 persona。 + +### 组装上下文 + +`SystemPrompt.assemble(context)` 接受一个可合并扩展的 `AssembleContext`。`dsh-system-prompt` 声明可选的 `scope` 选择器用于 scoped 路由,而 `dsh-agent` 通过声明合并将可选的类型化 `agent` 字段附加到其上(类型层面的 `agent → system-prompt` 边,无运行时依赖循环)。循环在每个步骤调用 `assembleContextFor(agent)`,使两个字段标识同一个 agent;section 文本提供方可以读取该上下文,`system-prompt/assemble` waterfall(瀑布式事件)也接收它,监听器可据此按 agent 过滤或扩展。 + +### 提示词变量 + +插件通过 `ctx.systemPrompt.variable(name, provider)` 注册 `{{name}}` 值。组装过程将它们解析到 waterfall 可见的变量映射中。渲染阶段拒绝以下情况:引用了未知的 own-property、已注册的提供方返回 `undefined`、格式错误的完整引用、以及仍包含闭合 `}}` 的不平衡引用;孤立的未匹配 `{{` 保留为行文,替换后的值不会被重新扫描。注册阶段拒绝无效或重复的变量名,section 名称也必须唯一。 + +`dsh-agent-loop` 注册两个内置变量,均为上下文 agent 的纯投影:`model`(= `options.model`)和 `cwd`(= `session.header.cwd`)。示例 persona 写 `powered by the {{model}} model`——模型名称只在 `model:` 配置键中声明一次。`{{cwd}}` 仅在 ACP 示例中演示:每个 ACP 会话携带客户端的 cwd,而配置预创建的 stdio agent 没有 cwd(在那里声称 `{{cwd}}` 的 persona 会导致该轮次失败——这是有意为之)。变量留在 loop 插件上(不同于下面的 section):它们是本循环驱动的 agent 的运行时事实,替换循环自行提供自己的变量。 + +### Persona 作为 order-0 section + +`dsh-system-prompt` 拥有 order 为 `-100` 的 `harness:identity` 和 order 为 0 的配置 `deployment:persona`,因此两者在循环被替换时仍然存活。提示词渲染只有一条路径 `renderPrompt(assembly)`,已路由请求 header 因此会记录准确的提示词,稍后由 `ctx.tokenMeter` 为压缩压力回放。agent 作用域的 `deployment:persona` 遮蔽全局默认值,允许 subagent 提供方在发布前安装 persona。约定的 order 区间为:identity `-100`、persona `0`、工具指导 `100–199`。 + +### 工具指导归属 + +每个工具的语义和选择指导放在工具 description 中。提示词 section 只承载跨调用习惯,例如检查 bash 退出标记或优先使用文件系统工具而非 shell 命令。`todo_write` 和 subagent 工具不需要 section,因为它们的 description 包含完整契约。部署 persona 只包含角色和行为。 + +### Subagent 对话历史描述符 + +`SubagentProvider.inheritsParentContext` 描述的是对话种子,而非作用域、服务、工具或权限。spawn 和 ACP 将其设为 `false`;fork 设为 `true`。`dsh-tool-subagent` 根据该标志派生工具和提示词参数的描述,包括 fork 继承已完成轮次但不继承进行中轮次这一点。提供方生命周期事件使该措辞与响应式提供方注册保持同步;其设计动机见[提供方生命周期事件 Agent Note](2026-07-05-subagent-provider-lifecycle-events.md)。 + +## 曾考虑的替代方案 + +- **循环自行组合一行 identity 文本**:在必须保持精简的那个包(「用插件,不改循环」)中硬编码面向模型的行文,且在 section 流水线之外构成第二条组合路径。(identity 确实以代码字面量交付——但作为 `dsh-system-prompt` 注册的普通 section,其 `system-prompt/assemble` waterfall 仍是部署需要移除它时的逃生阀。) +- **通过 `agent/request` waterfall 注入模型名称**:提示词文本会在两处组合,更早渲染的 persona 也可能与最终已路由 header 不一致。拥有延迟路由的请求插件还必须拥有该模型在提示词中更早出现的声明。 +- **在每个 persona 中手写模型名称**:与上方一行的 `model:` 键重复,配置修改后静默失实;正是本 Agent Note 要治愈的病症。 +- **宽松插值(未知引用保留原样或替换为空)**:一个拼写错误 `{{modle}}`(或一个空洞)会被发送给模型,直到 transcript(文本记录)审查时才会被发现。 +- **在配置中为每个 subagent 实例编写措辞**:面向模型的行文回到每个部署 × 实例中,重蹈 P2 病症。**根据提供方名称选择措辞**:`providerName` 本身是配置,重命名提供方后会静默获得错误的措辞。 +- **在 `apply` 时解析提供方(加载顺序要求)** 与 **仅用 section 承载 subagent 措辞(在 assemble 时惰性解析)**:提供方生命周期事件的替代方案;两者均在[提供方生命周期事件 Agent Note](2026-07-05-subagent-provider-lifecycle-events.md)中被否决。 + +## 不在范围内 + +- 更多变量(`date`、platform、git 状态):注册表使每个变量成为拥有该事实的插件的一行贡献;本 Agent Note 不认领任何一个。 +- 为预创建的 stdio agent 提供配置 `cwd`(可让 stdio persona 使用 `{{cwd}}` 并按真实路径分区持久化):推迟到会话 cwd 方案重新讨论时。 + +## 交付的不变式 + +- tui-agent 的提示词通过一条组装路径依次渲染 identity、带插值模型名的 persona,然后是 fs/bash/web 指导。 +- fork 和 fresh subagent 的描述反映提供方是否继承已完成的对话轮次;工具随提供方生命周期变化而出现、消失和重新措辞。 +- 未知、无值、格式错误或不平衡的变量引用会指明 section 名称并抛出异常;重复的 section、变量和工具注册同样抛出异常。 +- 快照回放与提示词无关:它按轮次和步骤索引已记录的分片流,不比较发出的请求。 + +## 后果 + +- 组装后的提示词中每个事实现在恰好有一个归属方,leaf YAML 中手工维护的工具行文已消除:加载或卸载一个工具插件不再需要编辑任何部署的 persona。 +- `{{model}}` 在组装时反映 `AgentOptions.model`。如果一个插件在 `agent/request` waterfall 中切换模型,提示词对该步骤的声明就会过时;如果一个插件在那里提供模型(options.model 未设置——循环文档中记载的回退路径),变量在渲染时无值,包含 `{{model}}` 的 persona 会在 waterfall 运行前失败。两者的补救方式相同,就是归属规则本身:拥有延迟绑定模型事实的插件在 `system-prompt/assemble` waterfall 上提前声明它(`assembly.variables['model'] = …`)——一个归属方,两处声明;一个循环测试端到端固定了 supply 路径。已接受。 +- 当一个已绑定的提供方不存在时(尚未激活、已卸载、HMR(热模块替换)重载中),subagent 工具不存在,该窗口内的模型请求中不会包含它。这是诚实的状态——替代方案是注册一个 description 或执行都不可信的工具。 +- 严格性意味着 persona 可能在渲染时导致轮次失败(例如在无 cwd 的会话上使用 `{{cwd}}`)。失败是受控的——该轮次以 `error` 结束,循环存活——且这是一个我们希望大声暴露的撰写错误。 +- 目前没有在提示词行文中转义字面 `{{name}}` 的语法;如果真实提示词确实需要,再行添加。 diff --git a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.i18n.yaml new file mode 100644 index 0000000000..f9c309c39f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-05-reconstructable-requests.md: 153d37a2faf2265134d5ff9e88f0bbfa275328e0 +2026-07-05-reconstructable-requests.zh.md: caf51c3065e416fd11aebc1c1d4dc2ee248e2e5c diff --git a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md index 99a7633c5b..153d37a2fa 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-05-reconstructable-requests.zh.md) + ## Problem The request pipeline did not guarantee prefix stability for provider caching, and the session log could not reconstruct what the model saw. It omitted model, system prompt, and tool schemas while allowing per-call request rewrites. Cache behavior and replay equivalence therefore depended on whichever plugins happened to be loaded. diff --git a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md new file mode 100644 index 0000000000..caf51c3065 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md @@ -0,0 +1,56 @@ +# Agent Note: 每个 LLM(大语言模型)请求都可从会话日志重建 + +Status: implemented + +[English](2026-07-05-reconstructable-requests.md) | 中文 + +## 问题 + +请求流水线未能保证前缀稳定性以利用提供方缓存,会话日志也无法重建模型实际看到的内容。日志遗漏了 model、系统提示词和工具 schema,同时允许逐次调用的请求改写。因此缓存行为和回放等价性取决于碰巧加载了哪些插件。 + +快乐路径的参考形态是 MiniCode 的 `LLMClient`:一个有状态的对话客户端,随对话推进只做追加而不重建,仅在系统提示词、工具集或压缩(compaction)真正改变了模型需要看到的内容时才重置。本 Agent Note 回答的设计问题是:如何在不放弃事件溯源的前提下获得这种纪律。 + +## 决策 + +### 原则 + +**模型可见 ⟺ 已记录。** 凡到达模型请求的内容都必须记录在会话日志中。可检查的推论:**循环发出的每个对话请求都是会话日志的纯函数**——任何人持有日志即可逐字节重建请求。精确的范围声明:该保证覆盖循环构建的 `GenerateOptions`;提供方协议格式(wire format)字节由此推导而来,因为两个适配器的序列化在固定代码版本下都是逐消息的纯函数;直接的一次性调用(压缩的 summarize 调用)记录其信封标量(`compact/summary.{provider, model, maxTokens}`),其输入是对日志区域的确定性代码运算——可从日志加代码重建,因为只有循环会标记请求归属,所以它们不在不变式内。 + +前缀缓存稳定性是推论 #1,而非标题:一个仅追加的日志经逐节点纯函数投影,在 header 不变时自然产出前一请求的追加扩展——稳定性是涌现的,不是管理出来的。字节精确的审计/回放是推论 #2;带*可归因*漂移的恢复与 fork 是推论 #3。 + +### 机制 + +**消息。** `Session.deriveMessages()` 带缓存:每个 surface 条目在首次出现时通过公开的逐事件函数 `deriveEventMessage(event)` 精确投影一次;surface 重写(压缩的 `replace`,即 `SurfaceManager.replaceGeneration`)触发重建。调用方每次获得一个新数组,底层是共享的深度冻结消息:通过投影变异已记录的历史是不可表达的(会抛异常),取代了旧的逐次调用克隆隔离。外部重建器对日志前缀折叠同一个公开函数,因此不可能有两条路径产生分歧。 + +`EpochHeader` 记录请求的非历史状态:调用配置、渲染后的系统提示词、工具 schema 和会话前缀,空值规范化为缺失。`request/header` 始终写入完整快照:首个循环实例使用 reason `initial`,后续实例使用 `resume`,实例内变更使用 `change`。`foldRequestHeader` 选择最新快照。旧的 `request/header-delta` 事件和已移除的 `fallback` reason 在追加或加载时都会被拒绝。 + +每个步骤重建提示词组装。在实例的首个步骤中,`agent/session-prefix` 以一个冻结的空种子为基础,用仅限请求的开场消息进行扩展;结果在通用 `agent/pre-step` 检查点与边界快照之前被冻结并缓存于该循环实例。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。`agent/request` 只能替换那个冻结的配置种子,模型可见内容通过已记录的通道进入。循环记录欠下的 header 事件(前缀唯一的持久归宿),从前缀、快照和 header 构建 `GenerateOptions`,对其深度冻结但保持 `AbortSignal` 活跃。每实例状态仅有缓存的前缀和锚定快照是否已写入。 + +**`step/start` 是重建边界。** 一个步骤从该序列之前的事件推导消息。快照之后的注入加入下一次请求,事件发布期间的重入追加被拒绝。`agent/pre-step(agent, turn, step, signal)` 仍是当前请求所需内容的通用 seam。header 重建选择该步骤的 `request/header`,或在无新 header 写入时沿用前一个快照。 + +**强制执行。** `dsh-agent-loop/invariant` 配套插件向 `ctx.invariants` 注册,并在被选用时通过一个全新的 `Session` 独立重建每个循环请求,使活跃缓存无法为自身背书,然后在 `llm/stream` 处比较消息和折叠后的 header 字段。循环通过 `dsh-llm` 的 `markAgentLoopRequest()` 记录精确的冻结请求;这一进程内标识让配套插件和其他请求观察者识别对话工作,而直接的一次性调用无论其冻结形状或会话 id 如何都保持排除。正确性依赖于序列有界的重建,而非监听器顺序。带密钥的 e2e 要求首次请求之后有正值的 cache-read token;逐步骤用量是生产信号,header 变更或压缩表现为下一步骤的 cache-read 下降。 + +### MiniCode 形态:采纳,但溯源箭头反转 + +与 MiniCode 相同,对话仅追加推进,仅在模型可见状态变更时重置。与 MiniCode 不同,事件日志仍是真源,因为它同时拥有持久化、恢复、边界、工具配对和溯源。`Session` 缓存从日志推导的消息和 header 折叠结果,使每个请求都可独立检查。 + +## 曾考虑的替代方案 + +- **客户端作为真源**(照搬 MiniCode):在日志之外多出一个运行时真相——两者漂移而无人察觉;见上节。 +- **镜像日志的有状态传输客户端**:重复对话状态,需要围绕监听器做回滚,留下未记录的编辑面,且仍无法重建请求 header。Session 拥有的缓存加已记录的 header 避免了这些分裂的真相。 +- **逐次调用的请求标量**(一个可自由变异的配置传给每次 `agent/request` 分发):监听器可以零记账地逐次切换 model,悄然放弃本设计旨在保护的提供方缓存。配置是逐对话的已记录状态;waterfall(瀑布式事件)提议,日志记录。 +- **检测并报告**(比较连续请求,发散时告警):事后捕获违规;违规请求仍可构造并发出。因接口层面的不可表达性而否决。 +- **事件驱动组装**(仅在变更信号时重新渲染):存在漏信号的 bug 类别——会话中途注册的工具发出 `tools/change` 而非 `system-prompt/change`,第三方提供方可能什么都不发。逐步骤渲染加值比较在零信号纪律下即可稳健工作。 +- **自定义 header-delta 编解码器**(系统行编辑、按名称键控的工具编辑、完整配置/前缀替换):减少了重复字节,却复制了表示及其 diff/apply/fallback 机制。完整快照只保留一种回放表示。 +- **Header 快照上的叙事性变更字段列表**:可以通过比较连续快照推导。`reason` 仍保留,因为实例边界无法从快照值推导。 + +## 后果 + +- 一个日志无法解释的请求不可能被意外构造——无论是循环还是监听器;变异已构建的请求会抛异常;每个 header 变更都是持久的、可 diff 的日志事件。 +- 在建议性通道之间做选择是变更频率的决策,而本设计使稳定的那个在结构上成为默认:`agent/session-prefix` 的贡献在每个循环实例中只组合一次并逐字复用,因此以零边际成本扩展可缓存前缀,且不可能在会话中途击穿提供方缓存;会话中途变化的内容通过仅追加的历史通道流入——`agent.inject()` 以及工具/prompt-submit 的 `additionalContexts`——每条都是持久的 `context/message`,付出一次代价后即被前缀缓存,代价是在历史和日志中累积。将会话冻结的开场内容路由到前缀,将变更通知路由到历史通道;逐步骤的仅限请求尾部槽位被有意放弃(无消费方,且持久追加覆盖了当前所有更新模式)。 +- 在提供方处仍需全价计算的内容是固有的且已记录的:压缩(其 `compact/*` 事件和替换条目)、真正的提示词、工具或配置变更(reason 为 `change` 的 `request/header`),或带漂移的进程边界(不同的 `resume` 快照)。提供方自身的 reasoning-content 排除由服务端管理。 +- `step/start` 监听器行为变更(见上文)是对插件唯一可观察的语义变更;`agent/pre-step` 是当前请求的 seam。 +- 工具结果裁剪(计划中)无需新机制:一个已记录的单条目 surface replace(`start === end`),携带同一 `callId` 下裁剪后的 `tool/result`——属压缩家族,回放正确,缓存击穿由相同的压力逻辑批量处理。 +- 会话日志每个循环实例增长一个 `request/header` 快照,并在真正变更时增加快照。它比 delta 编解码器更大,但相对分片密集型日志仍然很小,并只保留一种回放表示。`SESSION_FORMAT_VERSION` 保持 `0`;旧的 delta 事件被拒绝而非迁移。 +- 快照预期输出变更一次(每个 transcript(文本记录)增加其 header 事件);写入文件系统的 fixture(测试前置数据)以规范化的撰写形式存储,工具参数使用 cwd 相对路径,因为回放只对 cwd 无关的参数路径做往返。 +- FIXME(call-config-shape):重新审视 `LlmCallConfig` 的确切字段集——哪些字段对缓存而言真正属于 epoch 级别(`model` 毫无疑问;采样标量出于谨慎放在那里),以及当适配器需要时,提供方特定的额外项(reasoning 选项、额外 body 参数)应归属何处。 diff --git a/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.i18n.yaml new file mode 100644 index 0000000000..516dd4edcb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-05-subagent-provider-lifecycle-events.md: afd45027e8b56cbf1d17e6dec749d8602c81124d +2026-07-05-subagent-provider-lifecycle-events.zh.md: 58d439936a3f2cc51d8190cbebe8e68cdb14c855 diff --git a/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.md b/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.md index 44733bb8c9..afd45027e8 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.md +++ b/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-05-subagent-provider-lifecycle-events.zh.md) + ## Problem [The prompt-variables Agent Note](2026-07-05-prompt-variables-and-tool-guidance-ownership.md) makes `dsh-tool-subagent` DERIVE its model-facing wording from its provider: `SubagentProvider.inheritsParentContext` (spawn/ACP `false`, fork `true`) drives both the tool description and the `prompt` parameter description, so the fork tool stops lying about context inheritance. That fix created a cross-fiber data dependency: a tool's description is fixed at TOOL REGISTRATION (deliberately — the description is where tool-choice guidance lives), but the provider arrives on its own plugin fiber, on no particular schedule. diff --git a/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.zh.md b/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.zh.md new file mode 100644 index 0000000000..58d439936a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.zh.md @@ -0,0 +1,36 @@ +# Agent Note: Subagent 提供方生命周期事件——`subagent/provider-added` / `subagent/provider-removed` + +Status: implemented + +[English](2026-07-05-subagent-provider-lifecycle-events.md) | 中文 + +## 问题 + +[提示词变量 Agent Note](2026-07-05-prompt-variables-and-tool-guidance-ownership.md) 让 `dsh-tool-subagent` 从其提供方派生面向模型的措辞:`SubagentProvider.inheritsParentContext`(spawn/ACP 为 `false`,fork 为 `true`)同时驱动工具描述和 `prompt` 参数描述,使 fork 工具不再在上下文继承问题上对模型撒谎。这一修复引入了跨 fiber 的数据依赖:工具描述在工具注册时固定(这是有意为之——描述是 tool-choice 引导所在之处),但提供方在自己的插件 fiber 上到达,时机不确定。 + +如果在工具插件的 `apply` 时刻解析提供方,就会产生一个隐式的加载顺序要求(「在 cordis.yml 中把后端列在工具前面」)。这个要求不成立,因为 Cordis Loader 并发启动同级条目,且 `Entry.init()` 不会等待激活完成:延迟到达的后端即使列在前面,也可能让工具 fiber 失败。Loader 不提供同级顺序保证——「异步状态不是同步状态」(见[防御性模式](../../../../docs/defensive-patterns.md))。 + +## 决策 + +注册表将提供方的成员变化作为类型化事件广播,消费方镜像这些事件而非假设顺序: + +- **`subagent/provider-added(provider)`**:一个提供方在 `ctx.subagents` 注册表中变为可解析。在注册时发出。 +- **`subagent/provider-removed(name)`**:一个提供方离开注册表(其插件 fiber 被 dispose(资源释放)——卸载或 HMR(热模块替换)重载)。从注册的 disposer 中发出。 + +`dsh-tool-subagent` 镜像其命名提供方的生命周期:当提供方可用(或变为可用)时注册工具——在那一刻从该提供方派生措辞——当提供方离开时注销工具,并在重新注册时(HMR 重载)重新派生。提供方不在时工具不存在,因此不会对模型撒谎。这里有意不留下任何需要文档化的加载顺序要求:事件让顺序问题消失,而非将其钉死。 + +这些事件还完善了 seam 的词汇:`ctx.subagents` 是一个命名注册表,多个委派后端(`spawn`、`fork`、`acp`)在其上共存;一个其他插件从中派生状态的注册表,应当以类型化事件广播成员变化,而非要求轮询或依赖加载顺序。 + +## 曾考虑的替代方案 + +- **在 `apply` 时解析提供方,不存在则抛异常**:否决。「先列后端」这一要求声称了 Loader 并不存在的顺序保证。 +- **重试查找(轮询直到提供方出现)**:最终能收敛,但在框架已有的机制(effect 注册 + disposal)之外发明了一套私有就绪协议;它也无法感知提供方离开,因此 HMR 会遗留一个措辞描述已 dispose 后端的工具。 +- **仅在 section 中放置 subagent 措辞,在组装时惰性解析**:同样能容忍任意加载顺序,但将 tool-choice 引导移出了描述,与提示词变量 Agent Note 建立的所有权规则相矛盾(每个工具的语义和何时使用属于描述)。响应式注册既保持描述的权威性,又不依赖顺序。 +- **根据提供方名称而非提供方对象确定措辞**:`providerName` 本身是配置,重命名后的提供方会静默获得错误的措辞;从已解析提供方自身的 `inheritsParentContext` 派生则不会漂移。 + +## 后果 + +- 从命名提供方派生状态的消费方响应 `subagent/provider-added`/`-removed` 事件,而非在 `apply` 时读取注册表;`dsh-tool-subagent` 是参考实现。 +- **添加时大声失败;移除时按监听器隔离。** 添加监听器可以回滚注册。移除在 disposal 期间运行,因此单个监听器抛异常只会被记录日志,不会饿死后续镜像或干扰拆解流程。`start()` 仍在每次运行时按名称解析提供方,防止陈旧工具调用已移除的后端。见[事件目录](../../../../docs/cordis-catalog/events.md)与[生产者/消费方映射](../../../../docs/event-producer-consumer.md)。 +- **工具不存在的窗口期。** 在后端 disposal 与重新注册之间(HMR 重载期间),模型看不到 subagent 工具。这是诚实的状态——替代方案是一个向空处分发的工具——工具注册表的 `tools/change` 事件发出会保持提示词组装的时效性。 +- **两个等待中的 fiber 共享同一 `toolName` 是无效配置,被延迟捕获。** 如果两个 `dsh-tool-subagent` 加载实例命名了不同的提供方但相同的 `toolName`,两者都会等待,先到达的提供方先注册;第二次注册仅在其提供方到达时才抛异常。插件中的 `TODO(subagent-dup-toolname)` 记录了这一影响范围;工具注册表的重名拒绝机制仍是最终防线。 diff --git a/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.i18n.yaml new file mode 100644 index 0000000000..6d14977e92 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-timeout-deadline-library.md: 11d4b8cd48dd345d2324b63e01bd726f12d846b4 +2026-07-06-timeout-deadline-library.zh.md: 334914c689adf54a654c5907395c29ceeeb50891 diff --git a/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md b/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md index 1c407d777d..11d4b8cd48 100644 --- a/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md +++ b/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-06-timeout-deadline-library.zh.md) + ## Problem Timeout handling was drifting apart across the tool-bearing capabilities, and the divergence was not superficial — it was the same logic re-implemented three ways, each with its own subtle correctness burden. diff --git a/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.zh.md b/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.zh.md new file mode 100644 index 0000000000..334914c689 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.zh.md @@ -0,0 +1,115 @@ +# Agent Note: 共享的超时/截止时间原语,硬终止留给各能力自行实现 + +Status: implemented + +[English](2026-07-06-timeout-deadline-library.md) | 中文 + +## 问题 + +超时处理在各个承载工具的能力之间逐渐分化,而且这种分化并非表面的:同一套逻辑被以三种方式重新实现,各自带有微妙的正确性负担。 + +- **bash**([packages/bash/bash-local/src/run.ts](../../../../packages/bash/bash-local/src/run.ts))在进程管道内部有一套完整、正确的超时实现:一个经配置钳位的 `timeoutMs`,两个独立触发器(用于超时的 `killTimer` 和用于上游取消的 `onAbort` 监听器),各自调用同一个 `kill()` 闭包对进程组执行 SIGTERM→宽限期→SIGKILL 升级,以及两个正交的结果布尔值(`timedOut`、`aborted`)独立锁存。 +- **web_fetch**([packages/web/web-fetch-local/src/provider.ts](../../../../packages/web/web-fetch-local/src/provider.ts))有一套正确但*手写*的超时:构造一个 `AbortController`,连接 `setTimeout(() => controller.abort(new WebError(…, 'WEB_FETCH_TIMEOUT')))`,手动添加和移除上游信号监听器,在 `finally` 中清除定时器,并在 `translateAbortOrNetwork` 辅助函数中从 `signal.reason` 恢复超时原因(因为 reader 只抛出裸 `AbortError`)。 +- **web_search**([packages/web/tool-web/src/search.ts](../../../../packages/web/tool-web/src/search.ts))**完全没有超时**:`WebSearchRequest`([packages/web/web/src/types.ts](../../../../packages/web/web/src/types.ts))不携带 `timeoutMs` 字段,各提供方的 `search()` 只转发 `exec.signal`。(web_search 在本次设计中保持无超时——见「后果」。) + +每个新的外部进程或网络工具都要重新推导同样四件事:钳位请求值、启动定时器、将超时与上游取消融合、在出口处区分「超时」与「已取消」。而融合与原因恢复恰恰是最容易出微妙错误的部分(web_fetch 的 `signal.reason` 处理就是证据)。与此同时,各能力执行的*终止*操作不可归约地不同:bash 杀死一个 OS 进程组(工作运行在子进程中,在本运行时之外,只能通过信号触达),而 web 中止一个进程内的 `fetch`(undici 拆除 socket)。不存在一个能停止所有能力工作的单一机制。 + +## 决策 + +`@deepseek-ai/dsh-timeout` 位于 `packages/util/`(与 `dsh-brand` 同级),负责超时的*计时与分类*这一半;*终止*那一半——硬终止——留在各能力的实现中。它是一个纯函数库,**不是** Cordis 服务或插件:不接收 `ctx`、不注册任何东西、不持有跨调用状态、不发射事件。这里刻意不设中央「超时服务」,因为那样的服务必须知道如何停止每个能力的工作——而这正是微内核要排除在共享层之外的知识,也是 Codex 将 `ExecExpiration` 限定于 exec 族所示范的原则。 + +### 库的对外接口 + +四个函数、一个 watchdog 接口加一个 reason 类型: + +```ts ignore-check +/** The internal reason attached to a timeout abort, so consumers can classify it after the fact. */ +export class TimeoutReason extends Error { + override name = 'TimeoutReason' + + constructor(readonly code: string, readonly timeoutMs: number) { + super(`${code} after ${timeoutMs}ms`) + } +} + +/** Validate/fill a caller's optional positive hint from the backend's default, then cap at its max. */ +export function clampTimeout( + requested: number | undefined, + def: number, + max: number, + name = 'timeoutMs', +): number + +/** + * Build a deadline signal that aborts on upstream cancellation OR on timeout, + * with the timeout carrying a `TimeoutReason`. `timeoutMs <= 0` means "no + * timeout" (background tasks): forward only the upstream signal, arm no timer. + * The returned object's `[Symbol.dispose]` clears the timer — `using` for a + * scope-lifetime consumer, a manual call for an event-lifetime one. + */ +export function deadline( + upstream: AbortSignal | undefined, + timeoutMs: number, + code: string, +): { signal: AbortSignal; [Symbol.dispose](): void } + +/** A stable signal plus one-at-a-time, timer-guarded async-iterator demand. */ +export interface IdleWatchdog { + readonly signal: AbortSignal + next<T>(iterator: AsyncIterator<T>): Promise<IteratorResult<T>> + [Symbol.dispose](): void +} + +/** Arm only while one iterator `next()` is outstanding, then rearm on later demand. */ +export function idleWatchdog( + upstream: AbortSignal | undefined, + timeoutMs: number, + code: string, +): IdleWatchdog + +/** Recover the TimeoutReason from an aborted signal (or error); `code` scopes the match to this deadline's timer. */ +export function timeoutOf(x: AbortSignal | { reason?: unknown }, code?: string): TimeoutReason | undefined +``` + +`deadline` 通过 `AbortSignal.any` 将上游信号与一次性定时器融合,附加一个类型化的 `TimeoutReason`,并暴露可 dispose(资源释放)的定时器清理。非正数超时是内部的「无超时」哨兵,用于后端拥有的后台任务;外部提示经过 `clampTimeout`,必须为正有限值。既无定时器也无上游信号时,函数返回一个永不中止的信号,具有相同的 disposal 形状。`idleWatchdog` 则要求正有限的间隔,在整个流期间保持一个稳定的融合信号,并且只在一个迭代器 `next()` 尚未结算时启动定时器;结算会解除定时器,后续 demand 会重新启动,并发 demand 会失败,dispose 会清除当前 arm。提供方将超时原因转译为 seam 特定的结果。`timeoutOf(signal, code)` 限定分类范围,使外层嵌套的 deadline 被视为上游取消而非内层能力自身的超时。 + +### 职责划分 + +| 关注点 | 负责方 | +|---|---| +| 校验请求提示并钳位默认值/最大值 | `dsh-timeout`(`clampTimeout`):纯算术加共享的正有限请求契约 | +| 启动一次性定时器、到期中止、携带 reason、与上游取消融合 | `dsh-timeout`(`deadline`) | +| 仅围绕未结算的迭代器 demand 启动和重启 | `dsh-timeout`(`idleWatchdog`) | +| 清除定时器 | `dsh-timeout`(任一原语的 `[Symbol.dispose]`) | +| 中止后对首个 abort reason 进行分类 | `dsh-timeout`(`timeoutOf`) | +| **实际终止工作** | 各能力的实现 | +| 默认值/最大值*数值* | 各能力的配置 | +| 超时 `code` 字符串 | 各能力(`WEB_FETCH_TIMEOUT` ≠ `BASH_TIMEOUT`) | + +信号只*通知*;终止始终是监听方的职责,而监听方因能力而异。bash 自行编写 `addEventListener('abort', kill)`,因为 OS 进程存在于本运行时之外,没有别的东西会杀死它;web 将 `d.signal` 交给 `fetch`,由 undici 拆除 socket。这也是文件读/写/编辑**不接受** `timeoutMs` 的原因:本地系统调用最多只能尽力中止,超时无法强制 `fsync`/`rename` 停止,添加超时将是一个违反「显式优于隐式」的隐式默认值。两个参考 agent 出于同样的原因对文件 I/O 不设超时。 + +### 各能力如何消费该库 + +- **web_fetch**:工具层保持校验并转发;提供方手写的 controller + `setTimeout` + 手动监听器 + `finally` + `signal.reason` 恢复被替换为提供方自有的 `deadline`/`timeoutOf`。已预先中止的上游信号仍然立即抛出 `WEB_ABORTED`;否则 `fetch` 使用融合后的 `d.signal` 运行,`translateAbortOrNetwork` 根据信号分类抛出的错误(`timeoutOf` → `WEB_FETCH_TIMEOUT`,否则已中止 → `WEB_ABORTED`,否则网络错误 → `WEB_PROVIDER_ERROR`)。公开的错误码契约不变,`TimeoutReason` 永远不会作为公开错误跨越 web seam。 +- **bash**:`resolve()` 将请求钳位为显式规格。前台 `run()` 创建 deadline 并将其信号传给进程执行,后者既有的 abort 监听器执行进程组 kill。执行器将首个 abort 分类为超时或取消。后台启动保持无超时,仅转发上游取消。 +- **LLM 适配器**:`dsh-llm-deepseek` 和 `dsh-llm-pi-ai` 用 `idleWatchdog` 包装实际的传输迭代。配置的五分钟间隔只覆盖尚未结算的提供方 demand,不包括下游消费方在分片之间花费的时间。稳定信号在整个调用期间传给 `fetch` 或 SDK,因此超时会关闭底层请求并映射为 `TIMEOUT`,而更早的调用方中止映射为 `ABORTED`。 + +## 后果 + +- `runBash` 的结果不再独立锁存 `timedOut` 和 `aborted`;超时与用户中止在进程关闭前竞争时,现在报告单一的首个 abort 原因,而非两者同时为 true。统一的 SIGTERM→宽限期→SIGKILL 终止路径不变,seam 类型 `BashRunResult` 保留两个布尔值(现在互斥),因此 `dsh-tool-bash` 的结果渲染不受影响。 +- `SpawnSpec.timeoutMs` 和 `SpawnOutcome.timedOut`/`aborted` 被移除,而非作为始终为零/始终为 false 的残余保留:由于 `runBash` 不再拥有定时器且执行器负责分类,这些字段无处被读取。这是与字面提案形状(向 `runBash` 传入 `timeoutMs: 0`)的唯一偏差;一个始终为 0 且无处读取的字段在逐文件覆盖率门禁下属于死代码。 +- web_fetch 去除了其定制的 controller/timer/listener/reason-recovery;分类器现在基于 deadline 信号(`timeoutOf` + `aborted`)而非抛出错误的形状来判断,这在请求阶段的 reject-with-reason 和读取阶段的裸 `AbortError` 两种情况下都是健壮的。 +- `AbortSignal.any` 和 `using`/`Symbol.dispose` 在此首次进入本仓库(Node ≥ 24 基线,已满足)。 +- 模型流现在共享一个可重启的定时器契约,不会把滑动的空闲间隔变成总调用截止时间,也不会计入消费方思考时间。该原语仍然只做通知;适配器测试证明其传输观察到稳定信号并终止。 + +以下内容不在本次范围内,列出以标明边界:`web_search` 可以在其工具 schema/快照覆盖率规划就绪后获得可选的面向模型的 `timeout_ms`;未来基于 ripgrep 的文件系统发现工具可以在存在后消费同样的提供方自有 deadline 形状;`tools/execute` waterfall(瀑布式事件)中间件可以通过驱动 `exec.signal` 为每次工具调用设置默认 deadline——那将是一个*消费*本库的插件,仍然只做通知,硬终止仍是各能力自己的事。 + +## 曾考虑的替代方案 + +**统一的超时*插件* / `ctx.timeout` 服务。** 基于微内核原则否决。一个能停止任何工具工作的服务必须理解每个能力的终止机制(进程组 SIGKILL、socket 拆除、系统调用边界检查),这正是架构所禁止的「内核知道太多」。Codex 的 `ExecExpiration` 被限定于 exec 族,正是因为它驱动的 kill(`killpg`)是进程族特有的;MCP 和模型流各自保有自己的。不存在一个连贯的中间层能为所有东西拥有终止权,因此共享部分只能是纯计时/分类那一半——一个库,而非服务。 + +**每个工具各自实现超时,不共享代码(先前的现状,也是 Claude Code 的选择)。** 否决,因为它已经在产生分化和重复的正确性负担:web_fetch 手写了与未来网络/进程类工具各自需要重新推导的完全相同的 controller/reason 逻辑,而融合 + `signal.reason` 恢复正是容易出错的部分。Claude Code 容忍完全重复;本仓库有一个统一的共享 abort 通道(每次 `execute` 上的 `exec.signal`),使得一个小型共享原语严格更优,因此成本/收益不同。 + +**用 `withTimeout(promise, ms)` 包装器代替信号工厂。** 否决,因为让 promise 与定时器竞争只是在截止时间到达时 resolve *工具调用*的 promise,而不会停止底层工作——子进程或 fetch socket 会泄漏。分发信号并要求能力监听,才能强制一条真实的终止路径存在。这与「dispose 必须达到完全停稳,而非仅仅请求它」的防御性规则一致。 + +**保留 bash 独立的超时和取消触发器。** 否决,因为一个 deadline 信号移除了定制定时器并标准化了分类。竞争的原因报告先到达的那个 abort,而既有的 SIGTERM→SIGKILL 终止路径保持不变。 diff --git a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.i18n.yaml new file mode 100644 index 0000000000..bd2426f377 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-07-tool-call-timeout-policy.md: 69fd1ee721de69621d3b57c10d960da0651b94dd +2026-07-07-tool-call-timeout-policy.zh.md: c0dc56127cb983bd515db424d0ca37da9d0e978a diff --git a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md index b7713fa8e0..69fd1ee721 100644 --- a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md +++ b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-07-tool-call-timeout-policy.zh.md) + ## Problem The [timeout/deadline Agent Note](2026-07-06-timeout-deadline-library.md) extracted the timing-and-classification primitive into `@deepseek-ai/dsh-timeout`, but timeout policy was still attached to individual capabilities and model-facing schemas. `bash` exposed `timeoutMs`; `web_fetch` exposed `timeout_ms`; `web_search` had no model-facing timeout even though providers already honor `exec.signal`; a future grep/glob tool would either import the timeout library directly or invent its own timeout policy. That is the wrong authoring shape for a plugin SDK: a tool author should normally forward `exec.signal` to the implementation it calls, and deployment policy should decide the budget. diff --git a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.zh.md b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.zh.md new file mode 100644 index 0000000000..c0dc56127c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.zh.md @@ -0,0 +1,114 @@ +# Agent Note: 工具调用超时策略作为插件 + +Status: implemented + +[English](2026-07-07-tool-call-timeout-policy.md) | 中文 + +## 问题 + +[超时/截止时间 Agent Note](2026-07-06-timeout-deadline-library.md) 将计时与分类原语提取到了 `@deepseek-ai/dsh-timeout`,但超时策略仍然附着在各个能力和面向模型的 schema 上。`bash` 暴露了 `timeoutMs`;`web_fetch` 暴露了 `timeout_ms`;`web_search` 没有面向模型的超时参数,尽管提供方已经遵循 `exec.signal`;未来的 grep/glob 工具要么直接导入超时库,要么自行发明超时策略。对于一个插件 SDK 来说,这是错误的编写范式:工具作者通常只需将 `exec.signal` 转发给其调用的实现,而部署策略来决定预算。 + +与此同时,仓库中并非所有超时都是面向模型的工具调用预算。钩子通过直接调用 `ctx.bash` 执行命令钩子,而非通过 `ctx.tools.execute()`;`bash` 模型工具通过同一个后端复用前台执行、后台启动、后台轮询和钩子调用。一步到位地将所有超时移入工具插件会混淆这些路径,并有破坏钩子超时语义的风险。 + +## 决策 + +工具调用超时是仅适用于面向模型的工具执行的策略,由三部分组成: + +- `@deepseek-ai/dsh-timeout` 仍是拥有 `deadline()` 和 `timeoutOf()` 的共享库。 +- `@deepseek-ai/dsh-tools` 在 `tools/pre-execute` 和 `tools/post-execute` 之间有一个环绕分发的 waterfall(瀑布式事件)`tools/execute`。 +- `@deepseek-ai/dsh-timeout-policy` 从注册表读取每个工具声明的 `timeoutMs`,并通过派生新的 `exec.signal` 来包装有此声明的调用。 + +执行流水线如下: + +```text +ctx.tools.execute(exec) + -> tools/pre-execute + -> tools/execute + -> registry dispatch (the base next()) + -> tool.execute(args, exec) + -> thrown tool errors normalize to ToolExecutionResult + -> tools/post-execute +``` + +默认行为是保守的:未声明 `timeoutMs` 的工具不会从该插件收到 `TOOL_TIMEOUT` 截止信号。 + +### `tools/execute` 环绕 seam + +`@deepseek-ai/dsh-tools` 声明了一个 `tools/execute` waterfall,其基础 `next()` 是带规范化的分发 thunk——即同一个内部 `try`/`catch`,将抛出的工具错误(或未知工具错误)转换为 `isError` 的 `ToolExecutionResult`。监听器接收 `(exec, next)`:调用 `next()` 委托给分发(返回其结果,可选地包装),或返回替代结果以短路分发。整个流水线仍位于 `execute` 的外层 try/catch 内,因此抛出异常的监听器会变成 `isError` 结果,而非轮次失败。 + +catch 是基础 `next`(而非 waterfall 之外的东西)这一点至关重要:当提供方看到超时信号并抛出自己的上游中止错误时,注册表分发首先将其转换为普通错误结果,然后 `timeout-policy` 才能将最终结果替换为 `TOOL_TIMEOUT`。 + +### `timeout-policy` 插件 + +该插件是 `@deepseek-ai/dsh-timeout-policy`,一个零配置的函数/命名空间插件(`name` / `inject` / `apply`),位于 `packages/timeout/` 组。每个工具的预算声明在工具自身,而非本插件:`ToolDefinition` 携带一个可选的 `timeoutMs`,由拥有该工具的插件从自身配置中设置。例如 `dsh-tool-web` 将 `fetchTimeoutMs` / `searchTimeoutMs`(默认 30000)解析到 `web_fetch` / `web_search` 的定义上: + +```yaml +- id: timeout-policy + name: '@deepseek-ai/dsh-timeout-policy' +- id: tool-web + name: '@deepseek-ai/dsh-tool-web' + config: + fetchTimeoutMs: 30000 + searchTimeoutMs: 30000 +``` + +超时放在工具定义上而非自由文本名称映射中,消除了拼错名称导致策略不生效的问题。`defineTool` 校验预算为正有限数。分发期间,执行器派生截止信号并将其赋给 `exec.signal`;注册表依据[工具取消契约](2026-07-19-cooperative-tool-cancellation.md),在执行工具体之前将该截止信号与调用方的原始信号融合。执行器随后恢复调用方信号,并将自身的超时转换为 `TOOL_TIMEOUT`;没有预算的工具原样通过。 + +信号替换采用**就地修改 `exec.signal`** 的方式,而非向 `next()` 传递新对象。Cordis 的 waterfall `next()` 忽略传入的任何参数,并以共享的 payload 数组重新调用下游监听器(`vendor/cordis/src/events.ts`),因此修改共享对象是包装器向注册表提供截止信号的方式。注册表会在进入工具体前再次融合已捕获的调用方信号;插件则在 `finally` 中将 `exec.signal` 恢复为调用方的原始值,使 `tools/post-execute` 永远不会看到本插件的截止信号。 + +`timeout-policy` 拥有 `TOOL_TIMEOUT` 代码的两种用途:传递给 `deadline()`/`timeoutOf()` 的内部截止代码(有作用域,使嵌套的外层截止读为普通取消)和结构化工具结果错误代码。其替换结果为: + +```ts ignore-check +function toolTimeoutResult(timeoutMs: number): ToolExecutionResult { + return { + content: [{ type: 'text', text: `Error: tool call timed out after ${timeoutMs}ms` }], + isError: true, + error: { + message: `tool call timed out after ${timeoutMs}ms`, + info: { name: 'ToolTimeoutError', code: 'TOOL_TIMEOUT' }, + }, + } +} +``` + +这是一个协作式截止。它不会通过竞争工具 promise 来杀死任意工作;工具或其调用的能力必须遵循 `exec.signal` 并达到完全停稳。因此声明 `timeoutMs` 意味着「此工具与 `exec.signal` 协作」,插件 README 将此作为其契约。 + +无需新的会话事件来保证可重建性:`TOOL_TIMEOUT` 是该调用的最终面向模型的 `tool/result`,因此现有会话日志已经记录了下一次模型请求所见的内容和结构化 `{ name, code }` 错误。 + +### 现有工具适配 + +`web_fetch` 和 `web_search` 已迁移。`dsh-tool-web` 保留对其面向模型 schema 的所有权,这些 schema 不暴露超时旋钮:`web_fetch` 移除了 `timeout_ms` 参数以匹配参考 agent 的形状,`web_search` 保持仅查询。工具体不导入 `@deepseek-ai/dsh-timeout`;它们将 `exec.signal` 转发给 `ctx.web`。 + +`dsh-web-fetch-local` 保留一个配置级别的 `timeoutMs` 作为大型资源兜底,服务于直接调用 `ctx.web.fetch()` 的调用方和配置错误的部署;它不拥有面向模型的超时。当 `TOOL_TIMEOUT` 信号先到达 fetch 提供方时,提供方作用域的分类将其视为上游 `WEB_ABORTED`,而外层 `tools/execute` 包装器将最终工具结果替换为 `TOOL_TIMEOUT`。一个已发布的 web 工具部署将提供方兜底配置为高于 `timeout-policy` 预算,使工具调用策略在模型调用中通常胜出。 + +`bash` 保持当前的后端超时路径。`dsh-tool-bash` 继续暴露 `timeoutMs` 和 `run_in_background`;`dsh-bash-local` 继续使用 `@deepseek-ai/dsh-timeout` 处理 `BASH_TIMEOUT`;钩子桥接继续调用 `runHook()` 并通过 `ctx.bash` 传递 `timeoutMs`。这保持了前台/后台/钩子行为的稳定。 + +`read`、`write`、`edit`、`todo_write`、`task_list` 和 `task_kill` 不加入工具调用超时。`task_output` 自己拥有有界等待,因为等待超时是成功的实时状态结果,而非工具失败。 + +未来面向模型的 grep/glob 工具可以基于 `ctx.bash` 实现而无需导入 `@deepseek-ai/dsh-timeout`:它将 `exec.signal` 转发给 `ctx.bash`,并声明自己的 `timeoutMs`(来自其插件配置)供执行器应用。如果 bash-local 的后端超时对这类工具造成问题,bash seam 可以后续添加调用方自有截止模式;这不在本次范围内。 + +## 曾考虑的替代方案 + +**将插件命名为 `tool-timeout`。** 字面的 Agent Note 名称匹配了 `gen-tool-catalog` 完整性守卫的 `packages/*/tool-*` glob,该 glob 要求每个匹配项注册一个面向模型的工具。本插件不注册任何工具——它是一个 `tools/execute` 包装器——因此 `tool-*` 名称要么导致 `verify-tool-catalog` 失败,要么强制产生一个误导性的启动条目。包(package)为 `@deepseek-ai/dsh-timeout-policy`,位于新的 `packages/timeout/` 组;cordis.yml 的 `id` 仍可为 `timeout-policy`。 + +**仅保留逐工具的超时处理。** 这是 `bash` 和 `web_fetch` 的既有形态,也与 Claude Code 和 Codex 对 shell 命令的做法一致。它对 web 类工具不利,因为每个新的支持超时的工具都必须自行选择校验方式、上限语义、文档、快照和分类。插件集中了策略和分类,让每个工具的 schema 专注于业务输入。 + +**立即将所有超时策略移出 bash-local。** 长期来看更干净——bash-local 将成为纯子进程执行器,所有调用方自行管理截止时间。但作为第一步不合适,因为钩子直接调用 `ctx.bash`,且 bash 模型工具的前台/后台语义与工具调用生命周期不同。保留 `BASH_TIMEOUT` 维持了这些路径的稳定,同时让工具调用超时在更简单的工具上先行验证。 + +**为所有工具使用全局默认预算。** 方便,但会让工具作者意外:任何偶然运行超过全局预算的工具在插件加载后就会开始失败。逐工具声明预算使采纳成为有意的行为。 + +**暴露面向模型的 `timeout_ms` 覆盖参数。** Claude Code 的 `WebFetch`/`WebSearch` 和 Codex 的 web 工具将超时排除在模型调用形状之外。模型覆盖会使超时成为提示词语义的一部分,并迫使 `timeout-policy` 引入 schema/参数剥离规则。Web 超时仅作为部署策略。 + +**让 `timeout-policy` 自行匹配工具参数。** 诸如「当 `bash.run_in_background` 为 true 时禁用超时」之类的规则引擎会让策略插件了解工具特定的参数语义。通过不将 bash 迁移到工具调用超时来规避此问题。 + +**使用 `tools/pre-execute` 加 `tools/post-execute` 代替新的环绕 seam。** pre 监听器可以启动截止时间并修改 `exec.signal`;post 监听器可以分类并替换。这样做的问题是截止时间的生命周期会跨越两个独立的 waterfall:需要 call-id 映射、在每条 pre-deny/tool-throw/post-throw/dispose 路径上清理,以及与其他监听器的排序规则。`tools/pre-execute` 也是允许/拒绝门禁,而非执行包装器。`tools/execute` 给超时一个词法作用域:启动、委托、分类、释放。 + +**使用 `Promise.race` 对非协作工具强制超时。** 与超时库 Agent Note 相同的理由否决:它在底层进程、fetch 或提供方操作可能仍在运行时就将控制权返回给调用方。插件只发送信号;终止仍是实现方的责任。 + +## 后果 + +- `@deepseek-ai/dsh-tools` 在有意拆分 pre/post 工具钩子的拦截 seam 之后,获得了一个环绕分发的表面。其契约是狭窄的——包装注册表分发,而非替代 pre 门禁或 post 结果策略——且基础 `next()` 是带规范化的分发,因此包装器永远不会看到原始的工具抛出。 +- 多个 `tools/execute` 监听器按普通 Cordis waterfall 顺序组合:调用 `next()` 的监听器包装下游监听器加分发;不调用 `next()` 直接返回的监听器短路它们。一个同时组合超时与未来重试/沙箱/指标包装器的部署通过注册顺序选择语义(「超时覆盖整个重试」vs「超时覆盖每次尝试」)。 +- 按声明加入是一个有意的误配置风险:工具可以声明 `timeoutMs` 但不遵循 `exec.signal`,这样的工具在超时时不会停止。注册表会等待这一未达完全停稳的工具体,而不是竞速它;同时插件契约声明:声明预算意味着协作;web 工具在已转发信号的工具上验证了这一模式。 +- 过渡期间 `bash` 和已迁移的 web 工具有意使用不同的超时路径:`TOOL_TIMEOUT` 是面向模型的工具调用预算,而 `BASH_TIMEOUT` 仍是 bash 和钩子使用的 bash 后端超时。 +- 与字面提案的偏差,按 implemented-Agent Note 规则记录:插件包为 `@deepseek-ai/dsh-timeout-policy`(而非 `tool-timeout`);信号替换是在 `next()` 之前就地修改 `exec.signal`(而非 `next({ ...exec, signal })`,Cordis 会忽略后者);逐工具预算声明在 `ToolDefinition` 上(`timeoutMs`,由拥有该工具的插件从其配置中设置),而非在本插件配置中按工具名映射——因此执行器是零配置的,拼错工具名不可能发生。以上三点均在上文 `## Decision` 中描述。 diff --git a/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.i18n.yaml new file mode 100644 index 0000000000..67955d377d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-08-agent-scope-contexts.md: e4c076189a8e8a438b561232d3779ad1f6ab0d08 +2026-07-08-agent-scope-contexts.zh.md: 35e725e43d402b048daf12c3b4be384b3fd2d2ce diff --git a/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.md b/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.md index 68c9bd3b3e..e4c076189a 100644 --- a/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.md +++ b/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-08-agent-scope-contexts.zh.md) + ## Problem One application needs to share infrastructure across many agents while letting each agent have its own tools, prompt contributions, policies, and listeners. Shared adapters, persistence, and user interfaces belong to the deployment; a persona, tool variant, or listener often belongs to one agent. diff --git a/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.zh.md b/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.zh.md new file mode 100644 index 0000000000..35e725e43d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.zh.md @@ -0,0 +1,171 @@ +# Agent Note: agent 即注册作用域 + +Status: implemented + +[English](2026-07-08-agent-scope-contexts.md) | 中文 + +## 问题 + +一个应用需要在多个 agent(智能体)之间共享基础设施,同时让每个 agent 拥有自己的工具、提示词贡献、策略和监听器。共享的适配器、持久化和用户界面属于部署层面;而 persona、工具变体或监听器往往只属于某一个 agent。 + +为每个 agent 建立独立的服务图会重复共享基础设施。使用一个全局注册图则有相反的问题:某个 agent 特有的贡献可能泄漏到无关的 agent 中。贡献者需要一种普通的注册机制,既能决定谁可以看到某项贡献,又能决定何时清理它。 + +该机制还需要一个发布边界。agent 在其本地世界构建完成之前不得变为可见,拆除时也必须保留该本地世界直到最终工作停止。 + +## 决策 + +每个存活的 agent 拥有一个扁平的注册层,通过 `agent.ctx` 暴露。代码通过拥有某项贡献的上下文进行注册;具备作用域感知的服务将部署全局注册与恰好一个匹配的 agent 层合并;操作从其真实 agent 选择该层;该层在 agent 的完整发布生命周期内存在。 + +Cordis 是 SDK 底层的插件框架。Cordis **上下文**是插件用来访问服务和注册效果的对象,效果的清理跟随该上下文。[Cordis 入门](../../../../docs/cordis-primer.md)对该框架有更详细的说明。 + +对大多数贡献者而言,完整契约是四条规则: + +| 问题 | 规则 | +|---|---| +| 在哪里为某个 agent 注册行为? | 通过 `agent.ctx` 调用普通注册 API | +| 某个 agent 的操作能看到什么? | 部署全局加上该 agent 的层,按所属服务的合并规则 | +| 哪些作用域监听器会运行? | 无作用域监听器加上为该操作所属 agent 注册的监听器 | +| 该层存在多久? | setup 在发布前完成;dispose 保留该层直到工作完全停稳 | + +作用域是扁平的。解析永远不会遍历父级或兄弟作用域,生命周期所有权也不意味着注册继承。 + +```mermaid +flowchart LR + plain["Plain plugin context<br/>cleanup follows the plugin"] -->|"registers into"| globalLayer["Deployment-global layer"] + agentAContext["agentA.ctx<br/>cleanup follows Agent A"] -->|"registers into"| agentALayer["Agent A layer"] + agentBContext["agentB.ctx<br/>cleanup follows Agent B"] -->|"registers into"| agentBLayer["Agent B layer"] + + operationA["Operation for Agent A"] -->|"selects"| agentAView["Agent A view<br/>globals plus A local"] + globalLayer --> agentAView + agentALayer --> agentAView + operationB["Operation for Agent B"] -->|"selects"| agentBView["Agent B view<br/>globals plus B local"] + globalLayer --> agentBView + agentBLayer --> agentBView +``` + +缺失的交叉边即隔离规则:Agent A 的本地注册不会进入 Agent B 的视图,父级的注册也不会仅因父级拥有子级的生命周期就进入子级。 + +配套的[运行时设计 Agent Note](2026-07-12-agent-scope-runtime-design.md) 阐述了实现与正确性推理。[subagent 组合控制 Agent Note](../feature/2026-07-12-subagent-persona-tool-filter-and-depth.md) 负责独立的 `persona`、`toolFilter` 和 `maxDepth` 功能。 + +### 注册来源决定可见性与清理 + +通过普通插件上下文进行的注册是部署全局的,随该插件一起 dispose(资源释放)。同一方法通过 `agent.ctx` 调用则贡献给一个 agent,随该 agent 的作用域一起 dispose。 + +| 注册来源 | 默认可见性 | 随谁 dispose | +|---|---|---| +| 普通插件上下文 | 每个符合条件的 agent 视图 | 注册插件 | +| `agent.ctx` | 仅该 agent 的视图 | agent 作用域 | + +工具、提示词段落与变量、工具限制、守卫以及作用域事件监听器都遵循此契约。命名的本地值通常对该 agent 遮蔽同名全局值;各所属服务文档会说明例外与合并行为。 + +普通贡献者的模式是在 agent setup 期间注册完整的本地世界: + +```js +const handle = await ctx.agents.create({ + sessionId: SessionId('reviewer'), + agentOptions: { model: 'model-name' }, + setup(agentCtx) { + agentCtx.systemPrompt.section({ + name: 'deployment:persona', + order: 0, + text: 'Review code, but do not modify files.', + }) + agentCtx.tools.register({ + name: 'review_summary', + description: 'Return the review summary.', + parameters: { type: 'object', properties: {} }, + async execute() { + return [{ type: 'text', text: 'review complete' }] + }, + }) + }, +}) + +ctx.tools.get('review_summary') // undefined: not global +ctx.tools.get('review_summary', handle.agent) // the reviewer-local tool + +await handle.dispose() +ctx.tools.get('review_summary', handle.agent) // undefined: scope is gone +``` + +setup 接收一个完整的受信 Cordis 上下文,因此可以组合普通插件和服务。其契约仅限组合:不支持通过 cast 或内部注册表调用来驱动或发布正在构建中的 agent。 + +### 操作选择视图 + +注册来源与操作主体是两个独立的事实。通过 `agent.ctx` 调用服务决定的是新注册归属何处,并不将后续读取绑定到该 agent。 + +工具查找与执行接收其所服务的 agent。提示词组装接收正在构建请求的 agent 的组装上下文。事件分发接收其领域主体。这使共享服务实例可在多个 agent 间复用,同时让每个操作的视图保持显式。 + +只有采纳了作用域契约的服务才会解析 agent 层。`agent.ctx` 不会自动改变任意 Cordis 服务调用的行为。 + +### 作用域事件将路由与事件数据分离 + +关于 Agent A 的事件通常到达无作用域监听器和 A 作用域监听器,而不到达 B 作用域监听器。没有 agent 主体的事件仅到达无作用域监听器。 + +在 Cordis 层面,`Scoped<T>` 是一个不透明的路由接收器。它携带用于选择监听器的过滤器,但本身不是领域对象。因此事件签名将真实的 `Agent`、工具执行、审批请求或其他主体作为显式参数保留,供监听器检查。 + +以 `{ global: true }` 注册的监听器有意绕过上下文受众过滤,但其清理仍跟随注册上下文。注册表成员变更通知保持不过滤,因为它们描述的是共享注册表状态而非某个 agent 的操作。生成的[事件目录](../../../../docs/cordis-catalog/events.md)是详尽的事件参考。 + +### 创建最后发布,dispose 最后撤销 + +`ctx.agents.create()` 和 `resume()` 构建未发布的会话、作用域、agent 和驱动器。它们等待 `setup`,准入最终的会话和 agent 条目,按序公告,启动循环,然后才返回 handle。 + +可选的创建信号仅在创建或恢复挂起期间取消工作。promise resolve 后,返回的 `AgentHandle` 拥有显式 dispose 权。 + +如果加载、setup、准入或发布失败,私有事务回滚其准备的一切。使用同一个调用方提供的存活 ID 的并发操作可能都到达 setup,但最终注册表条目只准入一个;每个失败者拒绝并清理其私有资源。在等待 dispose 完成后的顺序复用仍然有效。 + +`AgentHandle.dispose()` 反转边界。它停用创建或驱动,等待同步发布解除,停止并排空驱动器和最终会话刷写,分离 agent 和会话,最后 dispose 作用域。重复或竞争的 dispose 请求合并为一个完成 promise。 + +调用方的 Cordis 上下文和具体的 AgentLoop 工厂是结构性共同所有者。卸载任一方都会 dispose 事务或存活 agent。 + +```mermaid +flowchart TB + request["Create or resume"] --> privateWorld["Build private session, scope, agent, and driver"] + privateWorld --> setup["Await composition through agent.ctx"] + setup --> admission["Admit final session and agent entries"] + admission --> publish["Announce lifecycle and start the driver"] + publish --> live["Return AgentHandle"] + + privateWorld -->|"failure, cancellation, or owner loss"| rollback["Rollback private work"] + setup -->|"failure, cancellation, or owner loss"| rollback + admission -->|"duplicate or owner loss"| rollback + publish -->|"listener failure or owner loss"| rollback + live -->|"handle or owner disposal"| quiesce["Stop and drain work"] + rollback --> quiesce + quiesce --> detach["Detach agent, then session"] + detach --> revoke["Dispose the agent scope"] +``` + +## 安全与权限是非目标 + +agent 作用域组合的是受信的同进程注册。它不沙箱化插件、不定义父到子的权限格、不在创建时冻结授权、也不保证子级不能做超出父级的事。 + +父级可以拥有一个可见工具比自身更广的子级,因为生命周期所有权不赠予也不限制注册。持有 Cordis 上下文的插件同样运行在同一进程中,可以直接调用可用服务。 + +需要非升权保证的部署需要独立的权限表示、传播规则和执行检查。父级子集授权、创建时授权快照、显式未来授权 API,以及通用的能力/输出/终止标签均不在本决策范围内。 + +## 曾考虑的替代方案 + +被否决的设计要么将可见性与清理分离,要么只覆盖一类注册,要么重复共享基础设施,要么将生命周期所有权与继承混为一谈。 + +### 向每个注册传递 agent 选项 + +类似 `tools.register(definition, { agent })` 的 API 在每个注册表中重复作用域管道,且允许可见性所有权与清理所有权漂移。通过 `agent.ctx` 注册使两个事实跟随同一个 Cordis effect owner。 + +### 过滤事件但保持注册表全局 + +监听器过滤可以阻止错误的钩子运行,但无法限定工具 schema、可执行查找、提示词段落、变量或其他已注册数据的作用域。agent 本地组合仍需临时的全局变更。 + +### 为每个 agent 创建独立的服务图 + +所需的视图是共享部署服务加上一个本地注册层。每 agent 一个图会重复适配器,并使共享持久化、提供方注册表和应用启动复杂化。 + +### 继承父级注册作用域 + +父子关系描述的是生命周期和对话谱系,而非通用合并策略。层级查找会让无关服务意外继承,且在没有独立权限模型的情况下无法定义安全性。 + +## 后果 + +贡献者使用一种熟悉的模式:通过插件上下文注册共享行为,通过 `agent.ctx` 注册本地行为,在操作中选择真实 agent,dispose 返回的 handle。从观察者角度看 setup 是原子的,拆除则保留本地行为直到工作停止。 + +代价是显式的主体选择、异步的编程式创建,以及服务需要逐个采纳作用域。扁平注册作用域有意不等同于权限,subagent 组合控制作为独立功能存在,而非隐藏的作用域语义。 diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml index b76ed1a9ae..1ab141230b 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.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 -2026-07-10-single-file-executable-sdk-runtime-distribution.md: 43ba5708d1216c37a7ad7e2904df7d2a6baf016d -2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md: 3b33ff870d745584d2988bb6a7eb1a31e56ec3da +2026-07-10-single-file-executable-sdk-runtime-distribution.md: 39cfb2999dea7767a18702ad7d160c9e88d7bf20 +2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md: e1a21c40647e1418d4afd02c0bc6b44ef0d4a8cf diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md index 43ba5708d1..39cfb2999d 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md @@ -25,7 +25,7 @@ Terminology reminder: pkg's `/snapshot` VFS has nothing to do with this repo's t ### The serving surface is a plugin: the two packages ui/jsonrpc + examples/jsonrpc-demo -The deterministic protocol implementation (`server.ts` / `transport.ts`) lands as two packages on the existing `ui/acp` + `examples/acp-demo` pattern — the serving surface is itself a plugin: +The deterministic protocol implementation (`server.ts` / `transport.ts`) lands as two packages on the existing `acp/acp` + `examples/acp-demo` pattern — the serving surface is itself a plugin: - [`packages/ui/jsonrpc`](../../../../packages/ui/jsonrpc/README.md) (`@deepseek-ai/dsh-jsonrpc`): the pure protocol plugin; on apply it mounts `HarnessSdkServer` plus a line-delimited JSON-RPC transport on the process stdio, with disposal through `ctx.effect()`. Whether to serve is decided by `cordis.yml`; a yml that does not mount it is a legitimate process that does not serve. Protocol-level exit belongs to the plugin (after answering the `shutdown` request it disposes its own fiber, then `exit(0)`; an HMR-style unload only stops the service without exiting the process). - [`packages/examples/jsonrpc-demo`](../../../../packages/examples/jsonrpc-demo/README.md) (`@deepseek-ai/dsh-jsonrpc-demo`): a thin app bin — `installFailLoud` + `loadEnv` + config discovery + `boot()` from [`dsh-app-boot`](../../../../packages/ui/app-boot/src/index.ts), done once boot completes; the server is brought up by the `dsh-jsonrpc` entry in the yml. Its only dependency is app-boot. Process-level exit belongs to the bin (stdin EOF/SIGTERM → dispose then 0, SIGINT → 130). diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md index 3b33ff870d..e1a21c4064 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md @@ -25,7 +25,7 @@ exe 使用 [@yao-pkg/pkg](https://github.com/yao-pkg/pkg)(vercel/pkg 归档后 ### 对外服务接口也是插件:ui/jsonrpc + examples/jsonrpc-demo 两包 -确定性协议实现(`server.ts` / `transport.ts`)按 `ui/acp` + `examples/acp-demo` 的既有模式落为两包——对外服务接口本身也是插件: +确定性协议实现(`server.ts` / `transport.ts`)按 `acp/acp` + `examples/acp-demo` 的既有模式落为两包——对外服务接口本身也是插件: - [`packages/ui/jsonrpc`](../../../../packages/ui/jsonrpc/README.md)(`@deepseek-ai/dsh-jsonrpc`):纯协议插件;执行 `apply` 时,在进程 stdio 上挂载 `HarnessSdkServer` 与按行传输的 JSON-RPC 层,资源释放走 `ctx.effect()`。是否提供服务由 `cordis.yml` 决定;未挂载该插件的配置会启动一个不提供此服务的合法进程。协议级退出归插件所有(应答 `shutdown` 请求后 dispose 自身 fiber,再调用 `exit(0)`;HMR 式卸载只停止服务,不退出进程)。 - [`packages/examples/jsonrpc-demo`](../../../../packages/examples/jsonrpc-demo/README.md)(`@deepseek-ai/dsh-jsonrpc-demo`):轻量应用入口——`installFailLoud` + `loadEnv` + 配置发现 + [`dsh-app-boot`](../../../../packages/ui/app-boot/src/index.ts) 的 `boot()`;`boot()` 完成后入口即完成,服务器由 `cordis.yml` 中的 `dsh-jsonrpc` 条目启动。它只依赖 `app-boot`。进程级退出归 `bin` 所有(stdin EOF/SIGTERM → dispose 后返回 0,SIGINT → 130)。 diff --git a/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.i18n.yaml new file mode 100644 index 0000000000..cbaedf3ab9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-12-agent-scope-runtime-design.md: 232fc02d66411b5ee8a21943795a3be4713bf238 +2026-07-12-agent-scope-runtime-design.zh.md: 39d558f8cde0183a3590d268aca36ea85e5f5c63 diff --git a/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md b/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md index bc27d37268..232fc02d66 100644 --- a/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md +++ b/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-12-agent-scope-runtime-design.zh.md) + ## Problem The [agent-scope contract](2026-07-08-agent-scope-contexts.md) is simple for contributors: register through `agent.ctx`, resolve one global-plus-agent view, publish only after setup, and retain the scope until work stops. The runtime must preserve that contract across a cooperative plugin framework, asynchronous creation, reentrant listeners, durable session commits, and worker or process failure. @@ -286,9 +288,9 @@ An ACP provider crosses a real process and wire boundary, so it retains validati Start resolves only after `initialize` and `newSession` succeed. Abort, spawn failure, RPC failure, or invalid startup response reaps the process before rejection. After readiness, result maps the ACP prompt outcome and streamed output; dispose requests cancellation, closes the connection, and awaits process exit through one memoized path. -## Workflows and ACP UI: retain only independent async facts +## Workflows and ACP processes: retain only independent async facts -Worker and editor bridges need more state than same-process registries because messages, process death, and rendering can settle independently. Their state is organized around those real facts rather than duplicate cancellation protocols. +Worker and child-process bridges need more state than same-process registries because messages, process death, and cleanup can settle independently. Their state is organized around those real facts rather than duplicate cancellation protocols. ### Workflow children are pending starts or published records @@ -304,11 +306,11 @@ The workflow result records the first accepted terminal outcome according to the Public disposal claims its memoized promise before invoking callbacks. Worker death closes admission before processing any queued late child request, synthesizes missing lifecycle ends, and starts child/process cleanup without rewriting an outcome already claimed. -### ACP prompt settlement does not depend on rendering success +### ACP prompt settlement does not depend on update delivery -The ACP UI correlates a prompt with its observed turn directly. It does not scan from a `logWatermark` or use session status as a second reconciliation oracle. +The [automation-only ACP bridge](../simplification/2026-07-23-acp-automation-only-protocol.md) correlates one in-flight prompt with its observed user-message turn directly. It does not scan from a log watermark or use session status as a second reconciliation oracle. -Prompt handling settles correlation in a `finally` around transcript rendering. A rendering failure can fail presentation, but it cannot skip prompt settlement or leave the session permanently in flight. Concurrent loads of the same persisted caller-supplied session ID remain excluded because that is a real persistence identity race, not a UUID collision concern. +The session-event listener settles correlation from the matching `turn/end` even when a committed-message update cannot reach the client. Update delivery therefore cannot leave the session permanently in flight. ACP creates server-assigned fresh session ids and owns every resulting agent handle until connection teardown. ## Correctness enforcement diff --git a/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.zh.md b/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.zh.md new file mode 100644 index 0000000000..39d558f8cd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.zh.md @@ -0,0 +1,392 @@ +# Agent Note: Agent 作用域运行时设计与正确性 + +Status: implemented + +[English](2026-07-12-agent-scope-runtime-design.md) | 中文 + +## 问题 + +[agent 作用域契约](2026-07-08-agent-scope-contexts.md)对贡献者而言很简单:通过 `agent.ctx` 注册,解析出一个全局加单 agent 的视图,仅在 setup 完成后发布,并保持作用域直到工作停止。运行时必须在协作式插件框架、异步创建、可重入监听器、持久化会话提交以及 worker 或进程故障等场景下维护这份契约。 + +主要的设计风险是为每个竞态条件引入第二套机制。独立的预留、就绪哨兵、取消中继、快照层和保护注册表可能镜像同一个事实,直到没有读者能分辨哪个才是权威的。这些机制还会诱使运行时把可信的类型化调用当作敌对的序列化边界来处理。 + +实现需要足够的状态来维护真实的所有权和结算边界,但不能更多。正确性审查者必须能够从接受、发布到拆除,沿着一条事实链跟踪下去,而无需在并行的表示之间做调和。 + +## 决策 + +运行时对每个独立事实使用一种机制。作用域路由有一个不透明载体与共享 layer store;每个活跃的注册表对象有一条注册表条目;每个创建或恢复操作有一个事务;类型化的同进程调用借用 readonly 值;真实数据边界只物化一次;协作式提示词组装的结果即为权威;worker/进程代码仅在不同所有者确实可能竞争时才保留独立的终止态和完全停稳态。 + +该设计可概括为七项选择: + +| 问题 | 权威机制 | +|---|---| +| 选择全局加某个 agent 的注册 | 不透明作用域键、路由载体与共享 layer store | +| 拥有一个活跃的 agent 或会话 | 由其 disposer 捕获的单条注册表条目 | +| 协调创建/恢复 | 单个 `AgentCreationTransaction` | +| 保护持久化、队列、模型或协议格式数据 | 在该边界处一次性物化 | +| 在同一进程内传递类型化值 | Readonly 借用契约 | +| 组合模型可见的提示词与工具表面 | 单个共享工具视图加权威的 assembly-waterfall 结果 | +| 协调 subagent、worker 和进程关闭 | 单个取消信号加该边界独立的终止态/完全停稳态事实 | + +本 Agent Note 余下部分按依赖顺序展开这些选择:Cordis 机制、作用域路由、创建与会话提交、工具与提示词、subagent 与工作流,最后是可执行检查。 + +[7 月 8 日 Agent Note](2026-07-08-agent-scope-contexts.md)仍然是贡献者契约。独立的 [subagent 组合控制 Agent Note](../feature/2026-07-12-subagent-persona-tool-filter-and-depth.md)拥有 `persona`、`toolFilter` 和 `maxDepth`;本文仅讨论它们的 setup 如何融入生命周期。 + +## Cordis 模型:上下文、fiber、effect、receiver 与 waterfall + +理解实现需要五个 Cordis 概念。上下文选择服务和注册所有权;fiber 是一个活跃的插件或子生命周期;effect 将清理逻辑附加到 fiber;事件接收器选择监听器;waterfall(瀑布式事件)让监听器按顺序变换或否决一个操作。 + +### 上下文是贯穿单个服务图的所有权路径 + +所有 agent 共享一个 Cordis 服务图。派生的上下文不会克隆 `ToolRegistry`、`SystemPrompt`、持久化或模型适配器;它改变的是:通过该上下文进行的注册如何被标记,以及哪些 effect 拥有其清理逻辑。 + +`agent.ctx` 就是这样一个派生上下文。服务调用仍然到达共享实例,而注册操作可以检查其调用上下文并将贡献存储在最近的作用域键下。普通的插件上下文不携带作用域键,因此注册到全局。 + +### Fiber 与 effect 使清理成为结构性的 + +Cordis fiber 是插件或子上下文被激活时创建的活跃实例。其状态记录该生命周期是 active、unloading、failed 还是 disposed。`ctx.effect()` 和 `ctx.on()` 返回 disposer,同时将这些 disposer 附加到注册所在的 fiber,因此卸载一个插件或 agent 作用域会移除通过该上下文注册的一切,无需单独的清单。 + +vendor 中的 Cordis fiber 实现在任意 setup 或 `internal/plugin` 观察者运行之前就建立了所有权。可重入的卸载可以看到已启动的子 fiber 或 effect,拒绝卸载开始后添加的 effect,并通过一个公开的一次性 disposer 加入已启动的清理。拆除观察者被逐个隔离,因此一个回调无法阻止结构性清理。 + +这些是框架生命周期保证,而非 agent 特有的策略。Agent 创建依赖它们,因为 setup 可以激活任意插件并同步重入所有者的 dispose。 + +### Receiver 路由监听器;waterfall 组合决策 + +Cordis 使用 dispatch receiver(`this`)过滤监听器,而 harness 的监听器需要一个显式的 agent、execution、request 或其他主体。`Scoped<T>` 标记作用域事件声明所期望的 receiver,但运行时载体刻意不暴露主体 API。 + +因此,产品辅助函数构造载体并单独传递领域主体。这防止监听器路由变成另一套对象模型,并使事件签名在不了解载体内部的情况下也可理解。 + +Cordis waterfall 是中间件风格的 dispatch。每个监听器接收 `next()`:调用它则委托给剩余监听器和基础操作,不调用则否决或替换下游结果。Waterfall 驱动提示词组装和工具策略;普通 emit 事件同步通知,parallel 事件等待所有监听器但没有否决结果。 + +## 作用域路由:一个不透明键选择一层 + +scope 包实现了 Cordis 路由所需的最小对象。其载体仅持有一个组合的服务过滤器和作用域谓词,而包私有地记录不透明键,并单独暴露会等待作用域 fiber 完全停稳的 disposer。 + +### 作用域标识使用对象标识 + +`ScopeKey` 是一个按标识比较的不透明对象。Harness 使用活跃的 `Agent` 作为自身的键,但该原语与领域无关,支持其他作用域所有者。 + +`createScope(parent, key)` 返回一个作用域,其 `ctx` 共享父级的服务,其 effect 被标记为该键。`scopeOf(ctx)` 读取最近的注册键。`scopeTarget(base, key)` 创建事件接收器,其过滤器保留 base receiver 的 Cordis 服务过滤器,然后接纳无作用域的监听器和具有该确切键的监听器。 + +Receiver 是一个小型载体而非领域对象的透明代理。需要 agent 的代码接收显式的事件参数;需要注册所有权的代码接收 `agent.ctx`。 + +### 注册表读取叠加一个精确 layer + +作用域感知的注册表使用 `ScopedLayers`,拥有一个即时创建的全局 aggregate 和按标识键惰性创建的 aggregate。读取解析全局 layer 和至多一个精确局部 layer;它不创建状态,也从不遍历父级链。注册可见性与 Cordis effect 所有权都从同一个上下文派生,而回收会等待具体 layer 的完整 aggregate 变空(见[决策](2026-07-12-scoped-layers-store.md))。 + +每个服务保留其领域规则。命名 command 和提示词视图使用共享的、保持插入顺序的 shadow 合并;工具保留更丰富的 resolver,因为限制会在加入局部工具前过滤全局工具,保留的 Code Mode transport 则单独插入。提示词变量和工具 guard 保持实时迭代,而工具提供方成员关系按每次 assembly 物化。Scope 提供存储生命周期和命名遮蔽,而非通用的注册表视图。 + +### 融合 dispatch 辅助函数防止主体漂移 + +`agentEvents(context, agent)` 构造 agent 的载体并注入同一个 agent 作为事件主体。会话、工具、approval、提示词和 subagent 服务同样从它们已拥有的对象派生路由,而非接受一个无关的键。 + +类型标记拒绝普通的裸 receiver 误用,开发环境不变式覆盖直接 JavaScript 或强制转换的 dispatch。主体保持显式,因为路由正确性和有用的事件数据是不同的关注点。 + +## Agent 创建:一个事务拥有完整操作 + +创建和恢复是一个具有多个阶段的异步生命周期,而非多个生命周期。`AgentCreationTransaction` 拥有调用方和工厂的活跃性、可选取消、私有资源、发布、回滚,以及每个所有者观察到的记忆化拆除。 + +### 注册表条目是唯一的活跃标识记录 + +AgentRegistry 和 SessionStore 各为每个活跃对象保留一条注册表条目。注册表条目持有稳定 ID、对象、作用域载体,以及属于该对象的少量发布或追加状态。 + +detach 闭包捕获其确切注册表条目。它仅在映射仍指向该注册表条目时才删除,因此旧的 disposer 无法删除一个复用相同 ID 的后续对象。注册表不会重读可变的调用方对象来决定标识。 + +没有预留 API。调用方提供的 ID 在最终写入注册表时被接纳。并发的同 ID 操作可能都完成私有 setup;恰好一个最终 `enter()` 成功,每个失败者回滚其私有资源。前一个 disposer 达到完全停稳态后,顺序复用即为有效。 + +### 事务在等待之前就拥有准备工作 + +事务在持久化加载或 setup 可能挂起之前,就被安装到调用方的 Cordis 上下文和具体的 AgentLoop 工厂下。它还在公开操作结算之前观察可选的创建/恢复信号。 + +创建准备一个新 Session。恢复加载并验证持久化的 Session,然后准备相同的活跃会话标识。两条路径随后构建作用域、agent 和 driver,并调用相同的 setup/发布算法。 + +工厂存储具体的 trace 目标,但通过调用方绑定的 Cordis trace 调用它们。这保留了依赖来源和调用方所有权,而不堆叠 trace 代理。 + +### Setup 是私有世界内的可信组合 + +Setup 接收完整的子上下文,可以等待插件激活。它可以注册工具、提示词段、限制、监听器和其他 effect,但公开契约不支持通过强制转换或内部注册表调用来驱动或发布正在创建中的 agent。 + +事务将异步加载和 setup 与停用进行竞争,而非无限等待外部代码拥有的 promise。如果取消或所有者卸载获胜,即使外部 promise 永不结算,公开创建也会在事务拥有的清理之后拒绝。 + +### 发布有一条有序的提交路径 + +发布按观察者所需的顺序接纳和宣告资源: + +1. 将会话写入注册表。 +2. 将 agent 写入注册表。 +3. 宣告 `session/created`。 +4. 宣告 `agent/created`。 +5. 启用公开驱动。 +6. 发射 `agent/session-start`。 +7. 启动 driver。 + +Agent 在两个注册表和创建通知都达成一致之前绝不驱动。同步监听器可以否决或 dispose 一个所有者;事务记录发布进行中,并等待该回调栈展开后再继续拆除。每个已开始的创建宣告在回滚期间都有匹配的销毁宣告。 + +以下序列图隔离了非显而易见的竞态:同步创建监听器可以在发布调用栈仍拥有两个注册表条目时请求 dispose。拆除必须立即停用,但要等待该栈展开后才停止和分离任何东西。 + +```mermaid +sequenceDiagram + participant Tx as AgentCreationTransaction + participant Registries + participant Listener as Synchronous listener + participant Driver + + Tx->>Tx: mark publication in progress + Tx->>Registries: announce agent/created + Registries->>Listener: invoke inside the same call stack + Listener->>Tx: dispose reentrantly + Tx->>Tx: deactivate, teardown waits for publication + Tx-->>Listener: disposal request accepted + Listener-->>Registries: return + Registries-->>Tx: announcement unwound + Tx->>Tx: resolve publication settlement + Tx->>Driver: stop and drain + Tx->>Registries: detach agent, then session + Tx->>Tx: dispose scope and resolve teardown +``` + +### 拆除在撤销注册之前保留工作 + +每个拆除请求加入一条记忆化路径。顺序为: + +1. 停用创建或驱动,让同步发布完成。 +2. 停止并排空 driver,包括空闲注入刷新。 +3. 分离 agent。 +4. 分离会话。 +5. Dispose agent 作用域。 +6. 退役事务所有权追踪。 + +此顺序让最终的 agent 和会话事件能使用匹配的作用域监听器,并使持久化观察者在最终刷新完成前保持附加。作用域 dispose 放在最后,因为注册撤销是外部可见的生命期边界。 + +## 会话追加:物化、验证、提交、通知 + +会话事件跨越持久化边界,因此追加操作拥有其数据。算法的其余部分使用一条已附加的注册表条目和一个提交点。 + +### 持久化数据一次性物化 + +Session 头部、种子和追加的事件是无损 JSON 数据。Session 构造函数或追加路径在存储前物化并验证它们,并暴露冻结的快照,因此后续调用方的修改无法改变持久化、回放或模型重建。 + +这是一个真实的所有权边界:值离开调用方,可能被持久化,且必须在之后重建相同的请求。这比类型化的同进程回调或注册表定义有意更严格。 + +### 提交前监听器可以否决;提交后观察者不能 + +追加遵循一个序列: + +1. 物化持久化事件和表面意图。 +2. 取得 SessionEntry 的独占所有权,并拒绝该注册表条目上的重入追加。 +3. 解析作用域回调并运行内部不变式验证。 +4. 恰好推送一次;这是提交点。 +5. 逐个通知每个观察者,隔离同步和异步失败。 +6. 释放追加状态并兑现发布期间请求的 detach。 + +没有观察者错误能让已提交的事件看起来未提交,一个坏的监听器也无法饿死后续监听器。Session 不变式在提交前暂存其转换,仅当同一事件到达被隔离的提交后观察者时才应用。 + +`flush()` 启动每个持久化监听器并等待所有结果后再报告失败。这种有意的 all-settled 行为防止同步失败饿死另一个后端或最终刷新。 + +## 信任边界:仅在所有权真正变更时复制 + +运行时区分类型化的进程内契约与序列化及持久化边界。这是值和回调的主要简化规则。 + +| 边界 | 所有权规则 | +|---|---| +| 同进程内的类型化服务/插件调用 | 借用 readonly 值和回调 | +| 解析的插件配置或外部文件 | 验证语义和结构输入 | +| 队列中的收件箱消息 | 在异步消费前物化 | +| 模型/工具 JSON 输入或输出 | 在模型/工具边界处物化 | +| 持久化会话或持久化数据 | 在提交前物化并验证 | +| Worker、进程或协议格式消息 | 序列化、验证并拥有解码后的值 | + +测试中构造恶意 getter、在交接后替换类型化回调、或强制转换伪造服务对象的做法本身不定义生产契约。运行时在数据跨越解析器、队列、模型、持久化、文件、worker、进程或协议格式(wire format)边界时保留检查,并在可信进程内依赖 readonly 类型加插件纪律。 + +回调隔离与数据所有权是分开的。监听器是任意扩展代码,即使其参数是可信的也可能抛出异常;发布和提交后路径仍按其事件契约隔离失败。 + +## 工具与提示词:单一视图、权威组装、已提交的结果 + +工具展示和执行共享一个私有解析器。提示词组装仍然是可信的协作式组合:注册表提供有序输入,assembly waterfall 的返回值就是 agent loop(智能体循环)记录和发送的内容。执行仅在策略或结果结算必须单调时才使用独立的单向边界。 + +### 一个解析器定义工具视图 + +私有解析器应用当前展示模式、活跃的全局限制、精确的局部叠加和局部遮蔽。Schema、查找、执行、Code Mode SDK 生成和限制验证都使用该解析器或其限制前的全局名称视图。 + +[subagent 组合控制 Agent Note](../feature/2026-07-12-subagent-persona-tool-filter-and-depth.md#tool-filtering-is-one-live-global-view-rule)拥有用户可见的 allow/deny 语义。实现要求是一致性:被过滤掉的全局工具不能通过另一条查找路径仍可执行,局部遮蔽的定义就是被展示和执行的同一个定义。 + +`ToolRestriction` 接受 readonly 的 allow/deny 名称并将其编译为内部集合。多个限制取交集。公开的 `visible()` 和 `knownNames()` 方法是不必要的,因为只有注册表需要中间视图。 + +### 工具执行拥有标识和边界物化 + +注册表为每次执行分配一个新的带品牌的 `Symbol` token。嵌套的 Code Mode 调用将外层 token 作为 `parent` 携带,因此结构化输出可以通过标识将内层捕获与其外层 `run_code` 结果关联。 + +注册表分配的新 Symbol 提供无碰撞的执行标识,无需 WeakSet 成员注册表。调用方无法通过 `ToolExecutionInput` 提供执行自身的 token;它们仅在注册表创建后接收流水线拥有的 `ToolExecution`。这是一个可信的类型化契约,而非针对任意强制转换或 JavaScript 调用方的运行时防御。 + +参数在模型/工具 JSON 进入流水线时一次性物化。Pre-、around- 和 post-execute 监听器操作类型化的 execution 和决策。Call ID 关联、审批、单调守卫和 Code Mode 嵌套仍然是显式的关系检查。 + +在 post-execute 或外层流水线完成规范化后,注册表先为候选结果创建无损快照,并将快照失败转为普通错误;随后调用在本次调用创建时已快照的可选 `ToolDefinition.finalizeContent` 回调,最后一次性物化并冻结被接受的最终结果。该回调只能替换内容,因此即使工具强制最后一道结果上限,结构化错误标识、上下文与元数据仍由注册表拥有。每个同步的 `tools/result` 观察者接收该确切的已提交对象,观察者失败被逐个隔离。外层流水线失败或候选快照失败会在最终内容处理之前被规范化,因此观察者可以丢弃针对同一权威边界的暂存工作。 + +### Assembly waterfall 拥有最终的模型可见组合 + +SystemPrompt 首先将全局加 agent 的段、变量和工具提供方解析为确定性的注册表贡献。作用域过滤的 `system-prompt/assemble` waterfall 随后可以重排、替换、添加或移除任何段、变量或 schema。其返回的组装结果即为权威;没有后续的恢复步骤,普通提示词段、工具定义或提供方结果上也没有终态元数据。 + +这是一个可信的同进程扩展 seam,而非权限边界。修改 Code Mode 的 `run_code` schema 或 `tools:sdk` 指令,或结构化子级的捕获 schema 或指令的监听器,有责任在其返回的组装中保持协议的一致性。ToolRegistry 仍然保留 `run_code` 不受普通工具注册和限制影响,因为那些是注册表不变式,但 assembly 中间件仍然可以自由变换最终的模型可见表面。 + +Scope 直接解决了真正的隔离问题。结构化输出贡献注册在子级的精确作用域中,而 Code Mode 从同一个已解析的工具视图派生其传输和 SDK。第二套命名保护系统需要另一套所有权和碰撞规则来覆盖任意 schema 提供方(包括有意贡献重复名称的提供方),却不创建新的信任边界。 + +### 结构化输出仅提交权威结果 + +结构化输出将子作用域组合与两阶段执行提交相结合。子级在发布前注册其 `structured_output` 工具和指令;可信的 assembly 监听器可以变换这些普通贡献,并有责任在期望子级完成时保持协议。工具体验证候选值并按当前 `ToolExecution` 暂存,但成功捕获仅由不可变的 `tools/result` 观察决定。 + +对于原生调用,观察者仅在该确切执行的最终结果成功时才删除暂存并提交其值。因此 post-execute 阻止或外层流水线失败不会留下已捕获的值。 + +对于 Code Mode SDK 调用,内层成功结果记录 `{ parentToken, value }` 而非提交。观察者等待 token 匹配 `parentToken` 的 `run_code` 执行,仅在该外层最终结果也成功时才提交。程序失败、运行时中止或外层 post-policy 拒绝会丢弃待定值。 + +一旦值处于待定或已提交状态,作用域单调守卫拒绝后续工具调用。提交后,普通串行的 `agent/turn-stop` 监听器在 continuation 和 steering(中途引导)已折叠之后返回停止决策。Schema 验证失败仍然是普通的 `INVALID_ARGS` 工具错误,子级可以在同一轮次内重试。 + +纯 Code Mode 的注册表贡献从原生 wire schema 中省略 `structured_output`,并通过生成的 SDK 暴露它。Assembly waterfall 可以有意改变该展示;执行仍然针对子作用域定义进行验证,监听器拥有其创建的任何替代模型可见路由的一致性。 + +### 三个执行边界有意设为单向 + +提示词组装有意是协作式的,但三个执行事实在其可扩展阶段之后需要单向结算: + +| 边界 | 最终权力 | 为何普通监听器顺序不够 | +|---|---|---| +| 工具 pre-policy | 单调拒绝 | 后续监听器不得重新允许已被拒绝的调用 | +| 工具结果 | 观察不可变的已提交结果 | 结构化输出必须仅提交实际逃出流水线的结果 | +| 轮次 continuation | 在普通 continuation 折叠之后停止 | 已提交的终端输出必须结束轮次 | + +`ToolGuard` 是单调策略注册表。已提交的工具观察是上述被隔离的 `tools/result` 点。终端结构化输出监听普通串行的 `agent/turn-stop` 折叠,在正常 continuation 和 steering 决策之后;类型化的监听器契约不需要公开的 `strictSerial()` dispatcher。 + +### Skill 和 approval 服务信任类型化调用方 + +Skill 注册表定义和 approval 策略是 readonly 的同进程契约。它们的服务不克隆回调对象,也不防御交接后的回调替换。 + +Skill 仍然验证外部 skill 文件和解析的提供方输出,通过调用 agent 的工具视图路由目录,并精确 dispose 注册。Approval 仍然解析策略、观察取消、按 `request.agent` 路由 `approval/request`、记录持久化审计对,并隔离应答者和提交后观察者的失败。 + +## Subagent:就绪即 start promise + +Subagent 启动有一次所有权转移。提供方拥有部分资源直到其 start promise 以一个就绪的已发布 run 兑现;调用方拥有返回的 run 并必须 dispose 它。 + +### 服务契约有一个取消通道 + +`SubagentProvider.start()` 和 `SubagentService.start()` 返回 `Promise<SubagentRun>`。Promise 仅在后端建立了它所承诺的子级之后才兑现,因此调用方和 `subagent/start` 观察者从不需要第二个 `run.started` 就绪 promise。 + +`SubagentStartRequest.signal` 是必需的。中止它会在启动期间和就绪之后请求取消。`SubagentRun.dispose()` 也请求取消并等待完全停稳。没有单独的公开 `run.cancel()` 通道。 + +可选的 `sendMessage()` 支持能接受 steering 的活跃后端。可选的 `resume()` 返回 `Promise<SubagentRun>`,因为恢复的子级有相同的异步就绪边界。 + +服务在调用提供方之前验证提供方能力和请求语义。提供方拒绝在拒绝逃出之前清理所有部分资源,且不发射 `subagent/start`/`subagent/end` 对。兑现之后,服务附加结果观察、发射作用域 start 并返回 run。提供方移除阻止后续 start,但不撤销提供方已接受的 run。 + +### 进程内提供方复用核心事务 + +Spawn 和 fork 共享一个进程内 driver。它通过 `parent.ctx` 创建子级,将必需的 signal 传入核心创建事务,并在未发布的 setup 期间安装 persona、工具限制和结构化输出贡献。 + +提供方等待创建并仅返回已发布的 run。在交接时,核心创建分离其仅用于创建的 abort 监听器;提供方在安装活跃 run 监听器之前立即重新检查 signal,因此在那个窄窗口中的 abort 会 dispose 新句柄而非逃脱取消。父级拆除跟随子级,因为操作属于 `parent.ctx`;提供方卸载阻止新 start 但不成为已接受 run 的第二个撤销所有者。Run disposer 取消子级并等待 AgentHandle 的有序拆除。 + +Spawn 使用空会话种子。Fork 使用经验证的已完成轮次前缀。对话种子仅改变历史,不导入作用域、工具、服务或权限。 + +### ACP 提供方拥有进程直到就绪或清理 + +ACP 提供方跨越真实的进程和协议格式边界,因此它保留验证、环境清洗、消息序列化、abort/进程竞争,以及从 kill 到进程退出并完全停稳的过程。 + +Start 仅在 `initialize` 和 `newSession` 成功后才 resolve。Abort、spawn 失败、RPC 失败或无效启动响应在拒绝前回收进程。就绪后,result 映射 ACP 提示词结果和流式输出;dispose 请求取消、关闭连接并通过一条记忆化路径等待进程退出。 + +## 工作流与 ACP 进程:仅保留独立的异步事实 + +Worker 和子进程桥接比同进程注册表需要更多状态,因为消息、进程死亡和清理可以独立结算。它们的状态围绕这些真实事实组织,而非重复的取消协议。 + +### 工作流子级是待定 start 或已发布记录 + +工作流宿主保持待定的提供方 start promise 和已发布的子级记录。子级仅在异步 `SubagentService.start()` 兑现时才从待定变为已发布;被拒绝的 start 清理其部分提供方工作且不产生子级生命周期对。 + +一个宿主拥有的 AbortController 向待定和活跃子级提供必需的 signal。关闭工作流准入中止该 signal,因此没有重复的 `ChildCancel` worker RPC 或显式的宿主侧 `run.cancel()` 扇出。完全停稳需要等待待定 start 和已发布子级 dispose 两者。 + +Worker 边界仍然序列化请求和结果。宿主保留首个终端结果仲裁、精确的子级计数、worker 死亡处理、优雅终止、迟到/重复消息拒绝和有界清理,因为结果接收、worker 退出和子级完全停稳是真正独立的事实。 + +### 终端结果与物理清理保持分离 + +工作流结果按公开优先级规则记录首个被接受的终端结果。该结果选定后清理可以继续:活跃子级仍需 dispose,worker 仍需终止,慢速外部后端可能超出配置的优雅期限。 + +公开 dispose 在调用回调之前取得其记忆化 promise 的所有权。Worker 死亡在处理任何排队的迟到子级请求之前关闭准入,合成缺失的生命周期结束,并启动子级/进程清理而不重写已声明的结果。 + +### ACP 提示词结算不依赖更新投递 + +[仅面向自动化的 ACP 桥接层](../simplification/2026-07-23-acp-automation-only-protocol.md)直接将一个进行中的提示词与其观察到的用户消息轮次关联。它不从日志水位线扫描,也不使用会话状态作为第二个调和预言机。 + +即使已提交消息的更新无法送达客户端,会话事件监听器也会从匹配的 `turn/end` 结算关联。因此更新投递不能让会话永久处于进行中状态。ACP 创建由服务器分配 id 的全新会话,并拥有由此产生的每个 agent 句柄,直到连接拆除。 + +## 正确性强制 + +该设计通过类型、运行时逃逸点、生成的契约和行为测试来强制执行。没有哪一层被要求证明它无法观察到的东西。 + +### 类型使常规路径难以误用 + +Readonly 契约描述借用的同进程值。`Scoped<T>` 标记事件接收器,`agentEvents()` 融合载体和主体,工具输入省略注册表拥有的 token,subagent 异步返回类型直接暴露就绪性。 + +TypeScript 无法管控 JavaScript 强制转换、直接 Cordis dispatch、进程消息或持久化文件,因此运行时强制保留在这些逃逸点。 + +### 运行时不变式覆盖跨服务事实 + +`dsh-scope/invariant` 配套插件在被选用时验证每个声明的作用域事件使用带标记的载体,以及暴露主体的事件族使用匹配的键。独立的 `dsh-session/invariant` 贡献在追加提交前暂存 trace 验证,并在同一事件提交后推进;二者都通过 `ctx.invariants` 注册。 + +该插件不通过扫描注册表来管控可信 setup,也不拒绝通过强制转换构造的提示词 assembly 对象。这些检查会将组合契约变成推测性的运行时机制,却不保护真实的外部边界。 + +### 生成的产物使公开契约保持对齐 + +事件目录、服务目录、生产者/消费方矩阵、配置目录、模块图、工具目录、type-equiv 块和作用域事件解析器映射都是从源码生成或受新鲜度门禁约束的。[TypeScript 语义门禁 Agent Note](../process/2026-07-14-typescript-program-backed-semantic-gates.md)拥有 Program 构造、语义事件发现和解析器生成规则。 + +行为测试固定了作用域路由和 dispose、最终写入注册表时的碰撞清理、发布回滚、有序完全停稳、持久化前/后提交行为、跨展示和执行的活跃工具过滤、协作式提示词组装、原生和 Code Mode 中的结构化输出提交、异步 subagent 启动和信号取消、worker 终端仲裁、ACP 结算和进程拆除。 + +## 曾考虑的替代方案 + +[7 月 8 日 Agent Note](2026-07-08-agent-scope-contexts.md#alternatives-considered)拥有公开扁平作用域契约的替代方案。此处的替代方案关注实现形态。 + +### 使用透明代理作为作用域载体 + +模拟主体的代理必须保持属性、可调用、可构造、私有字段、描述符和代理不变式行为,而监听器路由从不需要这些。一个小型不透明载体保持过滤器和键,而显式事件参数携带主体。 + +### 在 setup 前预留 agent 和会话 ID + +预留防止重复的私有 setup 工作,但需要跨服务能力、释放排序、废弃预留清理和已准备对象绑定。ID 由调用方提供,并发复用是调用方错误;最终写入注册表时可以选择赢家,而失败的事务干净地回滚。 + +### 对每个类型化的同进程参数做快照 + +通用复制防御有状态 getter 和违反 readonly 契约的调用方,但增加分配、重复验证器和可能遗忘复制的路径。物化属于解析器、队列、模型、持久化、worker、进程和协议格式边界——即所有权真正变更的地方。 + +### 为就绪、取消和 dispose 提供独立控制器 + +并行哨兵可能都镜像一个操作是否活跃。一个事务或 start promise 拥有操作;独立 promise 仅在发布展开、外部工作、终端结果和物理层面的完全停稳可以独立结算时才保留。 + +### 保留同步 subagent start 加 `run.started` + +这将提供方接受与就绪分离,迫使每个消费方注册部分 run、附加结果观察、等待就绪并清理就绪失败。异步 start promise 使提供方到调用方的所有权转移本身成为就绪边界。 + +### 在 assembly 之后恢复选定的提示词或工具贡献 + +Waterfall 之后的恢复步骤会在文档化的协作式 seam 之后创建第二套组合规则。正确分配规范的存在或缺失还需要为任意工具 schema 提供方制定所有权和碰撞规则,而这些提供方的普通输出可能包含重复名称。作用域注册已经提供了所需的按 agent 隔离,可信的 assembly 监听器拥有其返回内容的协议一致性,因此命名恢复增加了机制却不建立独立边界。 + +### 用同进程加固替代 worker/进程生命周期守卫 + +Worker 消息、进程死亡和持久化输入确实跨越所有权和序列化边界。首个结果仲裁、验证、环境清洗和使进程完全停稳的清理即使在敌对的同进程回调机制不存在时仍然必要。 + +## 后果 + +实现更小,其证明与所有权图具有相同的形状。一个键选择一层,一条注册表条目拥有一个活跃注册表对象,一个事务拥有创建,一个解析器拥有工具视图,一个异步 promise 转移 subagent 所有权。 + +### 设计保证的内容 + +- 作用域贡献仅在其精确的 agent 视图中可见,并随该作用域一起 dispose。 +- 创建和恢复不暴露部分配置的句柄;最终写入注册表时的失败者和发布失败清理每个已准备的资源。 +- Dispose 在 driver 排空和最终会话工作期间保留作用域监听器和持久化,然后撤销作用域。 +- 持久化、队列、模型、worker、进程和协议格式的值在其真实边界处被拥有;类型化的同进程值遵循 readonly 契约。 +- ToolRegistry 的展示、查找和执行在专家 assembly 变换之前解析相同的活跃视图,已提交的结果有一个不可变的观察点。 +- 注册表贡献是确定性输入,而可信的 assembly waterfall 拥有最终的模型可见组合。 +- Subagent start 仅返回就绪的 run,必需的 signal 取消待定或活跃的工作,dispose 到达后端的完全停稳契约。 +- Worker/进程结果优先级和清理在死亡、迟到消息和有界拆除下保持正确。 + +### 代价与局限 + +作用域感知服务仍然维护全局和按标识键索引的映射,操作必须显式携带其真实 agent。异步创建/恢复和 subagent start 要求调用方等待所有权转移并 dispose 返回的句柄。 + +可信的 `system-prompt/assemble` 监听器可以移除或替换 Code Mode 和结构化输出协议片段。这是有意为之:监听器拥有最终组合,必须保持部署期望仍可用的任何协议。 + +该设计信任同进程中的类型化插件。它不防御任意强制转换、有状态 getter、违反 readonly 契约的修改,或插件有意在支持的组合 API 之外使用环境服务访问。 + +[安全与权限非目标](2026-07-08-agent-scope-contexts.md#security-and-authority-are-non-goals)仍然是根本性的。这些机制证明注册组合、发布和生命期所有权;它们不证明隔离或父到子的非升权。 diff --git a/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.i18n.yaml index b49506364b..46f0a1cd41 100644 --- a/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.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 -2026-07-12-scoped-layers-store.md: b850b6bcbb22401b386b4458b6d5c65a160c85cd -2026-07-12-scoped-layers-store.zh.md: 8bfc0a0e8ec1e3de624ff8d9e48b7517833fc025 +2026-07-12-scoped-layers-store.md: c5186d1652bca617eed62ec02937f2d055ea727c +2026-07-12-scoped-layers-store.zh.md: 3183811be553428ebcd8f59f15989c44d458b477 diff --git a/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.md b/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.md index b850b6bcbb..c5186d1652 100644 --- a/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.md +++ b/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.md @@ -123,4 +123,4 @@ All seven facades keep validation and diagnostics in their owning registry and c - `dsh-scope` unit tests cover global construction, lazy scoped construction, non-creating reads, named merge order and shadowing, aggregate reclamation, factory and action failure cleanup, notification ordering and rollback, `notify: false`, effect labels, exact disposer identity, idempotent teardown, caller-owned duplicate errors, independent anonymous duplicates, live iterators, and drained-generation detachment. - Focused tool, system-prompt, and command suites cover restrictions, reserved transport handling, known/restrictable-name agreement, guard re-entrancy and self-replacement, validation order, exact diagnostics, section shadow-before-evaluate, provider snapshot membership, variable re-entrancy and self-replacement, contained command observers, frozen and sorted views, direct execution, and lifecycle disposal. - The scoped core-data type-equivalence check ties `ScopeLayer` documentation to its source declaration. Repository documentation, module-graph, build, hygiene, coverage, and built-artifact gates exercise the root export and package boundary. -- Existing ACP, headless, and TUI keyless snapshots remain the regression boundary for tool schemas, prompt assembly, and human commands. The implementation does not update any expected transcript. +- Existing ACP, headless, and TUI keyless snapshots remain the regression boundary for tool schemas and prompt assembly; TUI coverage owns human commands. The implementation does not update any expected transcript. diff --git a/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.zh.md b/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.zh.md index 8bfc0a0e8e..3183811be5 100644 --- a/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.zh.md @@ -123,4 +123,4 @@ export class AnonymousEntries<V> { - `dsh-scope` 单元测试覆盖全局构造、专属层延迟构造、非创建式读取、命名合并顺序与遮蔽、聚合回收、工厂与 action 失败清理、通知顺序与回滚、`notify: false`、effect 标签、原始 disposer 身份、幂等拆除、调用方提供的重名错误、相同匿名值的独立登记、活迭代器,以及表清空后的 generation 脱离。 - 工具、系统提示词和命令专项测试套件覆盖 restriction、保留传输处理、已知名称与可限制名称的一致性、guard 重入与自我替换、校验顺序、精确诊断、section 先遮蔽再求值、提供方快照成员关系、variable 重入与自我替换、隔离失败的命令观察者、冻结且有序的视图、直接执行和生命周期销毁。 - 作用域核心数据的类型等价性检查将 `ScopeLayer` 文档与其源声明绑定。仓库级的文档、模块图、构建、hygiene、覆盖率与构建产物门禁会覆盖包根导出与包边界。 -- 现有 ACP(Agent Client Protocol)、headless 和 TUI 无密钥快照继续作为工具 schema、提示词组装和人类命令的回归边界。实现不会更新任何预期 transcript(文本记录)。 +- 现有 ACP(Agent Client Protocol)、headless 和 TUI 无密钥快照继续作为工具 schema 与提示词组装的回归边界;人类命令由 TUI 覆盖。实现不会更新任何预期 transcript(文本记录)。 diff --git a/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.i18n.yaml index e83cfff95e..52ec59ccbf 100644 --- a/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.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 -2026-07-15-llm-model-catalog-and-acp-selection.md: 6cc8afc6c7431fbf3eb29fc358b432db4f72b529 -2026-07-15-llm-model-catalog-and-acp-selection.zh.md: 1cce7a58d0ec83dc01feaf72ccb61d294a78ddd5 +2026-07-15-llm-model-catalog-and-acp-selection.md: adbd8671f0ea5cd2e0c049c32616453882329396 +2026-07-15-llm-model-catalog-and-acp-selection.zh.md: dfcb581e43149281cd18b28f1411ea98944983ad diff --git a/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md b/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md index 6cc8afc6c7..adbd8671f0 100644 --- a/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md +++ b/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md @@ -4,6 +4,8 @@ Status: implemented English | [中文](2026-07-15-llm-model-catalog-and-acp-selection.zh.md) +> The catalog decision remains current. Per-session ACP model selection is superseded by [ACP as an automation-only protocol](../simplification/2026-07-23-acp-automation-only-protocol.md). + ## Problem Provider-routed adapters let every request choose `provider + model`, but `LlmService` exposed only routing and streaming. A UI could not discover which providers were registered or which models an adapter was prepared to recommend. ACP clients therefore received no `model` session config option, so Zed, JetBrains, and VS Code integrations had no model list even though the request seam already supported runtime switching. @@ -24,21 +26,17 @@ Catalog membership is advisory. It drives selectors and diagnostics but never ch `dsh-llm-pi-ai` maps the configured provider's installed `getModels(provider)` entries into the neutral catalog. Its existing request-time catalog lookup remains authoritative and still rejects unknown models with `UNKNOWN_MODEL`. `dsh-llm-deepseek` accepts an optional `models` config containing display entries, defaulting to `deepseek-v4-flash` and `deepseek-v4-pro`. An explicit list replaces those defaults and an empty list disables discovery. The entries improve selector UX for known public or private models, while every unlisted model id continues to pass through unchanged. -### ACP session config option +### Per-session selection in the front door -The ACP bridge advertises one select with `id: model` and `category: model` in `session/new` and `session/load` when the session has a complete target whose provider is registered. Each opaque option value encodes the full provider/model pair. Models are grouped by provider when multiple non-empty provider groups exist; a single group is flattened for clients that render simple selects better. +A selection is owned by the front door that offers it (today the TUI `/model` selector), never by `LlmService` or `AgentOptions`: those are deployment-wide or creation-wide objects, and mutating them would couple concurrent sessions. Each opaque choice carries the full provider/model pair, because the same model id may appear under multiple routes. -The session's current target is added to the displayed options when its adapter omits it. This preserves custom DeepSeek and private-endpoint models while keeping the adapter catalog advisory. A target with an unregistered provider is not advertised, and a model-less agent remains available to another `agent/request` supplier. - -`session/set_config_option` accepts only values from the current catalog snapshot and updates a target reference owned by that ACP session. No global `LlmService` or `AgentOptions` state changes, so concurrent sessions may select different providers and models. The existing permission select remains independent, and every response returns the complete refreshed option state. +The ACP automation transport is not a catalog consumer. Its deployment config supplies one optional provider/model target for newly created agents, and it advertises no model selector or configuration-option interface. ### Prompt/request consistency and durability -Agent setup installs scoped `system-prompt/assemble` and `agent/request` listeners. Prompt assembly snapshots the selected pair once per step, overwrites the assembled `provider` and `model` variables after downstream prompt listeners, and the request listener applies that same snapshot after downstream request listeners. A selection during asynchronous assembly therefore starts on the next step rather than splitting prompt text from routing. Other call-config fields remain untouched. +`installAgentLlmTarget` (in `dsh-agent`) installs scoped `system-prompt/assemble` and `agent/request` listeners for a front-door-owned target. Prompt assembly snapshots the selected pair once per step, overwrites the assembled `provider` and `model` variables after downstream prompt listeners, and the request listener applies that same snapshot after downstream request listeners. A selection during asynchronous assembly therefore starts on the next step rather than splitting prompt text from routing. Other call-config fields remain untouched. -The request header remains the durable source of truth. When a selected target is actually used, the existing full `request/header` snapshot records it. `session/load` initializes the ACP selection from the folded last request header before falling back to bridge config. A selection that is never used by a request is intentionally in-memory only because it never became model-visible state. - -ACP's experimental `providers/*` capability is not used. That draft surface configures provider base URLs, protocols, and headers, including secrets; it does not enumerate models and would give the UI authority to rewrite deployment-owned adapter configuration. +The request header remains the durable source of truth. When a selected target is actually used, the existing full `request/header` snapshot records it, and a front door initializes its selection from the folded last request header before falling back to creation options. A selection that is never used by a request is intentionally in-memory only because it never became model-visible state. ## Alternatives considered @@ -46,21 +44,19 @@ ACP's experimental `providers/*` capability is not used. That draft surface conf **Make catalogs mandatory whitelists.** This conflicts with the hand-written adapter's arbitrary model pass-through and private deployments. The selected adapter already owns authoritative request validation. -**Store selection in `AgentOptions` or `LlmService`.** Those are creation-wide or deployment-wide objects. Mutating them would couple concurrent ACP sessions and bypass the logged `agent/request` replacement path. +**Store selection in `AgentOptions` or `LlmService`.** Those are creation-wide or deployment-wide objects. Mutating them would couple concurrent sessions and bypass the logged `agent/request` replacement path. **Persist a new model-selection session event immediately.** An unused UI selection has not affected a model request. Recording the existing request header when the target is consumed preserves the model-visible-if-and-only-if-logged rule without adding a second source of truth. -**Use ACP `providers/*`.** That unstable API changes endpoint and authentication configuration rather than selecting a model for one session, and its lifecycle and secret-handling semantics do not match this feature. - ## Consequences - Any adapter can expose a dynamic model list without leaking provider-library types into the core seam. - Catalog consumers must treat absence as “not advertised,” never “invalid request.” -- pi-ai-backed ACP deployments automatically inherit the installed pi-ai provider catalogs; hand-written DeepSeek deployments list known choices explicitly and retain arbitrary model support. -- ACP clients receive a standard stable model config option, with provider-aware values and per-session isolation. +- pi-ai adapters expose their installed provider catalogs; hand-written DeepSeek deployments list known choices explicitly and retain arbitrary model support. +- Human-facing catalog consumers own their selection interaction. ACP uses its fixed deployment target and does not widen the protocol with model discovery. - Request headers remain compatible with the provider-routed session shape; no new JSONL event or format version is required. -- A catalog read can be asynchronous. ACP reads a detached snapshot before creating or resuming an agent, so discovery failure cannot leave a partially published session. +- A catalog read can be asynchronous, and every caller receives detached values. ## Testing -Unit coverage validates catalog detachment and malformed metadata, pi-ai and DeepSeek catalog projection, ACP provider grouping, custom-current insertion, invalid values, provider/model request routing, prompt-variable alignment, concurrent-session isolation, model-less fallback, and load restoration from the request header. The existing ACP transport suites verify that the additional config option does not change prompt, cancellation, replay, approval, or tool-rendering behavior. +Unit coverage validates catalog detachment and malformed metadata, pi-ai and DeepSeek catalog projection, provider/model request routing, and prompt-variable alignment; per-agent isolation follows from installing the listeners on the agent-scoped context. ACP transport tests validate fixed provider/model forwarding independently of catalog discovery; the TUI suite covers selector interaction and header-based restoration. diff --git a/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.zh.md b/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.zh.md index 1cce7a58d0..dfcb581e43 100644 --- a/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.zh.md @@ -4,6 +4,8 @@ Status: implemented [English](2026-07-15-llm-model-catalog-and-acp-selection.md) | 中文 +> 目录决策仍然有效。ACP 会话级模型选择已由 [ACP 作为仅面向自动化的协议](../simplification/2026-07-23-acp-automation-only-protocol.md)取代。 + ## 问题 基于提供方路由的适配器允许每次请求选择 `provider + model`,但 `LlmService` 只暴露路由和流式调用。UI 无法发现已注册的提供方,也无法知道适配器愿意推荐哪些模型。因此,ACP 客户端收不到 `model` 会话配置项;即使请求接缝已经支持运行时切换,Zed、JetBrains 和 VS Code 集成仍没有模型列表。 @@ -14,9 +16,9 @@ ACP 选择还必须保留提供方维度。同一个模型 ID 可能存在于多 ## 决策 -### 提供方中立的建议性发现 +### 提供方无关的建议性发现 -`LlmAdapter` 增加 `providerInfo(provider)` 与异步 `listModels(provider)` 方法。其提供方中立结果分别为 `LlmProviderInfo { id, name }` 和 `LlmModelInfo { provider, id, name, description? }`。默认实现以路由名称作为提供方名称,并且不展示模型,从而保持现有适配器行为。 +`LlmAdapter` 增加 `providerInfo(provider)` 与异步 `listModels(provider)` 方法。其提供方无关结果分别为 `LlmProviderInfo { id, name }` 和 `LlmModelInfo { provider, id, name, description? }`。默认实现以路由名称作为提供方名称,并且不展示模型,从而保持现有适配器行为。 `LlmService.listProviders()` 按注册顺序返回分离后的元数据。`LlmService.listModels(provider)` 委托给路由所有者,校验非空 ID 和名称,并在提供方不匹配或模型 ID 重复时以 `INVALID_CATALOG` 失败,最后返回分离后的值。未知提供方仍以 `NO_ADAPTER` 失败。提供方元数据在 `registerAdapter()` 期间进行原子校验,错误展示记录不会留下部分注册。 @@ -24,43 +26,37 @@ ACP 选择还必须保留提供方维度。同一个模型 ID 可能存在于多 `dsh-llm-pi-ai` 将已配置提供方的安装目录 `getModels(provider)` 映射为中立目录。其现有请求时目录查询仍是权威依据,未知模型仍以 `UNKNOWN_MODEL` 失败。`dsh-llm-deepseek` 接受可选的 `models` 配置作为展示条目,默认包含 `deepseek-v4-flash` 和 `deepseek-v4-pro`。显式列表会替换这些默认值,空列表则关闭发现。这些条目改善已知公开或私有模型的选择体验,而所有未列出的模型 ID 仍会原样透传。 -### ACP 会话配置项 +### 前门内的会话级选择 -当会话具有完整目标且目标提供方已注册时,ACP bridge 会在 `session/new` 与 `session/load` 中展示一个 `id: model`、`category: model` 的选择项。每个不透明选项值都编码完整的提供方/模型字段组合。存在多个非空提供方分组时按提供方分组;只有一个分组时将其展开,以便对简单选择器支持更好的客户端展示。 +选择由提供它的前门拥有(今天是 TUI 的 `/model` 选择器),而不由 `LlmService` 或 `AgentOptions` 拥有:它们是部署级或创建级对象,改动它们会把并发会话耦合在一起。每个不透明选项都携带完整的提供方/模型对,因为同一模型 ID 可能出现在多个路由下。 -如果适配器目录未包含会话当前目标,该目标仍会加入展示选项。这能保留自定义 DeepSeek 与私有端点模型,同时维持目录的建议性。提供方未注册的目标不会展示;缺少模型的 agent 仍可由其他 `agent/request` 提供者补齐。 +ACP 自动化传输层不是目录消费方。它通过部署配置为新创建的 agent 提供一个可选的提供方/模型目标,不展示模型选择器或配置选项接口。 -`session/set_config_option` 只接受当前目录快照中的值,并更新该 ACP 会话独占的目标引用。它不会修改全局 `LlmService` 或 `AgentOptions` 状态,因此并发会话可以选择不同的提供方和模型。现有权限选择项保持独立,每次响应都返回完整的刷新后配置项状态。 +### Prompt/请求一致性与持久化 -### Prompt/请求一致性与持久化 +`installAgentLlmTarget`(位于 `dsh-agent`)为前门拥有的目标安装 agent 作用域的 `system-prompt/assemble` 与 `agent/request` 监听器。Prompt 组装在每个 step 对所选组合做一次快照,在下游 prompt 监听器之后覆写组装出的 `provider` 与 `model` 变量;请求监听器在下游请求监听器之后应用同一快照。因此,发生在异步组装期间的选择会从下一个 step 生效,而不会让 prompt 文本与路由分裂。其他调用配置字段保持不变。 -Agent setup 会安装作用域内的 `system-prompt/assemble` 与 `agent/request` 监听器。Prompt 组装为每个 step 只快照一次选中的字段组合,在下游 prompt 监听器完成后覆盖组装结果中的 `provider` 与 `model` 变量;请求监听器则在下游请求监听器完成后应用同一个快照。因此,异步组装期间发生的选择会从下一个 step 生效,不会导致 prompt 文本与路由分裂。其他调用配置字段保持不变。 - -请求头仍是持久化事实来源。当选中目标被实际使用时,现有的完整 `request/header` 快照会记录它。`session/load` 先从折叠后的最后请求头初始化 ACP 选择,再回退到 bridge 配置。一个从未被请求使用的选择只保留在内存中,因为它从未成为模型可见状态。 - -本功能不使用 ACP 的实验性 `providers/*` 能力。该草案接口配置提供方 base URL、协议和 headers,其中可能包含密钥;它不枚举模型,并且会赋予 UI 改写部署所有的适配器配置的权力。 +请求头仍是持久化的事实来源。当所选目标真正被使用时,现有的完整 `request/header` 快照会记录它;前门先从折叠后的最后一个请求头初始化其选择,然后才回退到创建选项。从未被请求使用的选择有意只保留在内存中,因为它从未成为模型可见状态。 ## 考虑过的替代方案 -**只返回模型字符串。** 仅模型值会丢失提供方路由;两个提供方暴露相同 ID 时立刻产生歧义。 +**只返回模型字符串。** 只有模型的值会丢失提供方路由,一旦两个提供方暴露相同 ID 就会产生歧义。 **将目录设为强制白名单。** 这与手写适配器的任意模型透传和私有部署冲突。请求的权威校验本就属于被选中的适配器。 -**将选择存入 `AgentOptions` 或 `LlmService`。** 这些对象分别面向创建过程或整个部署。修改它们会耦合并发 ACP 会话,并绕开带日志归因的 `agent/request` 替换路径。 +**把选择存进 `AgentOptions` 或 `LlmService`。** 它们是创建级或部署级对象。改动它们会把并发会话耦合在一起,并绕过有日志记录的 `agent/request` 替换路径。 -**立即写入新的模型选择会话事件。** 尚未使用的 UI 选择没有影响模型请求。目标被消费时记录现有请求头,既满足“模型可见当且仅当已记录”的规则,也不会引入第二个事实来源。 - -**使用 ACP `providers/*`。** 该不稳定 API 用于修改端点与认证配置,而不是为单个会话选择模型;其生命周期和密钥处理语义都不适合本功能。 +**立即持久化一个新的模型选择会话事件。** 未被使用的 UI 选择尚未影响任何模型请求。在目标被消费时记录现有请求头,既保持“模型可见当且仅当有日志”的规则,又不会引入第二个事实来源。 ## 结果 - 任意适配器都能暴露动态模型列表,无需把提供方库类型泄漏到核心接缝。 - 目录消费者必须把缺失理解为“未展示”,而不是“请求无效”。 -- 基于 pi-ai 的 ACP 部署会自动继承已安装的 pi-ai 提供方目录;手写 DeepSeek 部署显式列出已知选项,同时保留任意模型能力。 -- ACP 客户端会收到稳定标准的模型配置项,其中的值保留提供方信息,并按会话隔离。 -- 请求头继续使用基于提供方路由的会话结构;不需要增加 JSONL 事件或格式版本。 -- 目录读取可以是异步的。ACP 在创建或恢复 agent 前读取分离后的快照,因此发现失败不会留下部分发布的会话。 +- pi-ai 适配器会暴露其已安装的提供方目录;手写 DeepSeek 部署显式列出已知选项,同时保留对任意模型的支持。 +- 面向人类的目录消费方拥有各自的选择交互。ACP 使用固定部署目标,不会为模型发现扩大协议范围。 +- 请求头与基于提供方路由的会话形态保持兼容;不需要新的 JSONL 事件或格式版本。 +- 目录读取可以是异步的,且每个调用方都会收到分离后的值。 ## 测试 -单元测试覆盖目录分离与错误元数据、pi-ai 和 DeepSeek 目录投影、ACP 提供方分组、自定义当前模型补入、无效值、提供方/模型请求路由、prompt 变量一致性、并发会话隔离、无模型回退,以及从请求头恢复选择。现有 ACP 传输测试验证新增配置项不会改变 prompt、取消、回放、审批或工具展示行为。 +单元测试覆盖目录分离与错误元数据、pi-ai 和 DeepSeek 目录投影、提供方/模型请求路由,以及 prompt 变量对齐;按 agent 的隔离来自监听器安装在 agent 作用域上下文这一事实。ACP 传输测试独立验证固定提供方/模型的转发行为;TUI 套件覆盖选择器交互与基于请求头的恢复。 diff --git a/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.i18n.yaml index 70b98f0cf1..005f23b151 100644 --- a/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.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 -2026-07-15-lsp-capability-seam.md: 7265b04ac9b2f83764bdd13f07b2d3404c4c1708 -2026-07-15-lsp-capability-seam.zh.md: 10e8956005045d0934dd9dada5718b85a34cda3f +2026-07-15-lsp-capability-seam.md: d96b3a9c5139c1455a51f4fff793293d7b5a11c0 +2026-07-15-lsp-capability-seam.zh.md: 54dd32e46dded5722dda910e9138879d3f99de07 diff --git a/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.md index 7265b04ac9..d96b3a9c51 100644 --- a/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.md @@ -18,7 +18,7 @@ Add LSP as a three-package capability seam with one read-only model tool and one 1. `@deepseek-ai/dsh-lsp` at `packages/lsp/lsp` owns `ctx.lsp`, provider registration and selection, normalized requests/results, execution control, and structured LSP errors. 2. `@deepseek-ai/dsh-lsp-local` at `packages/lsp/lsp-local` adapts configured stdio language servers to the seam. One plugin instance accepts a named server table and registers one isolated provider for each command and extension-to-language-id mapping. -3. `@deepseek-ai/dsh-tool-lsp` at `packages/lsp/tool-lsp` owns the model-facing `lsp` schema, prompt guidance, argument validation, result limits and formatting, and ACP presentation. +3. `@deepseek-ai/dsh-tool-lsp` at `packages/lsp/tool-lsp` owns the model-facing `lsp` schema, prompt guidance, argument validation, result limits and formatting, and transport-neutral UI presentation. `dsh-lsp-local` is a generic host, not a language-server catalog or installer. Deployments explicitly configure commands and mappings; future presets belong in composition plugins or `cordis.yml` overlays. @@ -100,7 +100,7 @@ The tool requires `workspaceRoot` from session `header.cwd`, with no fallback; a Locations render as stable, file-grouped `path:line:character` entries. A `file:` URI accepted by Node `fileURLToPath()` becomes a relative path inside the workspace or an absolute path outside it; other URIs remain verbatim. `maxLocations` defaults to `100` and reports omitted items; `maxResultChars` defaults to `16_000` and bounds every complete rendered result, including its truncation metadata. Empty locations and `null` hover are successful no-result responses; missing or malformed server payloads fail with structured `LSP_MALFORMED_RESPONSE` errors. -ACP uses `{ card: 'generic', kind: 'search', title, locations: [{ path: file_path, line }] }` with an args-derived operation/cursor `title`. Because `FileLocation` has no character, follow-along focuses the input line while the title preserves the cursor; presentation remains pure. +The transport-neutral presenter uses `{ card: 'generic', kind: 'search', title, locations: [{ path: file_path, line }] }` with an args-derived operation/cursor `title`. Because `FileLocation` has no character, follow-along focuses the input line while the title preserves the cursor; presentation remains pure. ## Timeout ownership @@ -174,7 +174,7 @@ The local provider trusts its configured server and claims no sandbox confinemen ## Testing - Package tests pin the three-package dependency direction, runtime injections, and `ctx.lsp`-only communication. -- Tool tests pin the four operations, coordinate validation, configured bounds and omission markers, prompt, and ACP presentation. +- Tool tests pin the four operations, coordinate validation, configured bounds and omission markers, prompt, and UI presentation. - Registry tests pin atomic reservation/release, order-independent selection, and structured unavailable, disposed, conflict, and unsupported-operation errors. - Fake-stdio tests pin exact initialization capabilities, four protocol mappings, `Location`/`LocationLink` and hover normalization, and `findReferences` mapping to `references.includeDeclaration`. - Synchronization tests pin UTF-16 negotiation and conversion, supported and rejected `textDocumentSync` forms, blocked and failed open writes, balanced transient open/close, close-write failure, and malformed-response rejection. @@ -182,7 +182,7 @@ The local provider trusts its configured server and claims no sandbox confinemen - Lifecycle tests pin startup single-flight, complete-lifecycle serialization with fresh queued source reads, cross-workspace parallelism, abortable queues, crash replacement without replay, failed-stdin teardown, and quiescent disposal. - Host-filesystem tests pin session-cwd requirements, relative and absolute source containment through symlinks, document validation, file/non-file URI rendering, unformatted source, and no `fs/observed` event. - A keyless pinned TypeScript real-server e2e exercises all four operations; runnable configuration uses the same explicit provider mapping. -- Snapshots cover model-visible schema, prompt, results, omissions, and ACP rendering; a built-artifact smoke test covers framing and cleanup. +- Snapshots cover model-visible schema, prompt, results, and omissions; a built-artifact smoke test covers framing and cleanup. - Package and architecture docs cover configuration, security boundaries, and search/read guidance; the new `packages/lsp/` group is added to the AGENTS.md repository-layout block, the packages/README.md group table, and architecture.md in the same change. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.zh.md index 10e8956005..54dd32e46d 100644 --- a/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.zh.md @@ -18,7 +18,7 @@ harness 已具备文本搜索与文件读取能力,但二者都无法识别程 1. `packages/lsp/lsp` 下的 `@deepseek-ai/dsh-lsp` 负责 `ctx.lsp`、提供方注册与选择、标准化请求与结果、执行控制,以及结构化 LSP 错误。 2. `packages/lsp/lsp-local` 下的 `@deepseek-ai/dsh-lsp-local` 将配置的 stdio 语言服务器适配到该服务边界。一个插件实例接收具名服务器表,并为每组命令及扩展名到语言 id 的映射注册一个隔离的提供方。 -3. `packages/lsp/tool-lsp` 下的 `@deepseek-ai/dsh-tool-lsp` 负责面向模型的 `lsp` schema、提示词指导、参数校验、结果限制与格式化,以及 ACP(Agent Client Protocol)展示。 +3. `packages/lsp/tool-lsp` 下的 `@deepseek-ai/dsh-tool-lsp` 负责面向模型的 `lsp` schema、提示词指导、参数校验、结果限制与格式化,以及与传输方式无关的 UI 展示。 `dsh-lsp-local` 是通用 host,不是语言服务器目录或安装器。部署显式配置命令与映射;未来 preset 属于组合插件或 `cordis.yml` overlay。 @@ -100,7 +100,7 @@ interface LspToolInput { 位置按文件稳定分组并渲染为 `path:line:character`。Node `fileURLToPath()` 可接受的 `file:` URI 在工作区内转换为相对路径,在工作区外转换为绝对路径;其他 URI 保持原样。`maxLocations` 默认值为 `100`,并报告省略的条目;`maxResultChars` 默认值为 `16_000`,并限制每个完整渲染结果,其中包括截断元数据。空位置与 `null` hover 是成功的无结果响应;服务器载荷缺失或格式错误时,以结构化 `LSP_MALFORMED_RESPONSE` 错误失败。 -ACP 使用 `{ card: 'generic', kind: 'search', title, locations: [{ path: file_path, line }] }`,`title` 由参数推导并标明操作与光标。由于 `FileLocation` 没有 character,跟随位置聚焦输入行,标题保留完整光标;展示保持纯函数。 +与传输方式无关的展示器使用 `{ card: 'generic', kind: 'search', title, locations: [{ path: file_path, line }] }`,`title` 由参数推导并标明操作与光标。由于 `FileLocation` 没有 character,跟随位置聚焦输入行,标题保留完整光标;展示保持纯函数。 ## 超时归属 @@ -174,7 +174,7 @@ ACP 使用 `{ card: 'generic', kind: 'search', title, locations: [{ path: file_p ## 测试 - 包测试固定三个包的依赖方向、运行时注入和仅通过 `ctx.lsp` 通信的边界。 -- 工具测试固定四种操作、坐标校验、配置限制与省略标记、提示词和 ACP 展示。 +- 工具测试固定四种操作、坐标校验、配置限制与省略标记、提示词和 UI 展示。 - 注册表测试固定原子占用/释放、不受顺序影响的选择,以及结构化的不可用、已释放、冲突和不支持操作错误。 - 测试用 stdio server 固定精确的初始化能力、四种协议映射、`Location`/`LocationLink` 与 `hover` 归一化,以及 `findReferences` 到 `references.includeDeclaration` 的映射。 - 同步测试固定 UTF-16 协商与转换、受支持和被拒绝的 `textDocumentSync` 形式、打开写入阻塞与失败、配对的临时打开/关闭、关闭写入失败和错误响应拒绝。 @@ -182,7 +182,7 @@ ACP 使用 `{ card: 'generic', kind: 'search', title, locations: [{ path: file_p - 生命周期测试固定启动 single-flight、完整生命周期串行化及排队查询读取最新源文件、跨工作区并行、可取消队列、崩溃后不重放的替换、stdin 失败后的进程拆除,以及释放后完全停稳。 - 主机文件系统测试固定 session cwd 要求、符号链接下相对与绝对源路径的规范 containment、文档校验、file/non-file URI 渲染、无格式源文本和不发送 `fs/observed`。 - 无密钥且固定版本的 TypeScript 真实服务器 e2e 覆盖四种操作;可运行配置使用同一项显式提供方映射。 -- 快照覆盖模型可见 schema、提示词、结果、省略提示和 ACP 渲染;构建产物冒烟测试覆盖分帧与清理。 +- 快照覆盖模型可见 schema、提示词、结果和省略提示;构建产物冒烟测试覆盖分帧与清理。 - 包与架构文档覆盖配置、安全边界和搜索/读取指导;同一改动中,新的 `packages/lsp/` 包组要加入 AGENTS.md 的仓库布局块、packages/README.md 的分组表和 architecture.md。 ## 影响 diff --git a/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.i18n.yaml index d218c2a0b2..0b599bc639 100644 --- a/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.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 -2026-07-22-tui-interactive-extension-service.md: 82e7c751b6e5b7500f9f7d7004fda8b905dccabb -2026-07-22-tui-interactive-extension-service.zh.md: d7340e3f5dcf45e95b2d6e15ce3fc33726a555ae +2026-07-22-tui-interactive-extension-service.md: 86cb39748358882d26766467d08f4f43510c1cc2 +2026-07-22-tui-interactive-extension-service.zh.md: d53f526a07b20fcff7086a1f501558d23e7eea8a diff --git a/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.md b/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.md index 82e7c751b6..86cb397483 100644 --- a/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.md +++ b/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.md @@ -28,7 +28,7 @@ Manager tests pin FIFO admission, cancellation, repeated close, shutdown outcome **Expose pi-tui objects directly.** This gives plugins maximum freedom but makes private focus, rendering, and teardown state a public compatibility contract. It also cannot arbitrate independently loaded overlays. -**Put interactive callbacks on command definitions.** Commands are shared by TUI and ACP and remain useful without a terminal. Adding terminal state to `ctx.commands` would couple discovery and dispatch to one presentation implementation. +**Put interactive callbacks on command definitions.** Commands remain transport-neutral domain entries even though TUI is their only shipped consumer. Adding terminal state to `ctx.commands` would couple discovery and dispatch to one presentation implementation. **Create a complete TUI slot and action framework at once.** Actions, editor replacement, transcript renderers, status regions, and completion providers have different composition and conflict rules. Shipping them behind one broad API would freeze those rules before a concrete consumer proves them. diff --git a/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.zh.md b/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.zh.md index d7340e3f5d..d53f526a07 100644 --- a/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.zh.md @@ -28,7 +28,7 @@ Cordis 插件可以通过 `ctx.commands` 注册用户命令,但需要终端交 **直接暴露 pi-tui 对象。** 这会赋予插件最大的自由度,却会把私有的焦点、渲染与拆卸状态变成公开兼容性契约,也无法在独立加载的浮层之间进行仲裁。 -**在命令定义中加入交互回调。** 命令由 TUI 与 ACP 共享,即使没有终端也仍然有用。向 `ctx.commands` 添加终端状态,会让发现与分派流程耦合到某一种呈现实现。 +**在命令定义中加入交互回调。** 命令仍是传输无关的领域条目,尽管 TUI 是唯一已交付的消费方。向 `ctx.commands` 添加终端状态,会让发现与分派流程耦合到某一种呈现实现。 **一次性建立完整的 TUI slot 与 action 框架。** action、编辑器替换、transcript 渲染器、状态区域和补全提供方具有不同的组合规则与冲突规则。在具体消费方验证这些规则之前就将其纳入一个宽泛 API,会过早固化这些规则。 diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index 54df5f07ab..87ce1f1bac 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.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 -2026-07-23-client-plugin-loading-model.md: 58651fd258a6b2929c58bb6f93b44adb6e8e1818 -2026-07-23-client-plugin-loading-model.zh.md: f60b06c7bfaa9c70170082ac4384ba2bd899676e +2026-07-23-client-plugin-loading-model.md: 3513e026785fc366455bb32bf788a3a098275bb1 +2026-07-23-client-plugin-loading-model.zh.md: f31a1b076a5d93db44c67463730b38283d44ff7f diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index 58651fd258..3513e02678 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -56,11 +56,11 @@ What happens between `dsh web` starting and the UI appearing? Three stages: the **Host side — compose the graph.** -1. The composing app (`apps/cli`) mounts the roster as in-memory Loader entries via `mountWebPlugins`. The roster is one flat list of the plugin packages, plus the `client-hmr` row under `--dev`. A roster package that fails to import throws loud at mount. -2. The registry (`createHostWebPluginRegistry`) scans the mounted entries' package.json `dshClient` declarations and composes `window.__DSH_BOOT__`: `{ rev, entries: [{ id, url, rev, inject?, immediately? }] }`. The `inject` edges and the `immediately` mark come from manifests, never hand-copied. It refuses a declared plugin without a built `./client` bundle, and any malformed declaration field — load-time fail loud. -3. The registry rescans on cordis `internal/plugin`, microtask-debounced; a rescan failure keeps serving the previous graph. Each bundle's content is hashed into its `rev` (cache busting + HMR diff anchor), and the row set into `graph.rev`. Every row is fetch-served: `/plugins/<id>/client.js?rev=…`. The graph types are a wire contract dual-held on both sides, because the webserver keeps zero workspace dependencies. +1. The composing app (`apps/cli`) ships the roster as ordinary rows in its `cordis.yml` config tree — client plugin packages are entry rows like every host plugin, and `--dev` appends the `client-hmr` row in code (`AppCLIEntry`) before the settle/sweep so the fail-loud triple covers it. A roster row that fails to import is caught by the boot's `assertEntriesLoaded`. +2. The `dsh-client-modules` node half (the package is dual-face: its browser half is the module table) scans loader entries' package.json `dshClient` declarations and composes `window.__DSH_BOOT__`: `{ rev, entries: [{ id, url, rev, inject?, immediately? }] }`. The `inject` edges and the `immediately` mark come from manifests, never hand-copied. It refuses a declared plugin without a built `./client` bundle, and any malformed declaration field — activation-time fail loud (a FAILED fiber the sweep reports). +3. Scanning is incremental per package — there is no full-rescan code path. Each cordis `internal/plugin` emission marks the fiber's entry name dirty (entry-less fibers drop O(1)); a microtask flush reconciles each dirty name against live loader entries, with package metadata (including the negative "not a client package" verdict) cached per name forever and bundle re-hashing reachable only through `rebuilt(id)`. The activation pass seeds the same dirty set from current entries and flushes synchronously, so first scan and steady state share one implementation. Each bundle's content hash is its `rev` (cache busting + HMR diff anchor), the row set hashes into `graph.rev`, and every row is fetch-served: `/plugins/<id>/client.js?rev=…`. The graph types are single-sourced in the modules package's `./impl` export — the webserver knows nothing about the graph (it is a plain route-registration plugin; modules registers the bundle route and taps the index render itself). -Why is the roster a hand-written list and not a scan? Because which plugins compose into a deployment is a composition decision, not a package property — a dshClient package existing in the repo does not mean this deployment mounts it, so discovery-by-scan cannot make that call. The roster lives in `apps/cli/web.ts` rather than cordis.yml only because `dsh web`'s host is a hand-assembled `bootHost` with no Loader config tree yet. +Why is the roster yml rows and not a scan? Because which plugins compose into a deployment is a composition decision, not a package property — a dshClient package existing in the repo does not mean this deployment mounts it, so discovery-by-scan cannot make that call; the node half scans only what the tree actually mounted. **Phase one — the module face.** The shell builds the module system over the graph, then prefetches every `immediately` row in parallel. Prefetch is fetch + execute, which registers factories only. A single row's prefetch failure is swallowed here: phase two's import retries the fetch and owns the loud failure, so one bad row cannot mask the others. `immediately` is a prefetch mark — not a barrier, not an identity. The package declares it, the registry carries it into the row. The infrastructure plugins (connection, runtime, ui-theme, i18n, plus hmr) declare it; UI plugins simply arrive on demand. @@ -74,9 +74,9 @@ Why is the roster a hand-written list and not a scan? Because which plugins comp ### Hot reload: one driver plugin, self-watched bundles -Whether hot reload is active is a composition decision: dev graphs include the `client-hmr` row (a normal plugin package) and turn on bundle watching; prod graphs do neither. +Whether hot reload is active is a composition decision: dev compositions mount the `client-hmr` row (a normal plugin package, appended by `--dev`) whose node half brings the bundle watch and the SSE channel; prod compositions mount nothing and have neither. -How does a rebuilt bundle become a reload signal? The webserver observes it itself — no builder tells it. The registry scan already holds every plugin's bundle path (`clientPath`), so in dev mode the registry stat-polls each scanned bundle file with `fs.watchFile`. Polling is by design: inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`. On a mtime/size change the registry re-hashes that row (`rebuilt(id)`); when the `rev` actually changed, it broadcasts a `rebuilt` frame on `GET /plugins/events` — a system SSE channel that sends the full graph on connect and `rebuilt` frames on change, presentation-only wire that never enters the session log. Watch set membership follows the table: rescans add watches for new rows and drop them for vanished ones, dispose drops all. The poll interval is a validated config field (default 500ms), not a constant. Rebuilding the bundles is any tsdown watch process's business — `scripts/dev-web.ts` remains as the watch-build entry point, its package list dshClient-discovered by scanning `packages/*/*/package.json` at startup — and builder and host share zero protocol. A torn read of a half-written bundle self-heals: the stats keep changing while the write completes, so the next poll tick re-hashes again and broadcasts the final rev. +How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. It reads bundle paths from `ctx.clientModuleHost.clientPath(id)`, and one HMR-owned interval stat-polls every current graph row. Adding a row is ordered as synchronous stat baseline, then immediate `clientModuleHost.rebuilt(id)`: a write after the module host's graph hash but before that baseline is caught by the immediate re-hash, while a write after the baseline leaves a stat delta for the next poll. This avoids `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and a bundle missing at poll time keeps its row dirty so reappearance forces a re-hash even with identical metadata. On a mtime/size delta or dirty row, `clientModuleHost.rebuilt(id)` is the single re-hash entry point; when the `rev` actually changed, the node half broadcasts a `rebuilt` frame on `GET /plugins/events` — a system SSE channel that sends the full graph on connect and `rebuilt` frames on change, presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding bundles is any tsdown watch process's business — `scripts/dev-web.ts` remains the watch-build entry point, its package list dshClient-discovered by scanning `packages/*/*/package.json` at startup — and builder and host share zero protocol. A torn read self-heals: stats keep changing while the write completes, so the next poll re-hashes and broadcasts the final rev. On the browser side, the driver reloads one plugin per frame, serialized: @@ -116,7 +116,7 @@ One governance implementation runs on both sides of the wire; the browser-specif Costs accepted: the vendored Loader carries idle machinery in the browser (EntryTree persistence is a no-op, groups/isolation unused); every plugin edit in dev pays a bundle rebuild plus fiber remount; graph `inject` rows are informational — activation truth is service-level — so a mismatch surfaces at the settled sweep, not at graph validation; and the three not-yet-promoted libraries keep their static-import export surface until their DI conversions land. -Roster endgame: when `dsh web` moves to config-tree boot, the roster lands in cordis.yml — client plugin packages become ordinary config-tree entry rows, `mountWebPlugins` and the `CLIENT_PACKAGES` constant disappear, and recomposing a deployment means swapping the yml/overlay. The registry needs zero changes for that move, since its `internal/plugin` subscription already discovers whatever entries the tree mounts. +Roster endgame (landed 2026-07-25 with the config-tree boot move): the roster lives in `apps/cli/cordis.yml`, `mountWebPlugins` and the `CLIENT_PACKAGES` constant are gone, and recomposing a deployment means swapping the yml/overlay. The graph composer moved from a webserver-side registry into the `dsh-client-modules` node half (the package upgraded to dual-face per this note's promotion rule — its consumer now reaches it through cordis DI), and the transport split landed alongside: the webserver became a plain route-registration plugin, `/api/*` binding moved to the connection node half over the upgraded `api-gateway` plugin (`dsh-host-apiproxy` providing `ctx.apiProxy`), and the dev bundle watch + SSE channel moved to the hmr node half. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md index f60b06c7bf..f31a1b076a 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md @@ -56,11 +56,11 @@ vendored Loader 经其 `internal` seam 消费模块系统——唯一调用点 **host 侧——组合这张图。** -1. 负责组合的 app(`apps/cli`)经 `mountWebPlugins` 把名册挂载为内存中的 Loader entry。名册是插件包的一张平铺清单,`--dev` 下外加 `client-hmr` 行。名册里 import 失败的包在挂载时大声抛错。 -2. 注册表(`createHostWebPluginRegistry`)扫描已挂载 entry 的 package.json `dshClient` 声明,组合出 `window.__DSH_BOOT__`:`{ rev, entries: [{ id, url, rev, inject?, immediately? }] }`。`inject` 边与 `immediately` 标记都来自 manifest,永不人肉抄写。它拒绝声明了插件却没有已构建 `./client` bundle 的包,也拒绝任何畸形的声明字段——装载期大声失败。 -3. 注册表在 cordis `internal/plugin` 上重扫,微任务去抖;重扫失败则继续供给上一张图。每个 bundle 的内容哈希进其 `rev`(缓存失效 + HMR diff 锚点),行集合哈希进 `graph.rev`。每一行都经 fetch 供给:`/plugins/<id>/client.js?rev=…`。图的类型是两侧各持一份的 wire 契约,因为 webserver 保持零 workspace 依赖。 +1. 负责组合的 app(`apps/cli`)把名册作为普通行放进它的 `cordis.yml` 配置树——client 插件包与每个 host 插件一样是 entry 行,`--dev` 由代码(`AppCLIEntry`)在 settle/sweep 之前追加 `client-hmr` 行,使 fail-loud 三件套一并覆盖它。名册行 import 失败由 boot 的 `assertEntriesLoaded` 捕获。 +2. `dsh-client-modules` 的 node 半(该包是双面的:浏览器半就是模块表)扫描 loader entry 的 package.json `dshClient` 声明,组合出 `window.__DSH_BOOT__`:`{ rev, entries: [{ id, url, rev, inject?, immediately? }] }`。`inject` 边与 `immediately` 标记都来自 manifest,永不人肉抄写。它拒绝声明了插件却没有已构建 `./client` bundle 的包,也拒绝任何畸形的声明字段——激活期大声失败(FAILED fiber,由 sweep 上报)。 +3. 扫描是单包增量——不存在全量重扫代码路径。每次 cordis `internal/plugin` 发射把该 fiber 的 entry 名标脏(无 entry 的 fiber O(1) 丢弃);微任务 flush 把每个脏名对账 live loader entries,包元数据(含「非 client 包」的否定结论)按名永久缓存,bundle 重哈希只经 `rebuilt(id)` 可达。激活趟从当前 entries 灌同一脏集合并同步 flush,初扫与稳态共享一条实现。每个 bundle 的内容哈希是其 `rev`(缓存失效 + HMR diff 锚点),行集合哈希进 `graph.rev`,每一行都经 fetch 供给:`/plugins/<id>/client.js?rev=…`。图类型单源在 modules 包的 `./client` 出口——webserver 对图一无所知(它是朴素路由注册插件;bundle 路由和 index 渲染 tap 都由 modules 自己注册)。 -为什么名册是手写清单而不是扫描?因为哪些插件组合进一次部署是组合决策,不是包属性——一个 dshClient 包存在于仓库里,不代表这次部署要挂载它,扫描发现无从替人做这个决定。名册住在 `apps/cli/web.ts` 而非 cordis.yml,只是因为 `dsh web` 的 host 还是一个手工装配的 `bootHost`,没有 Loader 配置树。 +为什么名册是 yml 行而不是扫描?因为哪些插件组合进一次部署是组合决策,不是包属性——一个 dshClient 包存在于仓库里,不代表这次部署要挂载它,扫描发现无从替人做这个决定;node 半只扫描配置树实际挂载了的东西。 **第一层——模块面。**壳在图之上建起模块系统,然后并行预取每个 `immediately` 行。预取即 fetch + 执行,只登记工厂。单行预取失败在这里被吞下:第二层 import 时会重试 fetch 并拥有那次大声失败,因此一个坏行藏不住其他行。`immediately` 是预取标记——不是屏障,不是身份。包声明它,注册表把它带进图行。基础设施插件(connection、runtime、ui-theme、i18n,外加 hmr)声明它;UI 插件则径直按需到达。 @@ -74,9 +74,9 @@ vendored Loader 经其 `internal` seam 消费模块系统——唯一调用点 ### 热重载:一个驱动插件,自行监视的 bundle -热重载是否启用是一项组合决策:dev 图包含 `client-hmr` 行(一个常规的插件包)并开启 bundle 监视;prod 图两者皆无。 +热重载是否启用是一项组合决策:dev 组合挂载 `client-hmr` 行(一个常规的插件包,由 `--dev` 追加),其 node 半带来 bundle 监视与 SSE 通道;prod 组合不挂载,两者皆无。 -重建好的 bundle 怎么变成重载信号?webserver 自己观察——没有构建器来通知它。注册表扫描本就握有每个插件的 bundle 路径(`clientPath`),因此 dev 模式下注册表用 `fs.watchFile` 对每个已扫描的 bundle 文件做 stat 轮询。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因。mtime/size 一变,注册表就重哈希该行(`rebuilt(id)`);当 `rev` 真的变了,才在 `GET /plugins/events` 上广播 `rebuilt` 帧——这是一条系统级 SSE(Server-Sent Events)通道,连接即发全量图,变更时发 `rebuilt` 帧,仅供呈现的 wire,永不进会话日志。监视集合的成员随表走:重扫为新行添加监视、为消失的行撤下监视,dispose(资源释放)撤掉全部。轮询间隔是一个经校验的配置字段(默认 500ms),不是常量。重建 bundle 则是任意一个 tsdown watch 进程的事——`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dshClient 发现——构建器与 host 共享零协议。写一半的 bundle 被撕裂读取会自愈:写入完成期间 stat 持续变化,下一个轮询节拍会再次重哈希并广播最终的 rev。 +重建好的 bundle 怎么变成重载信号?hmr 的 node 半自己观察——没有构建器来通知它。它从 `ctx.clientModuleHost.clientPath(id)` 读取图上各行的 bundle 路径,由 HMR 自持的单个定时器对当前图上的每一行做 stat 轮询。新增图行时,顺序固定为先同步取得 stat 基线,再立即调用 `clientModuleHost.rebuilt(id)`:在模块 host 算出图哈希之后、取得基线之前发生的写入会被这次立即重哈希捕获;取得基线之后发生的写入则会留下 stat 差异,供下一次轮询捕获。这避开了 `fs.watchFile`:它以异步首次 stat 建立基线,可能把构造期间的重建静默吸收进基线。监视集合的成员随 `onGraphChanged` 更新;消失的行撤下监视,轮询时缺失的 bundle 则让对应行保持标脏状态,文件重现时即使元数据相同也强制重哈希。mtime/size 变化或行处于标脏状态时,`clientModuleHost.rebuilt(id)` 是重哈希的唯一入口;当 `rev` 真的变了,node 半才在 `GET /plugins/events` 上广播 `rebuilt` 帧——这是一条系统级 SSE(Server-Sent Events)通道,连接即发全量图,变更时发 `rebuilt` 帧,仅供呈现的 wire,永不进会话日志。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因;轮询间隔是一个经校验的配置字段(默认 500ms),dispose(资源释放)会清掉那一个定时器。重建 bundle 则是任意一个 tsdown watch 进程的事——`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dshClient 发现——构建器与 host 共享零协议。写一半的 bundle 被撕裂读取会自愈:写入完成期间 stat 持续变化,下一个轮询节拍会再次重哈希并广播最终的 rev。 浏览器侧,驱动插件每帧重载一个插件,串行执行: @@ -116,7 +116,7 @@ wire 两侧跑着同一份治理实现;浏览器特有的表面只是一套模 接受的代价:vendored Loader 在浏览器里背着闲置机件(EntryTree 持久化是 no-op,分组/隔离未用);开发期每次修改插件都要付一次 bundle 重建加 fiber 重挂;图中 `inject` 行仅是信息性说明——激活的真相在服务层——因此不匹配会在 settled 扫描时浮出,而不是在图校验时被拦下;三个尚未升格的库在各自的 DI 转换落地之前保持静态 import 的导出面。 -名册的终局:当 `dsh web` 迁到配置树 boot,名册落进 cordis.yml——client 插件包变成普通的配置树 entry 行,`mountWebPlugins` 与 `CLIENT_PACKAGES` 常量消失,重组一次部署等于换 yml/overlay。注册表为这次迁移零改动,因为它的 `internal/plugin` 订阅本就发现配置树挂载的任何 entry。 +名册的终局(2026-07-25 随配置树 boot 迁移落地):名册住 `apps/cli/cordis.yml`,`mountWebPlugins` 与 `CLIENT_PACKAGES` 常量已消失,重组一次部署等于换 yml/overlay。图的组合器从 webserver 侧的注册表迁进 `dsh-client-modules` 的 node 半(该包按本 note 的升级法则升格为双面——其消费方现经 cordis DI 到达),传输拆分同轮落地:webserver 变为朴素路由注册插件,`/api/*` 绑定迁到 connection 的 node 半、走升格后的 `api-gateway` 插件(`dsh-host-apiproxy` 提供 `ctx.apiProxy`),dev 的 bundle 监视与 SSE 通道迁到 hmr 的 node 半。 ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.i18n.yaml new file mode 100644 index 0000000000..795cb97082 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-24-web-config-tree-boot-and-transport-layering.md: 9e93b828d5f11060aa476396f6981320c33485a5 +2026-07-24-web-config-tree-boot-and-transport-layering.zh.md: 996a5705bd5d00a2163a146ef8210247f512e6fa diff --git a/.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.md b/.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.md new file mode 100644 index 0000000000..9e93b828d5 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.md @@ -0,0 +1,42 @@ +# Agent Note: dsh web config-tree boot and the web transport layering + +Status: implemented + +English | [中文](2026-07-24-web-config-tree-boot-and-transport-layering.zh.md) + +> Scope: how `dsh web` composes (cordis.yml + pre-cordis boot classes + config sources) and how the web transport splits across packages (gateway / carrier / binding / graph / dev-reload). The [client plugin loading note](2026-07-23-client-plugin-loading-model.md) owns the browser-side loading chain this composition feeds. + +## Problem + +`dsh web` was the only hand-assembled surface left: `bootHost` mounted 32 plugins with configs pinned in code (violating no-hardcoded-tunables), the client roster was a `web.ts` constant, and TUI/headless had long been yml compositions. The transport layer misplaced responsibilities to match: the webserver self-described as a dumb carrier yet knew the `__DSH_BOOT__` graph, owned the SSE channel, and hard-coded the `/api/*` prefix; the dev bundle watch lived inside the prod registry behind a `watch?` flag with no lifecycle owner; the graph registry rescanned everything on every `internal/plugin` emission; per-request errors and fatal server errors shared one sink that always exited the process. One user-visible defect rode along: the web path never loaded `$DSH_HOME/.env`, so `DSH_HOME=… dsh web` could not find an API key living there. + +## Decision + +**Composition is one flat config tree.** `apps/cli/cordis.yml` holds every row — the host runtime (32 rows), the `api-gateway` row, the `webserver` row, and the ten `dshClient` rows (the browser roster; the modules row is simultaneously a host row). No spine bundle: every plugin is one row and every config field is yml-editable. `--dev` appends the `dsh-client-hmr` row in code before the settle sweep — prod and dev differ by exactly that row. Row order carries no load semantics; activation is service-availability driven, and the boot compensates with a fail-loud triple: `assertEntriesLoaded` (import failures), `installFailLoud` (late apply rejections), and an all-ACTIVE sweep (PENDING fibers — cordis inject waiting has no timeout). + +**Boot glue is a class pair.** `AppCLIEntry` (apps/cli) and `AppWebEntry` (the shell kernel) hold only what must exist independently of cordis: argv facts, the composed patch set, the parsed boot manifest, the module system instance, loading-page handles — everything else lives in plugins. `AppCLIEntry.run()` is three stages: layered env (ambient > cwd `.env` > `$DSH_HOME/.env`, closing the defect above) → patch composition → Loader include boot plus the triple. `AppWebEntry.run()` mirrors it browser-side: parse `window.__DSH_BOOT__` into a `BootManifest` (two views: npm-package rows for the module table, cordis-plugin rows for entry composition; malformed wire throws), build the module system, render the loading page, prefetch the `immediately` tier in parallel with Context/Loader setup, **await the prefetch before creating entries** (materialization is `tree.import`'s synchronous require, unprotected by fiber inject waiting; cross-package require edges such as i18n → runtime/client need every immediately-tier factory registered first — an empirically found 10–25% boot race otherwise), adopt the modules entry, create the graph rows, settle, sweep. + +**Config sources have one declaration place each.** yml static values are engineering defaults; the profile json (`./.dsh-tmp-profile/config.json`, read-only, never created, cwd-anchored until the `$DSH_HOME` migration) is user config mapped through a static `PROFILE_MAPPINGS` table onto target rows (`provider`/`model` → the `api-gateway` row, `persistenceRoot` → the jsonl row); CLI flags map onto the `webserver` row with a field set disjoint from the json's; env values enter through yml `!!js` expressions, never through the mapping table. Patches replace a row's config wholesale, so the entry class re-reads the yml row's static values (bypass parse) and merges overrides on top. An unmapped json key fails loud. The resolved frontend `distIndex` rides the same patch channel — an assembly fact, not user config. + +**The transport splits five ways.** `dsh-host-apiproxy` upgraded to the gateway plugin (`api-gateway` row): default-exports `ApiProxyService`, config `{provider, model}`, provides `ctx.apiProxy`, transport-agnostic and registers no routes — `createApiProxy` moved here from runtime (dependency direction allows it; runtime keeps `bootHost`/`startHost` for headless). `dsh-host-webserver` shrank to a plain route-registration plugin: `HttpServerService` provides `ctx.httpServer` (`register(route) → disposer` with duplicate-pattern throw, `tapIndex` transforms applied in registration order, `port`), listens on activation, per-request failures answer 400 and log without exiting, and knows no harness concepts. The connection node half owns the binding: it injects both services and registers `toFetchHandler(ctx.apiProxy)` under the `/api` prefix — future IPC carriers swap connection's transport while the gateway stays untouched. The modules node half (`ClientModuleHostService`, providing `ctx.clientModuleHost`) owns the graph: incremental per-package scanning (no full-rescan code path — `internal/plugin` marks the fiber's entry name dirty, a flush reconciles each name against live entries, package metadata including negative verdicts is cached forever, re-hashing is reachable only through `rebuilt(id)`), the bundle route, the index tap, and `onRebuilt`/`onGraphChanged` notification. The hmr node half owns dev reload: `fs.watchFile` stat-polling driven by `onGraphChanged` membership, and the `/plugins/events` SSE route. + +**Package export discipline.** The modules package exposes exactly `.` (node half) and `./client` (the complete browser half: `ClientModuleSystem`, `parseBootManifest`, the adoption plugin face) — no bespoke subpaths; wire types re-export through the root for host-side consumers. The adoption handshake: the kernel writes the constructed instance to `window.__DSH_MODULES__` before cordis exists; the `./client` apply reads the slot (missing = loud throw) and provides `ctx.modules`. + +## Consequences + +- Recomposing a web deployment is a yml/patch edit; the retired pieces (`mountWebPlugins`, `CLIENT_PACKAGES`, `createHostWebPluginRegistry`, `startWebServer`, the webserver's graph/SSE/api knowledge) are deleted. +- Headless still boots through `bootHost` (unchanged this round); its migration, the profile write path, the `$DSH_HOME` profile relocation, and IPC carriers are recorded deferrals in the design ledger. +- A TypeScript pitfall worth remembering: a `declare module 'cordis'` augmentation in a file with **no cordis import** is demoted to a standalone module declaration and silently shatters the program-wide `Context` merge (`ctx.on`/`ctx.effect` vanish across the program). Anchor with `import type {} from 'cordis'`. + +## Alternatives considered + +| Rejected | One-line reason | +|---|---| +| Dedicated `dsh-host-profile` receiver package | The profile json is consumed at patch time; the only runtime consumer of `{provider, model}` is the gateway itself — its config is the receiver | +| Runtime `assembly` shim plugin providing an `apiHandler` service | Existed only because `createApiProxy` lived in runtime; moving it into apiproxy made the gateway self-hosting, and `toFetchHandler` is a pure function the binding side calls | +| Full-rescan + incremental scan coexisting | Two implementations, two semantics; the single per-package path covers the activation pass too | +| A bespoke `./impl` export on the modules package | Non-uniform export surface; the standard `./client` carries the whole browser half | +| dev overlay / `cordis.dev.yml` | One yml; `!!js` cannot conditionalize row existence, and `--dev` appending one row is the entire difference | +| env vars in the mapping table | The same field would gain env/json double sourcing and need an invented precedence | +| Unbarriered create-after-prefetch (`arrive()` dedup as safety) | Disproved by a 10–25% boot race: in-flight dedup covers same-package double-fetch, not cross-package synchronous require edges | +| json file used directly as loader patches | json keys would couple to yml row structure; profile writers would need cordis knowledge | diff --git a/.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.zh.md b/.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.zh.md new file mode 100644 index 0000000000..996a5705bd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.zh.md @@ -0,0 +1,42 @@ +# Agent Note:dsh web 的 config-tree boot 与 web 传输分层 + +Status: implemented + +[English](2026-07-24-web-config-tree-boot-and-transport-layering.md) | 中文 + +> 范围:`dsh web` 如何组合(cordis.yml + cordis 之前的 boot 类 + 配置源),以及 web 传输如何跨包分层(网关 / 载体 / 绑定 / 图 / 开发期重载)。浏览器侧装载链归 [client 插件装载 note](2026-07-23-client-plugin-loading-model.md) 所有,本组合只是它的供给方。 + +## 问题 + +`dsh web` 曾是仅剩的手工装配面:`bootHost` 逐个挂 32 个插件、config 钉死在代码里(违反 no-hardcoded-tunables),client roster 是 `web.ts` 常量,而 TUI/headless 早已是 yml 组合。传输层的职责错位与之配套:webserver 自称哑载体却认识 `__DSH_BOOT__` 图、拥有 SSE 通道、硬编码 `/api/*` 前缀;dev 的 bundle watch 寄居在 prod registry 里靠 `watch?` 参数开关、生命周期无主;图 registry 对每次 `internal/plugin` 全量重扫;单请求失败与致命 server 错误共用一个一律退进程的 sink。还有一个用户可见缺陷:web 路径不装 `$DSH_HOME/.env`,`DSH_HOME=… dsh web` 读不到自定义 home 下的 API key。 + +## 决策 + +**组合是一棵平铺 config tree。** `apps/cli/cordis.yml` 持有全部行——host runtime(32 行)、`api-gateway` 行、`webserver` 行、十个 `dshClient` 行(浏览器 roster;modules 行同时是 host 行)。不做 spine bundle:每插件一行、每个 config 字段 yml 可改。`--dev` 在 settle sweep 之前由代码追加 `dsh-client-hmr` 行——prod 与 dev 的全部差异就是这一行。行序无装载语义;激活由服务可用性驱动,boot 以 fail-loud 三件套补偿:`assertEntriesLoaded`(import 失败)、`installFailLoud`(迟到的 apply 拒绝)、all-ACTIVE sweep(PENDING fiber——cordis inject 等待没有超时)。 + +**boot 胶水是一对 class。** `AppCLIEntry`(apps/cli)与 `AppWebEntry`(壳内核)只持有独立于 cordis 必须提前存在的东西:argv 事实、合成的 patch 集、解析出的 boot manifest、模块系统实例、loading 页句柄——其余一律进插件。`AppCLIEntry.run()` 三段:分层 env(ambient > cwd `.env` > `$DSH_HOME/.env`,顺手关掉上述缺陷)→ patch 合成 → Loader include boot 加三件套。`AppWebEntry.run()` 在浏览器侧镜像它:把 `window.__DSH_BOOT__` 解析成 `BootManifest`(双视角:npm 包行给模块表、cordis 插件行给 entry 组合;畸形 wire 大声抛)、建模块系统、渲染 loading 页、immediately 层预取与 Context/Loader 准备并行、**create entry 之前等预取齐**(物化是 `tree.import` 的同步 require,不受 fiber inject 等待保护;i18n → runtime/client 这类跨包 require 边要求 immediately 层工厂全部注册完——否则有实测 10–25% 的 boot 竞态)、收编 modules entry、逐图行 create、settle、sweep。 + +**每个配置源有唯一声明位置。** yml 静态值是工程默认;profile json(`./.dsh-tmp-profile/config.json`,只读、绝不创建、暂锚 cwd 直至 `$DSH_HOME` 迁移)是用户配置,经静态 `PROFILE_MAPPINGS` 表映射到目标行(`provider`/`model` → `api-gateway` 行,`persistenceRoot` → jsonl 行);CLI flags 映射到 `webserver` 行、字段集与 json 不相交;env 值经 yml `!!js` 表达式进入,绝不进映射表。patch 整体替换行 config,故 entry 类旁路 parse 重读 yml 行静态值再叠加覆盖。未映射的 json 键 fail loud。解析出的前端 `distIndex` 走同一 patch 通道——装配事实,不是用户配置。 + +**传输五分。** `dsh-host-apiproxy` 升格网关插件(`api-gateway` 行):默认导出 `ApiProxyService`,config `{provider, model}`,provide `ctx.apiProxy`,传输无关、不注册路由——`createApiProxy` 从 runtime 迁入(依赖方向允许;runtime 保留 `bootHost`/`startHost` 供 headless)。`dsh-host-webserver` 缩成朴素路由注册插件:`HttpServerService` provide `ctx.httpServer`(`register(route) → disposer`、重复 pattern 即抛、`tapIndex` 按注册序应用、`port`),激活即 listen,单请求失败答 400 并记日志不退进程,不认识任何 harness 概念。connection node 半拥有绑定:inject 两个服务,把 `toFetchHandler(ctx.apiProxy)` 注册在 `/api` 前缀下——将来 IPC 载体只换 connection 的传输,网关零改动。modules node 半(`ClientModuleHostService`,provide `ctx.clientModuleHost`)拥有图:单包增量扫描(无全量重扫路径——`internal/plugin` 把 fiber 的 entry 名标脏,flush 逐名对账 live entries,包元数据含否定结论永久缓存,重哈希唯一入口 `rebuilt(id)`)、bundle 路由、index tap、`onRebuilt`/`onGraphChanged` 通知。hmr node 半拥有开发期重载:`fs.watchFile` stat 轮询、watch 集合跟随 `onGraphChanged`、`/plugins/events` SSE 路由。 + +**包出口纪律。** modules 包只暴露 `.`(node 半)与 `./client`(完整浏览器半:`ClientModuleSystem`、`parseBootManifest`、收编插件面)——不设特设子路径;wire 类型经根出口 re-export 给 host 侧消费方。收编握手:内核在 cordis 之前把建好的实例写入 `window.__DSH_MODULES__`;`./client` 的 apply 读槽(缺槽大声抛)并 provide `ctx.modules`。 + +## 后果 + +- 重组一个 web 部署 = 改 yml/patch;退役件(`mountWebPlugins`、`CLIENT_PACKAGES`、`createHostWebPluginRegistry`、`startWebServer`、webserver 的图/SSE/api 知识)全部删除。 +- headless 本轮仍走 `bootHost`;它的迁移、profile 写入路径、profile 迁 `$DSH_HOME`、IPC 载体,均为设计台账中的挂账项。 +- 一个值得记住的 TypeScript 坑:`declare module 'cordis'` augmentation 所在文件若**没有任何 cordis import**,会被降级成独立 module declaration,无声打散全程序的 `Context` merge(`ctx.on`/`ctx.effect` 全程序消失)。用 `import type {} from 'cordis'` 锚定。 + +## Alternatives considered + +| 弃案 | 一行理由 | +|---|---| +| 专门的 `dsh-host-profile` 受体包 | profile json 在 patch 阶段消费完;`{provider, model}` 的唯一运行时消费方是网关自己——受体即网关 config | +| runtime 里的 `assembly` 垫层插件(provide `apiHandler`) | 它的存在只因 `createApiProxy` 住 runtime;本体迁入 apiproxy 后网关自持插件身份,且 `toFetchHandler` 是绑定方自己调的纯函数 | +| 全量重扫与增量扫描并存 | 两条实现两份语义;单包路径足以覆盖激活初扫 | +| modules 包特设 `./impl` 出口 | 出口面不统一;标准 `./client` 承载完整浏览器半 | +| dev overlay / `cordis.dev.yml` | 一套 yml;`!!js` 无法条件化行存在性,`--dev` 追加一行就是全部差异 | +| env 进映射表 | 同一字段将出现 env/json 双源,需再发明优先级 | +| create 不等预取(以 `arrive()` 去重为安全依据) | 被 10–25% boot 竞态证伪:在途去重只覆盖同包双拉,不覆盖跨包同步 require 边 | +| json 直接当 loader patches 文件 | json 键名将耦合 yml 行结构,写入方要懂 cordis | diff --git a/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.i18n.yaml index 8453907b5c..bf8f19a570 100644 --- a/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.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 -2026-07-20-code-mode-result-card-completeness.md: 03c14cd780832fa03977dade2c7d14feb0399369 -2026-07-20-code-mode-result-card-completeness.zh.md: 45047cc5bcb8b74668702302077ff91fd3ff6bdc +2026-07-20-code-mode-result-card-completeness.md: 97cd9d722e8252b956e16da03c3b8418451350f3 +2026-07-20-code-mode-result-card-completeness.zh.md: fea162b073e3473f7a07d4bf054408d28851fea9 diff --git a/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.md b/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.md index 03c14cd780..97cd9d722e 100644 --- a/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.md +++ b/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.md @@ -6,7 +6,7 @@ English | [中文](2026-07-20-code-mode-result-card-completeness.zh.md) ## Problem -The outer `run_code` tool persisted complete rendered content, but its editor presenter ignored that content and rebuilt the card body from a logs-only `presentationMeta` projection. A result-only run appeared correct because an empty presenter body let ACP and TUI fall back to `tool/result.content`. Once the program emitted a log, the presenter supplied non-empty content, that fallback stopped, and the returned value disappeared from the completed card. A spill policy's final head/tail preview was vulnerable to the same split ownership whenever captured logs made the stale projection non-empty. +The outer `run_code` tool persisted complete rendered content, but its UI presenter ignored that content and rebuilt the card body from a logs-only `presentationMeta` projection. A result-only run appeared correct because an empty presenter body let consumers fall back to `tool/result.content`. Once the program emitted a log, the presenter supplied non-empty content, that fallback stopped, and the returned value disappeared from the completed card. A spill policy's final head/tail preview was vulnerable to the same split ownership whenever captured logs made the stale projection non-empty. Nested Code calls never owned cards, so producing metadata for the outer call solely to reconstruct one incomplete card also obscured the intended one-card boundary. @@ -22,7 +22,7 @@ Nested dispatch remains unchanged. Calls marked by `exec.parent` emit bounded `t Tool unit coverage drives logs-only, result-only, logs-plus-result, no-output, spilled-result, and failure outcomes through the canonical registry, then pins the durable content and absence of a result presenter. A host-mux regression uses a call-only presenter to prove the result frame carries raw content exactly once and no view. These cases prove stale metadata cannot replace final content without making the host duplicate that content. -The keyless ACP and TUI Code Mode snapshots execute one outer program that performs two nested bash calls, logs `captured output`, and returns `CODE_ONE+CODE_TWO`. Both surfaces show one completed outer card containing both lines and no nested cards. +The keyless ACP backend and TUI Code Mode snapshots execute one outer program that performs two nested bash calls, logs `captured output`, and returns `CODE_ONE+CODE_TWO`. The persisted ACP log pins the complete result; the TUI surface shows one completed outer card containing both lines and no nested cards. ## Alternatives considered @@ -30,10 +30,10 @@ The keyless ACP and TUI Code Mode snapshots execute one outer program that perfo **Merge presenter metadata with `result.content`.** Rejected because the rendered content already contains the logs; merging would duplicate them and require brittle deduplication. -**Forward `result.content` through a generic result presenter.** Rejected because the durable event already carries that content and ACP/TUI already have a generic raw-content fallback. The host mux serializes a tool-owned result view beside the event, so forwarding would duplicate the rendered content in one frame merely to recreate the fallback; the default worker alone admits a 64 MiB variable-payload budget before rendering. +**Forward `result.content` through a generic result presenter.** Rejected because the durable event already carries that content and UI consumers already have a generic raw-content fallback. The host mux serializes a tool-owned result view beside the event, so forwarding would duplicate the rendered content in one frame merely to recreate the fallback; the default worker alone admits a 64 MiB variable-payload budget before rendering. **Create one card per nested dispatch.** Rejected because intermediate values are intentionally execution-local and never model-facing. Multiple cards would expose an implementation trace instead of the single Code Mode operation the model and user invoked. ## Consequences -ACP and TUI display the same complete content the model receives and replay persists, including post-policy spill previews, through their generic result fallback. The host API retains the pending program title without duplicating the raw result in a separate view payload. New `run_code` results no longer carry the optional logs metadata, but this requires no session-format bump: existing records remain valid because presentation reads their durable rendered content. +TUI and JSON-RPC/Web display the same complete content the model receives and replay persists, including post-policy spill previews, through their generic result fallback. The host API retains the pending program title without duplicating the raw result in a separate view payload. New `run_code` results no longer carry the optional logs metadata, but this requires no session-format bump: existing records remain valid because presentation reads their durable rendered content. diff --git a/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.zh.md b/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.zh.md index 45047cc5bc..fea162b073 100644 --- a/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-07-20-code-mode-result-card-completeness.zh.md @@ -6,7 +6,7 @@ Status: implemented ## 问题 -外层 `run_code` 工具会持久化完整的渲染内容,但编辑器的卡片展示逻辑忽略了这些内容,转而根据仅含日志的 `presentationMeta` 投影重新构建卡片正文。仅有结果的运行看似正确,是因为展示逻辑未提供正文时,ACP 和 TUI 会回退到 `tool/result.content`。只要程序输出一条日志,展示逻辑就会提供非空内容,回退随即停止,返回值便会从完成态卡片中消失。当已捕获的日志使陈旧投影变为非空时,输出落盘策略最终生成的头尾预览也会受到同一职责拆分的影响。 +外层 `run_code` 工具会持久化完整的渲染内容,但其 UI 展示器忽略了这些内容,转而根据仅含日志的 `presentationMeta` 投影重新构建卡片正文。仅有结果的运行看似正确,是因为展示器正文为空时,消费方会回退到 `tool/result.content`。只要程序输出一条日志,展示器就会提供非空内容,回退随即停止,返回值便会从完成态卡片中消失。当已捕获的日志使陈旧投影变为非空时,输出落盘策略最终生成的头尾预览也会受到同一职责拆分的影响。 嵌套 Code 调用从不生成自己的卡片。因此,仅仅为了重建这一张不完整卡片而给外层调用生成元数据,还掩盖了每次外层调用只生成一张卡片的预期边界。 @@ -22,7 +22,7 @@ Status: implemented 工具单元测试通过规范注册表覆盖仅有日志、仅有结果、日志与结果并存、无输出、结果落盘和失败的结果,然后固定持久内容以及结果展示器不存在这一事实。宿主 mux 回归测试使用仅有调用的展示器,证明结果帧恰好携带一次原始内容,且不含视图。这些案例证明陈旧元数据无法替换最终内容,同时不会让宿主重复该内容。 -无密钥的 ACP 与 TUI Code Mode 快照会执行一个外层程序:程序进行两次嵌套 bash 调用,记录 `captured output`,并返回 `CODE_ONE+CODE_TWO`。两个界面都只显示一张完成态外层卡片,其中包含这两行内容,且没有嵌套卡片。 +无密钥的 ACP(Agent Client Protocol)后端快照与 TUI Code Mode 快照会执行一个外层程序:程序进行两次嵌套 bash 调用,记录 `captured output`,并返回 `CODE_ONE+CODE_TWO`。ACP 持久化日志固定完整结果;TUI 界面只显示一张完成态外层卡片,其中包含这两行内容,且没有嵌套卡片。 ## 备选方案 @@ -30,10 +30,10 @@ Status: implemented **把展示元数据与 `result.content` 合并:**不予采纳。渲染内容已经包含日志;合并会造成重复,还需要依赖脆弱的去重逻辑。 -**通过通用结果展示器转发 `result.content`:**不予采纳。持久事件已经携带该内容,ACP 和 TUI 也已有通用的原始内容回退机制。宿主 mux 会在事件旁序列化工具拥有的结果视图,因此转发仅仅是为了重建该回退机制,却会在一个帧中重复渲染内容;仅默认 worker 在渲染前允许 64 MiB 的可变载荷预算。 +**通过通用结果展示器转发 `result.content`:**不予采纳。持久事件已经携带该内容,UI 消费方也已有通用的原始内容回退机制。宿主 mux 会在事件旁序列化工具拥有的结果视图,因此转发仅仅是为了重建该回退机制,却会在一个帧中重复渲染内容;仅默认 worker 在渲染前允许 64 MiB 的可变载荷预算。 **为每次嵌套分发创建一张卡片:**不予采纳。中间值有意只存在于执行期间,永远不面向模型。多张卡片会暴露实现轨迹,而不是模型与用户调用的单次 Code Mode 操作。 ## 影响 -ACP 和 TUI 通过通用结果回退机制显示与模型接收及回放持久化相同的完整内容,其中包括 post-policy 输出落盘预览。宿主 API 保留待完成的程序标题,同时不在单独的视图负载中重复原始结果。新的 `run_code` 结果不再携带可选的日志元数据,但无需提升会话格式版本:现有记录仍然有效,因为展示逻辑会读取其中持久化的渲染内容。 +TUI 与 JSON-RPC/Web 通过通用结果回退机制显示与模型接收及回放持久化相同的完整内容,其中包括 post-policy 输出落盘预览。宿主 API 保留待完成的程序标题,同时不在单独的视图负载中重复原始结果。新的 `run_code` 结果不再携带可选的日志元数据,但无需提升会话格式版本:现有记录仍然有效,因为展示逻辑会读取其中持久化的渲染内容。 diff --git a/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.i18n.yaml b/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.i18n.yaml new file mode 100644 index 0000000000..26ef840cd0 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-14-acp-agent-client-protocol.md: da23bbfa247bc2423072477cc4b6277485df1c9c +2026-06-14-acp-agent-client-protocol.zh.md: ec55922e0aee57169d8bbf44c3d91b18ea83041e diff --git a/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.md b/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.md index 7c47fc78e9..da23bbfa24 100644 --- a/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.md +++ b/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.md @@ -2,6 +2,10 @@ Status: implemented +English | [中文](2026-06-14-acp-agent-client-protocol.zh.md) + +> Superseded by [ACP as an automation-only protocol](../simplification/2026-07-23-acp-automation-only-protocol.md). This note records the retired editor-facing bridge design. + ## Problem The harness originally exposed agents only through a readline loop. That surface could carry text, but it gave an editor no structured way to create or resume sessions, correlate prompt completion, stream reasoning and tool activity, render tool-specific UI, ask for permission, or cancel one conversation without disturbing another. ACP defines those interactions as JSON-RPC over stdio, and Zed is the target client used to make concrete compatibility decisions. @@ -10,7 +14,7 @@ The bridge must preserve the harness's existing ownership boundaries. It cannot ## Decision -`@deepseek-ai/dsh-acp` is a UI/client-driver plugin under `packages/ui/acp`. It uses `@agentclientprotocol/sdk`'s `AgentSideConnection` over stdin/stdout and programs only interface services: the agent create/resume factory, session persistence, tool registry, user interaction, and optional approval/bash capabilities. It does not change the agent loop and is not a capability-seam implementation. +`@deepseek-ai/dsh-acp` was a UI/client-driver plugin in the `ui` package group (it now lives in `acp`). It used `@agentclientprotocol/sdk`'s `AgentSideConnection` over stdin/stdout and programmed only interface services: the agent create/resume factory, session persistence, tool registry, user interaction, and optional approval/bash capabilities. It did not change the agent loop and was not a capability-seam implementation. The bridge implements the following stable session path: @@ -30,7 +34,7 @@ The bridge also provides the ACP-backed `UserInteractionProvider`: `ask_user_que Lifecycle ownership is explicit. The bridge holds an `AgentHandle` per live session. Disconnect and Cordis disposal cancel pending prompts, dispose every handle in parallel, await loop quiescence and persistence flush, and then remove the records. Stream notification failures are contained so a vanished client cannot corrupt an agent turn. The ACP app composition loads no stdout logger; a test guards stdout as framed JSON-RPC only. -The precise supported and deferred protocol rows live in [`packages/ui/acp/acp-feature-support.md`](../../../../packages/ui/acp/acp-feature-support.md); the package README is the operational contract. +The current protocol contract lives in the [`dsh-acp` package README](../../../../packages/acp/acp/README.md). ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.zh.md b/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.zh.md new file mode 100644 index 0000000000..ec55922e0a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.zh.md @@ -0,0 +1,61 @@ +# Agent Note: Agent Client Protocol(ACP)支持——从外部编辑器驱动编码 agent + +Status: implemented + +[English](2026-06-14-acp-agent-client-protocol.md) | 中文 + +> 已被 [ACP 作为仅面向自动化的协议](../simplification/2026-07-23-acp-automation-only-protocol.md)取代。本 Agent Note 记录已退役的面向编辑器的桥接层设计。 + +## 问题 + +harness 最初仅通过 readline 循环暴露 agent。该接口能传输文本,但编辑器无法以结构化方式创建或恢复会话、关联提示词完成、流式输出推理(reasoning)与工具活动、渲染工具专属 UI、请求权限,或在不干扰其他对话的前提下取消某个对话。ACP(Agent Client Protocol)将这些交互定义为基于 stdio 的 JSON-RPC,Zed 是用于做出具体兼容性决策的目标客户端。 + +桥接层必须保持 harness 既有的所有权边界。它不能依赖具体的 agent loop(智能体循环),不能绕过工具注册表,不能在编辑器中执行 shell 命令,也不能发明第二个会话真源。stdout 同时也是协议传输通道,因此任何意外的日志输出都会破坏连接。 + +## 决策 + +`@deepseek-ai/dsh-acp` 曾是 `ui` 包组中的 UI/客户端驱动插件(现位于 `acp`)。它使用 `@agentclientprotocol/sdk` 的 `AgentSideConnection`(基于 stdin/stdout),仅编排接口服务:agent 创建/恢复工厂、会话持久化、工具注册表、用户交互,以及可选的审批/bash 能力。它不修改 agent loop,也不是能力 seam 的实现。 + +桥接层实现以下稳定的会话路径: + +- `initialize` 协商协议版本,声明支持 text 与 `resource_link` 类型的提示词,并声明 `loadSession` 能力。 +- `session/new` 校验绝对路径 `cwd`,将其存入 `SessionHeader`,通过 `ctx.agents` 创建 agent,并返回由组合层支持的配置选项。 +- `session/load` 在构造 agent 之前校验请求的 cwd 与持久化元数据是否一致,在异步恢复期间保留 id,将用户/助手/工具事件作为 ACP update 回放,并报告恢复后的 config-option 折叠结果。 +- `session/prompt` 接受文本和 resource link,拒绝不支持的或空的内容,每个会话同时只允许一个 in-flight 提示词,并在该提示词所属的 `turn/end` 时结算。错误轮次拒绝 RPC;其他关闭轮次的原因通过一个全覆盖的 ACP stop-reason 编解码器映射。 +- `session/cancel` 调用队列感知的 agent 取消路径,仅结算被寻址会话的提示词。 + +工具调用的展示仍由工具自身负责。工具的 `presentCall` 和 `presentResult` 返回 `generic`、`terminal` 或 `diff` 渲染意图变体;桥接层对该联合类型做 switch 并映射到 ACP。没有 presenter 的工具获得通用回退。Bash 终端卡片使用 Zed 的能力门控约定 `_meta.terminal_info`、`_meta.terminal_output` 和 `_meta.terminal_exit`;harness 仍通过 `ctx.bash` 执行命令,保留沙箱、环境清洗、所有权和 cwd。不支持该扩展的客户端收到普通文本内容。文件系统工具提供 diff 卡片和文件位置,桥接层中无需硬编码工具名分支。 + +权限处理是[用户审批 seam](2026-07-06-approval-seam.md)上的一个 answerer,而非 ACP 中的「每次工具调用都询问」策略。对桥接层所属 agent 且带有 call id 的 `approval/request`,会变为该 agent 编辑器会话上的 `session/request_permission`,提供一次性允许/拒绝选项。外部请求或无 call id 的请求委托给下游;缺失或失败的 answerer 会在故障时保持拒绝。发起询问的插件(如预执行策略或 bash 升级)拥有「是否询问」的决策权。 + +当 `ctx.permission` 被组合时,桥接层从部署的预设表中暴露一个 `permission` select。已发布的 `workspace-write` 和 `danger-full-access` 预设各自捆绑一个沙箱模式与一条审批策略;无法匹配的有效旋钮组合产生只能切走的 `custom` 状态。`session/set_config_option` 通过 `PermissionService.set()` 校验并写入两个所属旋钮事件。在开放轮次中的切换立即追加;空闲时的切换叠加在响应中,并在下一次 `agent/prompt-submit` 时锚定到开放轮次之前的请求组装阶段。在此之前它仅存于内存,因此崩溃后恢复的是持久化的折叠结果。ACP session mode 不被建模,因为 config option 是面向未来的协议表面;`AcpConfig.model` 保持连接级别。 + +桥接层还提供基于 ACP 的 `UserInteractionProvider`:`ask_user_question` 请求变为所属会话上的表单引导。select、multi-select、选项描述与自定义回答覆盖语义均被保留。 + +生命周期所有权是显式的。桥接层为每个活跃会话持有一个 `AgentHandle`。断连和 Cordis dispose(资源释放)会取消待处理的提示词,并行 dispose 所有 handle,等待循环完全停稳与持久化刷写,然后移除记录。流通知失败被隔离,因此消失的客户端不会破坏 agent 轮次。ACP 应用组合不加载 stdout logger;一个测试守卫 stdout 仅包含帧化的 JSON-RPC。 + +当前的协议契约见 [`dsh-acp` 包 README](../../../../packages/acp/acp/README.md)。 + +## 曾考虑的替代方案 + +**在 `tools/execute` 监听器前置一层,对每个 ACP 所属调用都询问权限**:否决。这会将权限策略硬编码到 UI 桥接层,即使没有策略要求也会询问,且无法服务于执行开始后才产生的审批请求。共享的 user-approval seam 将机制、询问策略和 UI answerer 分离。 + +**注入具体的 `agentLoop`**:否决。agent 的创建、恢复、空闲观察与释放是 `dsh-agent` 上的接口级所有权操作;UI 插件不需要依赖规则例外。 + +**通过 ACP `terminal/*` 执行 bash**:否决。这会将执行移到 harness 之外,绕过其沙箱、凭证清洗、任务所有权、cwd 解析与会话日志。终端元数据仅用于展示。 + +**将权限预设表示为 ACP session mode**:否决。部署定义的预设已经是一个 config-option select,而 session mode 是 ACP v2 计划移除的遗留接口。 + +**防御性劫持 stdout**:否决。进程级 monkey-patching 超出 Cordis 副作用所有权范围,且与协议传输存在竞争。应用组合拥有 stdout 纯净性。 + +## 后果 + +编辑器可以通过一条 ACP 连接创建、加载、提交提示词、取消、渲染、询问和重新配置多个 harness 会话,无需依赖特定的循环实现。会话事件日志仍是回放、提示词结算、cwd 与每会话配置的持久真源。工具展示与人工回答通道仍是可扩展的插件契约,而非 ACP 专属行为。 + +桥接层有意不实现会话列表/删除/恢复/关闭能力、MCP 透传、附加目录、图片/音频/嵌入资源提示词、plan、斜杠命令、用量更新、编辑器文件系统委托或 ACP 终端执行子协议。后续已通过标准会话配置选项加入运行时模型选择,见 [LLM 目录与 ACP 选择 Agent Note](../architecture/2026-07-15-llm-model-catalog-and-acp-selection.md)。 + +空闲时的配置选择在实时响应中是真实的,但在下一次 `agent/prompt-submit` 将其锚定到开放轮次之前不具持久性。在该边界之前崩溃会丢失待定选择;这是保持会话事件封闭于轮次内且回放安全的代价。 + +## 验证 + +ACP 测试套件覆盖内存协议编解码器、创建/加载回放、精确的提示词结算、取消竞争、不支持的内容、工具展示、终端能力回退、权限结果映射、config-option 校验与持久化、多会话隔离、断连/释放后的完全停稳,以及 HMR(热模块替换)清理。快照测试与 built-bin 测试验证应用组合,真实 API 的 e2e 测试在无 key 时自动跳过。 diff --git a/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.i18n.yaml b/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.i18n.yaml new file mode 100644 index 0000000000..d4665517a8 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-14-acp-multi-session.md: 088fe984fbc94fe0d8654702d5fce9eb0581cd3b +2026-06-14-acp-multi-session.zh.md: 2a803a6eff9b16b48fb90b2b986f74e762e5419c diff --git a/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.md b/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.md index 91d85aeded..088fe984fb 100644 --- a/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.md +++ b/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.md @@ -2,19 +2,23 @@ Status: implemented +English | [中文](2026-06-14-acp-multi-session.zh.md) + +> Written when ACP was an editor bridge, motivated by Zed's multi-session client model. [ACP as an automation-only protocol](../simplification/2026-07-23-acp-automation-only-protocol.md) removed the editor surfaces; the multiplexing decision itself is unchanged and this note now states it against the automation contract. + ## Problem -An ACP editor can keep several conversations alive over one agent subprocess. A single-active-session bridge would force extra processes and would not match Zed's client model, which tracks multiple session ids and concurrent loads. Multiplexing introduces isolation risks: events, prompt completion, cancellation, permission prompts, config selections, and predictable background-task ids must never cross session boundaries. +An ACP automation client can keep several conversations alive over one agent subprocess. A single-active-session bridge would force extra processes and prevent one parent controller from driving independent children over one connection. Multiplexing introduces isolation risks: committed answers, prompt completion, cancellation, permission requests, and predictable background-task ids must never cross session boundaries. ## Decision -The ACP bridge stores live sessions in `Map<SessionId, SessionRecord>`. Agent-scoped callbacks use `ownedRecord`: look up `agent.session.id` in that forward map and accept the record only when it owns the exact agent object, so a foreign same-id object cannot claim the session. A record owns its agent handle, in-flight prompt, live tool-call presentation state, pending idle config switches, session cwd, and client capability snapshot. A separate loading-id set reserves each id before asynchronous resume so two pipelined loads cannot construct duplicate agents; distinct ids may load concurrently. +The ACP bridge stores live sessions in `Map<SessionId, SessionRecord>`. Agent-scoped callbacks use `ownedRecord`: look up `agent.session.id` in that forward map and accept the record only when it owns the exact agent object, so a foreign same-id object cannot claim the session. A record owns its agent, exact disposer, and optional in-flight prompt with the durable turn number that eventually settles it. The session header owns its cwd; the bridge keeps no parallel workspace or client-capability state. -Every `session/event` and `agent/status` callback resolves the owning record before sending or settling anything. Each session permits one in-flight prompt independently. The prompt records a log watermark, captures its own `turn/start`, and settles only on the matching `turn/end`; a late end from a cancelled prior turn cannot resolve a newer prompt. `session/cancel` addresses one record and calls only that agent's queue-aware cancel path. +Every `session/event` callback resolves the owning record before sending or settling anything. Each session permits one in-flight prompt independently. The prompt captures its own user-sourced message `turn/start` and settles only on the matching `turn/end`; injection turns, autonomous plugin or goal turns, and a late end from a cancelled prior turn cannot resolve it. `session/cancel` addresses one record and calls only that agent's queue-aware cancel path. -Permission ownership uses the same exact-agent check against the forward map. The ACP `approval/request` answerer prompts only the editor session that owns the requesting agent and delegates foreign requests. User-interaction elicitations likewise route by agent ownership. Per-session sandbox and approval config values fold only that session's events, with pending idle switches stored on that record until the next turn anchors them. +Permission ownership uses the same exact-agent check against the forward map. The ACP `approval/request` answerer sends a one-shot machine-policy request only for the session that owns the requesting agent and delegates foreign or call-less requests. The bridge has no elicitation, config-selection, or other human-interaction state. -Background bash tasks carry an opaque owner token equal to the owning session id. `bash_output` and `bash_kill` compare the caller's token with the executor's task ownership before reading or killing; a predictable task id alone grants no access. Ownership is stored with the executor task, so a tool plugin reload does not erase it. +Background bash tasks carry an opaque owner token equal to the owning session id. `task_output` and `task_kill` compare the caller's token with the executor's task ownership before reading or killing; a predictable task id alone grants no access. Ownership is stored with the executor task, so a tool plugin reload does not erase it. Connection teardown clears the live map, settles each pending prompt as cancelled, and disposes all `AgentHandle`s in parallel. Each handle stops and awaits its loop, flushes the session while attached, unregisters the agent, and removes the session. Teardown is memoized and shared by client disconnect and plugin disposal. @@ -22,13 +26,13 @@ Connection teardown clears the live map, settles each pending prompt as cancelle [ACP v1 expressly permits several concurrent sessions on one connection](https://github.com/agentclientprotocol/agent-client-protocol/blob/01beb5fb5eec60e9f516a80d85eb03594bac61e3/docs/get-started/architecture.mdx#L16-L24), and each new session carries its own primary `cwd`. This bridge implements that session-level multiplexing, including different primary workspaces as recorded by the [per-session cwd decision](../architecture/2026-07-02-fs-per-session-cwd.md); it does not create one agent subprocess per session. -A multi-root project inside one session is a separate optional capability: ACP defines the [effective roots as the primary `cwd` plus `additionalDirectories`](https://github.com/agentclientprotocol/agent-client-protocol/blob/01beb5fb5eec60e9f516a80d85eb03594bac61e3/docs/protocol/v1/session-setup.mdx#L313-L367). [Zed sends the remaining project work directories only when the agent advertises that capability](https://github.com/zed-industries/zed/blob/ea77ca2818f3e059a2b61ecc7e63b67e01e1cec5/crates/agent_servers/src/acp.rs#L1139-L1145), otherwise it [drops them from the session request](https://github.com/zed-industries/zed/blob/ea77ca2818f3e059a2b61ecc7e63b67e01e1cec5/crates/agent_servers/src/acp.rs#L1454-L1472). The bridge does not advertise this capability and rejects non-empty values, as recorded in its [known limitations](../../../../packages/ui/acp/README.md#known-limitations-and-deferred-work), so a current Zed multi-root project reaches it with only the first work directory. +A multi-root project inside one session is a separate optional capability: ACP defines the [effective roots as the primary `cwd` plus `additionalDirectories`](https://github.com/agentclientprotocol/agent-client-protocol/blob/01beb5fb5eec60e9f516a80d85eb03594bac61e3/docs/protocol/v1/session-setup.mdx#L313-L367). The automation bridge advertises no multi-root capability and rejects non-empty `additionalDirectories`; each fresh session has exactly one workspace, as recorded in the [package contract](../../../../packages/acp/acp/README.md#protocol-contract). -[The standard transport is one editor-launched agent subprocess per stdio connection](https://github.com/agentclientprotocol/agent-client-protocol/blob/01beb5fb5eec60e9f516a80d85eb03594bac61e3/docs/protocol/v1/transports.mdx#L17-L42); multiple editor connections therefore require multiple subprocesses or a custom transport, while this decision guarantees multiple sessions within one connection. Within that connection, `ctx.sandboxPolicy` resolves every session's `cwd` as its own `workspace-write` root, so the shared bash and filesystem services can serve concurrent projects without granting cross-project writes. This does not add ACP `additionalDirectories`; it removes the process-wide root limit from the already-supported one-primary-root-per-session path. +[The standard transport is one agent subprocess per stdio connection](https://github.com/agentclientprotocol/agent-client-protocol/blob/01beb5fb5eec60e9f516a80d85eb03594bac61e3/docs/protocol/v1/transports.mdx#L17-L42); multiple connections therefore require multiple subprocesses or a custom transport, while this decision guarantees multiple sessions within one connection. Within that connection, `ctx.sandboxPolicy` resolves every session's `cwd` as its own `workspace-write` root, so the shared bash and filesystem services can serve concurrent projects without granting cross-project writes. This does not add ACP `additionalDirectories`; it removes the process-wide root limit from the already-supported one-primary-root-per-session path. ## Alternatives considered -**One live session per connection** — rejected. It adds process overhead and contradicts the target client's multi-session shape without removing multiplexing needs from the editor. +**One live session per connection** — rejected. It adds process overhead and prevents a programmatic parent from multiplexing independently cancellable work. **A per-session `ctx.extend()`** — rejected. A child context does not by itself create a child plugin fiber, so listeners would still belong to the bridge fiber. The implemented bridge instead uses global listeners with explicit O(1) demultiplexing and per-session owned records; agent lifecycle is owned by `AgentHandle`. @@ -36,10 +40,10 @@ A multi-root project inside one session is a separate optional capability: ACP d ## Consequences -N sessions can stream, prompt, request permission, switch config, and run background tasks concurrently without interleaving or cross-settling. A cancel or dispose in one session does not affect its neighbors. The bridge pays for explicit maps and isolation tests, but it does not add one listener set per session and therefore avoids listener fan-out during long-lived connections. +N sessions can return committed answers, prompt, request permission, and run background tasks concurrently without interleaving or cross-settling. A cancel in one session does not affect its neighbors. The bridge pays for explicit maps and isolation tests, but it does not add one listener set per session and therefore avoids listener fan-out during long-lived connections. -The bridge still exposes no protocol method to close one live session independently. Today records leave together on connection teardown; session close/resume lifecycle capabilities remain deferred in the ACP feature checklist. +The bridge exposes no protocol method to close one live session independently. Records leave together on connection teardown; navigation and resume belong to host APIs rather than this automation protocol. ## Verification -The multi-session suite drives concurrent sessions through interleaved updates, independent in-flight prompts, targeted cancellation, same-id and distinct-id load races, permission routing, config isolation, and teardown. Tool-bash tests prove one session cannot read or kill another session's background task. +The multi-session suite drives concurrent sessions through routed committed answers, independent in-flight prompts, targeted cancellation, and shared teardown; the approval and output-boundary suites cover permission routing and exact-agent rejection. Tool-bash tests prove one session cannot read or kill another session's background task. diff --git a/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.zh.md b/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.zh.md new file mode 100644 index 0000000000..2a803a6eff --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-14-acp-multi-session.zh.md @@ -0,0 +1,49 @@ +# Agent Note: 在单个连接上多路复用并发 ACP 会话 + +Status: implemented + +[English](2026-06-14-acp-multi-session.md) | 中文 + +> 本 Agent Note 写于 ACP 还是编辑器桥接层的时期,动机来自 Zed 的多会话客户端模型。[ACP 作为仅面向自动化的协议](../simplification/2026-07-23-acp-automation-only-protocol.md)移除了编辑器接口;多路复用决策本身不变,本 Agent Note 现依照自动化契约陈述它。 + +## 问题 + +一个 ACP(Agent Client Protocol)自动化客户端可以在同一个 agent(智能体)子进程上保持多个对话。如果桥接层只支持单活跃会话,就不得不启动额外进程,也会阻止一个父控制器通过一条连接驱动多个独立子任务。多路复用引入了隔离风险:已提交的回答、提示词完成、取消、权限请求以及可预测的后台 task id 绝不能跨越会话边界。 + +## 决策 + +ACP 桥接层将活跃会话存储在 `Map<SessionId, SessionRecord>` 中。agent 作用域的回调使用 `ownedRecord`:在正向 map 中查找 `agent.session.id`,且仅当该记录拥有精确的 agent 对象时才接纳它,使外部的同 id 对象无法冒领会话。一条记录拥有其 agent、精确的释放器,以及可选的进行中提示词和最终结算它的持久轮次号。会话 header 拥有其 cwd;桥接层不保留平行的工作区或客户端能力状态。 + +每个 `session/event` 回调在发送或结算任何内容之前,先解析出所属记录。每个会话独立允许一个进行中的提示词。提示词捕获自己源自用户消息的 `turn/start`,并仅在匹配的 `turn/end` 到达时结算;注入轮次、插件或 goal 的自主轮次,以及来自已取消的前一轮次的迟到 end 都不能 resolve 它。`session/cancel` 定位到一条记录,只调用该 agent 的队列感知取消路径。 + +权限归属使用对正向 map 的同一精确 agent 检查。ACP `approval/request` 应答器只为拥有发起请求的 agent 的会话发送一次性机器策略请求,并将外部请求或不带 call id 的请求委托出去。桥接层没有表单引导、配置选择或其他人机交互状态。 + +后台 bash 任务携带一个不透明的 owner token,其值等于所属会话 id。`task_output` 和 `task_kill` 在读取或终止之前,将调用方的 token 与执行器的任务归属进行比较;仅凭可预测的 task id 不能获得访问权。归属信息与执行器任务一起存储,因此工具插件重载不会擦除它。 + +连接拆除时清空活跃 map,将每个待处理的提示词以取消状态结算,并并行 dispose(资源释放)所有 `AgentHandle`。每个句柄停止并等待其循环完成、在仍然附着时刷新会话、注销 agent 并移除会话。拆除操作被 memoize 化,由客户端断连和插件 dispose 共享。 + +## 协议与工作区作用域 + +[ACP v1 明确允许一个连接上存在多个并发会话](https://github.com/agentclientprotocol/agent-client-protocol/blob/01beb5fb5eec60e9f516a80d85eb03594bac61e3/docs/get-started/architecture.mdx#L16-L24),每个新会话都携带自己的主 `cwd`。本桥实现该会话级多路复用,其中包括[按会话 cwd 决策](../architecture/2026-07-02-fs-per-session-cwd.md)所记录的不同主工作区;它不会为每个会话创建一个 agent 子进程。 + +一个会话内部的多根项目是另一项可选能力:ACP 把[有效根目录定义为主 `cwd` 加 `additionalDirectories`](https://github.com/agentclientprotocol/agent-client-protocol/blob/01beb5fb5eec60e9f516a80d85eb03594bac61e3/docs/protocol/v1/session-setup.mdx#L313-L367)。自动化桥接层不公布任何多根能力,并拒绝非空的 `additionalDirectories`;如[包契约](../../../../packages/acp/acp/README.md#protocol-contract)所记录,每个全新会话恰好有一个工作区。 + +[标准传输是每个 stdio 连接一个 agent 子进程](https://github.com/agentclientprotocol/agent-client-protocol/blob/01beb5fb5eec60e9f516a80d85eb03594bac61e3/docs/protocol/v1/transports.mdx#L17-L42);多个连接因此需要多个子进程或自定义传输,而本决策保证的是一个连接内部存在多个会话。在该连接内,`ctx.sandboxPolicy` 把每个会话的 `cwd` 解析为其自己的 `workspace-write` 根目录,因此共享的 bash 和文件系统服务可以服务并发项目而不授予跨项目写入。这不会添加 ACP `additionalDirectories`;它只是从已经支持的「每会话一个主根目录」路径中移除了进程级根目录限制。 + +## 曾考虑的替代方案 + +**每连接单活跃会话**:否决。增加进程开销,并阻止程序化的父控制器多路复用可独立取消的工作。 + +**每会话 `ctx.extend()`**:否决。子上下文本身不会创建子插件 fiber,因此监听器仍属于桥接层 fiber。实际实现的桥接层使用全局监听器加显式 O(1) 解复用,以及每会话拥有的记录;agent 生命周期由 `AgentHandle` 管理。 + +**以 Agent 对象标识作为 bash 任务归属**:否决。恢复或替换后的 agent 对象可能合法地代表同一个持久会话。不透明的会话 token 才是跨边界的标识,应当在插件重载后仍然存活。 + +## 后果 + +N 个会话可以并发地返回已提交的回答、提交提示词、请求权限和运行后台任务,而不会交错或跨会话结算。一个会话中的取消不影响相邻会话。桥接层为此付出了显式 map 和隔离测试的代价,但它不会为每个会话添加一组监听器,从而避免了长连接期间的监听器扇出。 + +桥接层不暴露独立关闭单个活跃会话的协议方法。所有记录在连接拆除时一起离开;会话导航与恢复属于 host API,而非这个自动化协议。 + +## 验证 + +多会话测试套件通过按路由投递的已提交回答、独立的进行中提示词、定向取消以及共享拆除来驱动并发会话;审批与输出边界套件覆盖权限路由和精确 agent 拒绝。工具 bash 测试证明一个会话无法读取或终止另一个会话的后台任务。 diff --git a/.agents/notes/implemented/feature/2026-06-15-code-mode.i18n.yaml b/.agents/notes/implemented/feature/2026-06-15-code-mode.i18n.yaml new file mode 100644 index 0000000000..7ee0bfc88c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-15-code-mode.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-15-code-mode.md: 8e964eeb36e430b58312427e45cf8e4a99582457 +2026-06-15-code-mode.zh.md: 3de1adfcf287b69ca8307244bde35f286ce4b99d diff --git a/.agents/notes/implemented/feature/2026-06-15-code-mode.md b/.agents/notes/implemented/feature/2026-06-15-code-mode.md index 0f5e8cc94b..8e964eeb36 100644 --- a/.agents/notes/implemented/feature/2026-06-15-code-mode.md +++ b/.agents/notes/implemented/feature/2026-06-15-code-mode.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-15-code-mode.zh.md) + ## Problem In the registry's native presentation, the agent loop advertises every visible capability as a JSON-schema function definition. `ToolRegistry` contributes its schemas to the system-prompt assembly, the assembly's `tools` land on the wire (and in the logged request header), the model invokes one `tool-call` block per step, and the loop dispatches each call through `ctx.tools.execute()` **sequentially** (parallel tool execution is an explicit open TODO in `dsh-tools` and [docs/architecture.md](../../../../docs/architecture.md)), with **every** intermediate `tool-result` re-entering the model's context on the next request. @@ -48,7 +50,7 @@ Under `'code'` and `'both'` the registry owns `run_code` as a reserved presentat **Concurrency is serialized.** Each run owns a dispatch queue, so even `Promise.all` executes tool calls in submission order. Settlement abandons queued calls that have not started. Parallelism requires per-tool concurrency-safety metadata. -**Presentation.** `run_code`'s render intent is decided here per the [render-intent Agent Note](../architecture/2026-07-02-tool-render-intent-union.md): `presentCall` creates a `generic` card with `kind: 'execute'`, the program text as its title, and the same program text as `rawInput`; `run_code` intentionally declares no `presentResult`, so ACP and TUI complete that card through their generic raw-content fallback using the final durable `tool/result.content`, including captured logs plus the returned value, failure, or post-policy spill preview. The program is the title because ACP execute cards reliably render that field while some clients omit body and raw-input content. This is not a `terminal` card: that card's semantics are "a shell command in a working directory", which a program is not. See the [result-card completeness note](../bug-fix/2026-07-20-code-mode-result-card-completeness.md). +**Presentation.** `run_code`'s render intent is decided here per the [render-intent Agent Note](../architecture/2026-07-02-tool-render-intent-union.md): `presentCall` creates a `generic` card with `kind: 'execute'`, the program text as its title, and the same program text as `rawInput`; `run_code` intentionally declares no `presentResult`, so the TUI and host/client runtime (Web) complete that card through their generic raw-content fallback using the final durable `tool/result.content`, including captured logs plus the returned value, failure, or post-policy spill preview. This is not a `terminal` card: that card's semantics are "a shell command in a working directory", which a program is not. See the [result-card completeness note](../bug-fix/2026-07-20-code-mode-result-card-completeness.md). ### Observability: `tool/code-dispatch` diff --git a/.agents/notes/implemented/feature/2026-06-15-code-mode.zh.md b/.agents/notes/implemented/feature/2026-06-15-code-mode.zh.md new file mode 100644 index 0000000000..3de1adfcf2 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-15-code-mode.zh.md @@ -0,0 +1,133 @@ +# Agent Note: Code Mode——模型针对工具注册表编写 TypeScript + +Status: implemented + +[English](2026-06-15-code-mode.md) | 中文 + +## 问题 + +在注册表的原生呈现方式下,agent loop(智能体循环)将每个可见能力以 JSON Schema 函数定义的形式通告给模型。`ToolRegistry` 将其 schema 贡献给系统提示词组装,组装结果中的 `tools` 落到协议格式(wire format)上(也记录在请求头日志中),模型每步调用一个 `tool-call` 块,循环通过 `ctx.tools.execute()` **逐个**分发每次调用(并行工具执行是 `dsh-tools` 和 [docs/architecture.md](../../../../docs/architecture.md) 中明确标注的 open TODO),且**每一个**中间 `tool-result` 都会在下一次请求时重新进入模型上下文。 + +对于多步工具操作,这种方式 token 开销大且串行。模型无法组合工具——遍历结果集、根据中间值分支、扇出、后处理——每次调用都需要一次完整的模型往返,而每次往返都会把完整的中间结果拖回上下文,不管模型是否需要。 + +Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一种替代方案,基于一个简单的观察:LLM(大语言模型)编写代码的能力优于发出工具调用,因为它们见过数百万行真实代码,而人为构造的工具调用 trace 相对很少。模型不再每步发出一次工具调用,而是针对工具生成的 API 编写一段 TypeScript 程序,程序在沙箱运行时中执行,模型只策展返回的内容——仅限它 print 或 return 的部分——而非所有中间结果。 + +工具呈现属于掌管工具可见性的注册表:如果把第二种呈现方式实现为事后的 waterfall(瀑布式事件)变换,正确性将依赖监听器顺序,并与[可重建请求](../architecture/2026-07-05-reconstructable-requests.md)冲突。执行基底同样属于基础设施而非占位实现:Node `worker_threads` 提供独立 isolate、空环境、堆上限以及对热同步循环的终止能力,同时契合 harness 既有的信任模型(§信任姿态)。 + +## 决策 + +三项决策,各自在下方独立小节中展开: + +1. **Code Mode 是 `ToolRegistry`(`dsh-tools`)的一等呈现模式**,通过经校验的 `mode` 配置选择:`'native'`(默认,贡献可见能力 schema)、`'code'`(注册表仅贡献其保留的 `run_code` 传输通道加一份生成的 SDK `.d.ts` 到系统提示词中)或 `'both'`(原生 schema 加传输通道 + SDK)。注册表在源头塑造其权威贡献;协作式提示词组装的结果仍具权威性,记录在日志中的请求头精确反映该返回的呈现。 +2. **代码执行是一个能力 seam**——`packages/code-runtime/` 包含接口包 `@deepseek-ai/dsh-code-runtime`,拥有 `ctx.codeRuntime`([能力 seam](../architecture/2026-06-13-capability-seams.md);消费方 = `dsh-tools`,core 消费 seam 的先例见 `agent-loop` → `dsh-llm`)。运行时对工具一无所知:它接收一段程序和命名的异步绑定,执行程序,报告 `{ value, logs, error? }`。语言和基底是后端属性,因此未来的 Python 或容器后端只是另一个实现包,而非重新设计。 +3. **交付的实现是 `@deepseek-ai/dsh-code-runtime-worker`**:每次运行 spawn 一个全新的 Node worker 线程,对模型的 TypeScript 进行 type-strip 后执行,绑定通过消息端口桥接,环境为空,堆/输出/时间上限可配置,并支持硬终止。其信任姿态在设计上等同于 bash——无需 unsafe-acknowledgement flag——因为 harness 已经交付了 `dsh-bash-local`,后者以严格*更高*的环境权限执行模型编写的任意 shell 命令。 + +本说明负责定义 Code Mode 的呈现、组合、隔离与结算基础。后续的[类型化工具返回值 Agent Note](2026-07-20-code-mode-typed-tool-returns.md)负责定义生成的输出映射、规范绑定值、`ToolCallError` 和无损外层输出边界。 + +### 注册表拥有模式 + +`ToolRegistry` 获得一个经 schemastery 校验的配置(`static Config`),这是它的第一个配置:`mode: 'native' | 'code' | 'both'`,默认 `'native'`。部署通过 `cordis.yml` 翻转模式(`tools: { mode: code }`),无需改代码,遵循 no-hardcoded-tunables 约定。 + +**协议工具列表。** 注册表在 `'native'` 下贡献可见能力,在 `'code'` 下仅贡献 `run_code`,在 `'both'` 下两者都贡献。最终的 `PromptAssembly.tools` 列表记录在请求头中。`run_code` 是一个保留的呈现传输通道,位于注册和限制层之外;直接提示词提供方和组装 waterfall 仍各自负责自己的贡献。 + +**与 `toolOrder` 的交互,预先说明:** 如果配置的 `systemPrompt.toolOrder` 引用了原生能力名称,在 `mode: 'code'` 下会拒绝所有组装,因为那些名称不在该模式的协议校验范围内。这是正确行为而非 bug:使用 Code Mode 的部署需要更新其 order 配置或移除它。 + +**SDK 提示词段。** 在 `'code'` 和 `'both'` 下,tool-guidance order band 中的惰性 `tools:sdk` 段为当前 scope 的可见能力渲染 TypeScript 声明加固定的使用说明。它共享查找和执行可见性,排除 `run_code`,并按字典序排列工具以获得字节稳定的输出。 + +**组装所有权。** `run_code` 和 `tools:sdk` 作为正常的组装输入进入受信任的 `system-prompt/assemble` waterfall。一个 scoped 的 `tools:sdk` 段可以在分发前遮蔽全局默认值,监听器也可以移除或替换任一贡献。waterfall 返回的组装结果是最终的,因此修改这些输入的人有责任在部署期望 Code Mode 可用时保持协议面的完整性;没有恢复 pass 会覆盖有意的组合。 + +**代码生成。** `jsonSchemaToTs()` 将 `defineTool` 的 JSON Schema 子集映射为 TypeScript,将 schema 描述带入 JSDoc,不支持的构造降级为 `unknown`。SDK 将工具暴露为带引号的对象键,支持任意名称而无需别名或冲突处理。类型是建议性的,因为运行时在执行前会剥离类型。 + +### run_code 工具与分发桥 + +在 `'code'` 和 `'both'` 下,注册表拥有 `run_code` 作为保留的呈现传输通道,带一个必需参数 `{ code: string }`。它由一个正常的 `ToolDefinition` 表示以供分发,但位于可过滤的能力层之外,因此限制规则不会意外移除 Code Mode 的唯一入口。调用遍历完整的工具流水线——`tools/pre-execute` → 单调守卫 → `tools/execute` 包裹分发 → `tools/post-execute` → 由定义拥有的可选 `finalizeContent` → 不可变的 `tools/result` 通知——与原生调用完全一致;权限插件可以在程序运行前检查程序文本,最终结果观察者看到的是规范化的外层结果。其 `execute(args, exec)`: + +1. **构建绑定。** 一个 run 级别的 signal 跟随外层取消,并在 run 结算时被 abort。每个可见工具绑定都会对无损 JSON 参数创建快照,等待序列化队列,以确定性的 call id 和外层 token 作为 `parent` 执行,通过外层 execution 延后返回的上下文,并记录 `tool/code-dispatch`。成功时返回工具最终的规范 JSON 值;失败则变为程序可见的 `ToolCallError`。每个子调用保留自己不可变的执行标识,并遍历完整的工具流水线。 +2. **运行程序**:`ctx.codeRuntime.run({ program: args.code, bindings: [{ global: 'tools', functions }], signal: runController.signal })`。运行时接收的是 run 级别的 signal 而非仅调用方的外层 signal,因此外层 run 以任何方式结算都会同时 abort 运行时内部的工作。 +3. **完全停稳后结算。** 运行时结算后,桥 abort 未完成的工作并排空分发队列后再返回。成功时返回捕获的日志和完成值,将其作为规范输出;注册表再把该值渲染为持久化的 `tool/result.content`,供结果卡片直接读取。运行时失败变为 `CodeRunFailedError`;后端拒绝使用注册表的正常错误边界。两者都产生结构化的错误结果,且 `run_code` 结算后不允许子调用追加。 + +**子调用上下文通过父调用延后。** 在 `run_code` 内部注入会破坏父调用/结果的相邻性,因此 `ToolRunContext.deferContext()` 按分发顺序收集每个子结果的 `additionalContexts` 条目。即使程序后来抛出异常,注册表仍携带该数组;循环只在外层结果与步骤中所有兄弟结果之后追加每个条目。外层 post-execute 阻止会丢弃工具延后的条目,只暴露阻止 decision 显式附加的上下文。 + +**并发被序列化。** 每次 run 拥有一个分发队列,因此即使 `Promise.all` 也按提交顺序执行工具调用。结算时放弃尚未开始的排队调用。并行化需要每个工具的并发安全元数据。 + +**呈现。** `run_code` 的 render intent 按[呈现意图 Agent Note](../architecture/2026-07-02-tool-render-intent-union.md)在此决定:`presentCall` 创建一个 `generic` 卡片,`kind: 'execute'`,以程序文本作为标题,并将同一程序文本作为 `rawInput`;`run_code` 有意不声明 `presentResult`,因此 TUI 和宿主/客户端运行时(Web)会通过通用原始内容回退机制,使用最终持久化的 `tool/result.content` 补全该卡片,其中包括捕获的日志,以及返回值、失败信息或 post-policy 输出落盘预览。这不是 `terminal` 卡片:该卡片的语义是「工作目录中的 shell 命令」,程序不是。参见[结果卡片完整性说明](../bug-fix/2026-07-20-code-mode-result-card-completeness.md)。 + +### 可观测性:`tool/code-dispatch` + +每次子分发追加一个仅日志的 `tool/code-dispatch` 事件,包含父子 call id、工具标识、规范化参数和结果摘要。它不进入模型历史,但可供持久化和 UI 使用。追加发生在开放的 `run_code` 轮次内。没有 agent 的直接执行仍然运行,但无法记录该事件。 + +### code-runtime seam + +`packages/code-runtime/code-runtime/`——`@deepseek-ai/dsh-code-runtime`,仅依赖 `cordis`。一个抽象的 `CodeRuntime extends Service`(`super(ctx, 'codeRuntime')`)加上词汇: + +- `CodeRunRequest = { program: string; bindings: CodeBindingNamespace[]; signal?: AbortSignal }` +- `CodeBindingNamespace = { global: string; functions: Record<string, (args: unknown) => Promise<CodeJsonValue>>; errorClass?: { name: string; memberNameProperty: string } }`——运行时将每个命名空间作为程序内部的全局异步函数对象暴露;可选描述符要求运行时注入真正的、程序可见的 reject 类,而无需让 seam 获知消费方专用名称。`CodeJsonValue` 是这个低依赖 seam 的结构化无损 JSON 类型,因此绑定参数与解析值可以完整跨越实现的序列化边界。 +- `CodeRunResult = { value?: CodeJsonValue; logs: string[]; error?: CodeRunFailure }`——程序执行失败时,执行 promise 仍会 fulfill,并通过 `error` 字段返回失败结果。只有调用方/seam 误用(例如重复的绑定命名空间)时,`run()` 才会 reject;消费方仍在自己的错误边界处理不合规后端的拒绝。 +- `CodeRunFailure = { kind: 'exception' | 'timeout' | 'abort' | 'worker-exit' | 'invalid-output' | 'output-limit'; message: string }`——按[防御性模式](../../../../docs/defensive-patterns.md)独立报告的正交结果;超时的 run 不是异常,abort 不是超时,有损完成值不是溢出,基底退出也与上述情况相互独立。 +- 两个只读的后端描述符,仅供信息参考而非门禁判定:`language`(程序必须使用的语言——交付的后端为 `'typescript'`;Python 后端会声明自己,并在呈现侧配对自己的 SDK 生成器)和 `isolation`(交付的后端为 `'worker-thread'`;未来可为 `'process'`、`'container'` 等)。`dsh-tools` 在 MVP 中要求 `language === 'typescript'`——其代码生成输出 TS——否则组装会大声失败,与 `toolOrder` 违规时的配置错误惯用法相同(如 `mode` 为非 native 但根本没有加载 `ctx.codeRuntime`)。 + +请求包含所有运行时输入;实现方拥有经校验的超时和上限默认值。注册表仅在组装 Code Mode 时查找可选的运行时,因此 native 模式不依赖它。缺失或语言不兼容的运行时会大声失败。替代基底或语言可以在同一 seam 背后替换实现,配对相应的 SDK 生成器。 + +### worker-thread 运行时 + +`@deepseek-ai/dsh-code-runtime-worker`,`packages/code-runtime/` 组的第二个包(package)。每次 `run()`: + +1. **宿主侧 type-strip**,使用 Node 内置的 `stripTypeScriptTypes`(`node:module`;在本仓库的整个引擎范围 `^22.19.0 || >=24.0.0` 内可用,且保持位置不变,因此运行时错误行号与模型源码一致)。仅剥离模式拒绝不可擦除的语法(`enum`、namespaces)——该拒绝以 `error.kind: 'exception'` 加 Node 的消息返回,SDK 说明写明「仅限可擦除 TypeScript」,模型像处理其他程序错误一样自我修正。语法级失败不会 spawn worker。 +2. **每次 run spawn 一个全新 `Worker`**,来自包自身的 bootstrap 模块:`env: {}`(真正为空——比 spawn 命令的 scrubbed-env 规则更严格),`resourceLimits` 来自配置,`stdout`/`stderr` 捕获到 `logs` 而非继承。不做池化,不跨 run 保留状态:程序的世界随 worker 消亡,这使得 run 仅从日志即可重建,状态泄漏不可表达。 +3. **在 bootstrap 中执行**:剥离后的程序成为一个 `AsyncFunction` 的函数体,其参数是绑定全局变量、消费方声明的 reject 类和一个捕获式 `console` shim,因此顶层 `await` 和 `return` 可用。Code Mode 声明 `ToolCallError`,成员属性为 `toolName`;运行时无需硬编码工具即可实体化真正的构造函数。无损 JSON 完成值会精确跨越边界;`undefined` 仍表示缺席,有损值产生 `invalid-output`,过大的外层结果产生 `output-limit`,而不会退化为检查格式化后的字符串替代品。 +4. **通过消息端口桥接绑定**:worker 中的每个绑定函数发送 `{ id, global, name, args }` 并等待回复;宿主根据请求的绑定校验名称、调用、并回复 `{ id, ok, value }` 或 `{ id, ok: false, message }`(宿主侧绑定拒绝变为程序侧 rejection)。worker 侧的命名空间对象通过 `defineProperty` 构建为 null-prototype,因此名为 `__proto__`、`constructor` 或 `toString` 的绑定是普通自有属性,而非原型链碰撞。未知名称、重复 id 和结算后消息被拒绝或忽略——端口协议假设对端是恶意的,因为对端运行的是模型代码。 +5. **强制独立预算。** `computeMs` 计量 worker 忙碌时间,允许慢速的 awaited 工具而不放过热循环。`maxWallMs` 约束总经过时间,包括未解析的等待。`maxOutputBytes` 只约束序列化后的外层日志、完成值或诊断的组合;中间绑定值没有字节数上限。到期、取消和完成都终止 worker,堆退出或外层溢出会作为显式失败报告。 +6. **dispose 至完全停稳**:服务自身的 dispose(资源释放)终止进行中的 worker 并*等待*其退出后再 resolve,遵循[防御性模式](../../../../docs/defensive-patterns.md)。 + +### 信任姿态 + +worker 运行时提供的是隔离,而非安全边界:模型代码可以访问 Node API,权限与 bash 工具相当。`worker.terminate()` 停止线程但不停止它 spawn 的 OS 进程。Code Mode 使用与 bash 相同的 `tools/pre-execute` 策略门禁,并额外提供空环境、堆限制、独立 isolate 和对程序本身的硬终止。需要硬多租户边界的部署需要为代码和 bash 都使用容器级后端;运行时的 isolation 描述符让它们能区分该后端。 + +### 模型看到的内容 + +SDK 指示模型编写一个异步的可擦除 TypeScript 函数体,通过 `await tools.name(args)` 调用工具,在需要时捕获被拒绝的工具调用,并仅 return 或 log 应重新进入上下文的输出。即使在 `Promise.all` 下调用仍保持顺序。声明前缀可能与原生 schema 一样大,尤其在 `'both'` 下,但对提供方缓存保持稳定。 + +## 后果 + +切换到 `'code'` 的部署必须更新任何仅限 native 的 `toolOrder`。组装监听器有责任维护任何被重写的协议面的完整性。子分发保持序列化,而每次调用的上下文会通过外层结果保留其 source、信封与元数据。 + +## 测试 + +- **Worker 运行时:** 真实 worker 测试覆盖类型化的绑定值与失败、每一种无损 JSON 根类型的完成值、无效和超限输出、精确的组合账本边界、compute 和 wall 预算、恶意绑定流量、空环境以及 dispose 至完全停稳。一个构建后包测试在纯 Node 下运行 worker 入口。 +- **注册表集成:** 测试覆盖代码生成、所有呈现模式、保留名称和限制规则、scoped 可见性、权威组装重写、`toolOrder`、运行时兼容性失败、完整流水线子分发、parent-token 关联、序列化、取消和队列排空、JSON 规范化、错误传播、日志事件、成功与失败程序中的有序上下文延后、外层阻止抑制以及 HMR(热模块替换)清理。 +- **带密钥 e2e:** 真实模型在一个程序中组合两次 bash 调用;另一个模型通过 Code Mode fs 分发发现嵌套的工作区指令。测试验证折叠的请求头、关联的分发事件、结果文件、延后上下文和模型行为。 +- **快照:** `code-mode-turn`、`both-mode-turn` 和 `code-mode-workspace-context` fixture(测试前置数据)固定 SDK 文本、请求头工具列表、分发事件、延后上下文和结果卡片。 + +## 曾考虑的替代方案 + +**一个零核心改动的附加消费方插件。** 否决,因为 `agent/request` 在[可重建请求](../architecture/2026-07-05-reconstructable-requests.md)下仅限 call-config,而变换已组装的工具列表需要在不拥有其配置的情况下撤销 `toolOrder` 规范化,并依赖监听器顺序。向模型提供哪些工具、以何种表示形式提供,是注册表的单一关注点:原生 schema 和 SDK 是同一个可见存储的两种投影。 + +**`node:vm` 作为参考运行时,加固推迟。** 否决:`node:vm` 不是隔离(原型链逃逸可达宿主 realm)且无法中断热循环。worker 线程提供独立 isolate、空环境、`resourceLimits` 和可靠的 `terminate()`,信任等级等同于 bash,因此参考实现和生产实现是同一个包,无需 unsafe-acknowledgement 仪式。 + +**在原生工具调用上做结果省略/摘要。** 仅解决问题的上下文膨胀一半:裁剪旧 `tool-result` 作为可重建请求下的日志化表面替换成本低,但仍需每次调用一次模型往返,且无法表达循环、分支或汇合。互补而非竞争;它可以在 Code Mode 下为残余的原生调用分层。 + +**循环中的并行原生分发。** 往返成本的另一个答案;仍是有效的未来工作(open TODO),仍被并发安全元数据阻塞,且仍无组合能力——它并行化的是模型在一步中已经决定的调用。Code Mode 的序列化队列决策保持两者兼容:当元数据就绪时,原生并行分发和每工具绑定并行化一起解锁。 + +**始终排他(忠于 Cloudflare,无模式)。** 否决,因为本 SDK 的主要消费方是编码 agent:其日常的单次调用(`bash`、`read`、`edit`)作为原生调用已经是最优的,强制每次编辑都通过程序会给常见场景增加负担。mode 配置让忠实形式(`'code'`)只需一行配置即可启用,而不强加于人。 + +**每工具可见性分层(此工具 native,彼工具 code-only)。** 推迟:它需要每工具元数据和 `'native' | 'code' | 'both'` 不提供的呈现拆分,且其设计取决于模型在 `'both'` 下如何分配使用的证据。 + +**SDK 中的清洁化标识符别名**(`my-tool` → `my_tool`,Cloudflare 的做法)。否决:`declare const` 上的带引号键使每个名称可达,零别名碰撞逻辑;模型能正常处理 `tools["my-tool"](…)`。 + +**REPL 风格的持久内核**(状态跨 `run_code` 调用存活)。在 MVP 中否决:跨调用状态对会话日志不可见,破坏了「每个请求是日志的纯函数」这一可重建性保证;每次 run 全新保持了这一点。内核风格的后端在未来仍可通过同一 seam 表达,配合自己的日志方案。 + +## 风险 + +**Worker 不是硬安全边界。** 有意为之且已文档化(§信任姿态):姿态等同于既有的 bash 工具,隔离程度超过它,门禁使用相同的 seam。需要更强隔离的部署需要未来的 `isolation: 'container'` 后端——作为 seam 设计的扩展点跟踪,而非本设计的 TODO。 + +**`stripTypeScriptTypes` 标记为 experimental。** 它与 Node 自身原生 `.ts` 执行背后的引擎(amaro/swc)相同,在本仓库的整个引擎范围内作为 API 暴露。缓解措施:运行时的单元测试套件固定了所依赖的行为(位置保持、可擦除限制的拒绝消息形状宽松匹配),调用位于一个私有函数之后,且 `amaro`/`sucrase` 是 API 变化时的直接替代品。仅可擦除子集是面向模型的契约线,错误路径是一个可工作的反馈循环,而非死胡同。 + +**SDK 的提示词成本,尤其在 `'both'` 下。** `.d.ts` 可能与它补充的原生 schema 体量相当;`'both'` 携带两种表示。前缀稳定性 + 提供方缓存摊销了每会话成本;mode 是每部署的;本 Agent Note 不做无条件节省的声明。何时优先使用哪种模式的量化指导明确属于上线后学习。 + +**注册表 scope 增长。** `dsh-tools` 吸收了代码生成、一个工具、一个桥和一个事件。通过包内的模块边界(`ts-types.ts`、`code-mode.ts` 与 `schema.ts`/`json-schema.ts`/`presentation.ts` 并列)和 seam 约束:所有基底相关的内容都在 `ctx.codeRuntime` 之后。 + +**大型无损 JSON 值可能耗尽内存。** 工具绑定会在分发前对无损 JSON 创建快照,并完整返回规范 JSON 解析值。运行时会校验 worker 端口两侧,但不对单次绑定设置字节数上限;结构化克隆成本以及进程或 worker 内存构成实际边界。只有包含日志、完成值和失败诊断的组合外层输出账本受字节数上限约束。 + +**仅序列化的子分发。** `Promise.all` 尚未获得挂钟并行性,仅减少往返次数;模型可能过度期望。说明中已声明;解除此限制与原生并行分发 TODO 所需的并发安全元数据绑定。 + +**预算计量读取事件循环,而非 flag。** 忙碌时间轮询(`eventLoopUtilization()`)比精确 CPU 计量更粗糙——预算到期最多延迟一个轮询间隔——且其正确性声明(「pending 的分发不能暂停它」)对恶意程序是承重的。两侧都有单元测试(带 pending 诱饵分发的热循环在 `computeMs` 处死亡;在慢绑定上空闲的程序存活到 `maxWallMs`),轮询间隔是内部常量而非配置——部署无法将其误调为绕过手段。 diff --git a/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.i18n.yaml b/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.i18n.yaml new file mode 100644 index 0000000000..60a0b50006 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-17-filesystem-tool-schemas.md: 9941b3916b361a916c8148eb099eb8cfd46371c8 +2026-06-17-filesystem-tool-schemas.zh.md: 47e43c47db83b1fcc292b17cf0113d9abd9293d1 diff --git a/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.md b/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.md index 59bf9be768..9941b3916b 100644 --- a/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.md +++ b/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-17-filesystem-tool-schemas.zh.md) + ## Problem [The filesystem capability-seam Agent Note](../architecture/2026-06-17-filesystem-capability-seam.md) defines the filesystem capability seam (`ctx.fs`), the package split (`dsh-fs`, `dsh-fs-local`, `dsh-tool-fs`, plus the `dsh-fs-policy` policy plugin), and the observed-file/stale-version policy for read-before-write/edit checks — which the [split-fs-seam](../simplification/2026-06-26-fsspec-style-fs-seam.md) and [event-gate](../architecture/2026-06-26-file-context-as-event-gate.md) Agent Notes moved off `ctx.fs` into the `dsh-fs-policy` plugin on the `fs/*` event gate. The remaining decision for the first filesystem tool delivery is the model-facing schema surface: what arguments the model sees for `read`, `write`, and `edit`. diff --git a/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.zh.md b/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.zh.md new file mode 100644 index 0000000000..47e43c47db --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.zh.md @@ -0,0 +1,112 @@ +# Agent Note: 文件系统工具 schema——面向模型的读/写/编辑接口形状 + +Status: implemented + +[English](2026-06-17-filesystem-tool-schemas.md) | 中文 + +## 问题 + +[文件系统能力 seam Agent Note](../architecture/2026-06-17-filesystem-capability-seam.md) 定义了文件系统能力 seam(`ctx.fs`)、包(package)拆分(`dsh-fs`、`dsh-fs-local`、`dsh-tool-fs`,加上 `dsh-fs-policy` 策略插件),以及针对 read-before-write/edit 检查的 observed-file/stale-version 策略——[拆分文件系统 seam](../simplification/2026-06-26-fsspec-style-fs-seam.md)和[事件门控插件](../architecture/2026-06-26-file-context-as-event-gate.md) Agent Note 后来将其从 `ctx.fs` 移至 `dsh-fs-policy` 插件的 `fs/*` 事件门上。首次文件系统工具交付剩余的决策是面向模型的 schema 接口:模型在 `read`、`write` 和 `edit` 中看到哪些参数。 + +该 schema 应足够小,以便在 `dsh-tool-fs` 的首次实现中完成,但又足够稳定,使未来的本地/远程/沙箱文件系统后端不需要改动面向模型的接口。同时应避免从参考系统中照搬所有选项。Claude Code 和 OpenCode 暴露了类似的核心文件工具,但在命名风格和额外 flag 上有所不同;本 Agent Note 为原型选择最小的共有接口。 + +## 决策 + +`@deepseek-ai/dsh-tool-fs` 在首个文件系统工具套件中暴露以下三个面向模型的工具: + +| 工具 | 我们的 schema | Claude Code | OpenCode | 说明 | 原型包含 | +|---|---|---|---|---|---| +| `read` | `read(file_path, offset?, limit?)` | `Read(file_path, offset?, limit?, pages?)` | `read(filePath, offset?, limit?)` | 仅文件;`offset` 从 1 开始;首版不支持图片、PDF 或多模态内容。 | 是 | +| `write` | `write(file_path, content)` | `Write(file_path, content)` | `write(content, filePath)` | 创建或覆盖 UTF-8 文本。在默认 fs-policy 下,更新现有文件前必须先观测;创建新文件则不需要。 | 是 | +| `edit` | `edit(file_path, old_string, new_string, replace_all?)` | `Edit(file_path, old_string, new_string, replace_all?)` | `edit(filePath, oldString, newString, replaceAll?)` | 字面字符串替换;默认要求唯一匹配;在默认 fs-policy 下必须先观测(任意窗口读取均算作观测)。 | 是 | + +schema 使用 snake_case 字段名(`file_path`、`old_string`、`new_string`、`replace_all`),与 Claude Code 及现有 DeepSeek Harness 工具 schema 示例保持一致。消费方包将这些面向模型的名称转换为 `ctx.fs` 调用和 `fs/*` 事件分发。 + +## 工具 schema + +### `read` + +`read` 检视一个 UTF-8 文本文件并返回带行号的内容。 + +参数: + +- `file_path: string`——必填。要读取的路径,由 `ctx.fs` 解析。 +- `offset?: number`——可选。返回的第一行,从 1 开始。默认为第一行。 +- `limit?: number`——可选。返回的最大行数。默认值与上限是 `dsh-tool-fs` / `ctx.fs` 的实现细节。 + +首次实现不涉及的内容: + +- 无 PDF `pages` 参数。 +- 无图片或多模态文件读取。 +- 不通过 `read` 列出目录;如有需要,目录列表将作为单独的后续工具。 + +### `write` + +`write` 创建或完整替换一个 UTF-8 文本文件。 + +参数: + +- `file_path: string`——必填。要写入的路径,由 `ctx.fs` 解析。 +- `content: string`——必填。要写入的完整 UTF-8 文本内容。 + +在默认 fs-policy 下,使用 `write` 更新已有文件需要同一执行上下文先前对该文件有过一次观测(read/write/edit);`dsh-fs-policy` 插件将观测到的版本作为 `fs/write-intent` 上的 stale guard 提供。创建新文件不需要先前观测。如果策略插件不存在,`write` 是无条件的裸提供方 create-or-overwrite。 + +schema 不将 `expected_hash`、`expected_version` 或 `create_only` 作为面向模型的参数暴露。陈旧版本检查由后端产生的版本和策略插件的观测状态驱动,而非要求模型通过 schema 复制版本令牌。 + +### `edit` + +`edit` 通过替换字面文本来更新已有的 UTF-8 文本文件。 + +参数: + +- `file_path: string`——必填。要编辑的路径,由 `ctx.fs` 解析。 +- `old_string: string`——必填。要替换的字面文本。首次实现中空字符串无效。 +- `new_string: string`——必填。字面替换文本;空字符串表示删除匹配内容。 +- `replace_all?: boolean`——可选。默认为 false。为 false 时,`old_string` 必须恰好匹配一处。 + +`edit` 要求同一执行上下文先前对该文件有过一次观测(任何窗口化的 read 都算——授权基于版本新鲜度,而非全文查看要求),或该上下文先前对该文件做过 write/edit。`dsh-fs-policy` 策略插件推导所有者并将记录的版本作为 stale guard 提供;提供方的 mutation lock 负责执行。 + +首次实现拒绝 Codex 风格的 patch 语法和多模式 edit API。它使用一种严格的字面替换模式,使面向模型的契约保持简单,并让后端掌控精确匹配、重复匹配、行尾和陈旧版本的语义。 + +## 结果形状 + +首次实现曾将 `ContentBlock[]` 格式化逻辑放在 `execute` 中。[规范工具输出契约](../architecture/2026-07-20-canonical-tool-output-contract.md)如今将 `ctx.fs` 的结果事实保留为工具经校验的值,并通过 `output.render` 派生相同的模型文本;文件状态的记录/刷新仍归 `ctx.fs` 所有。 + +默认原生投影: + +| 工具 | `tool-fs` 使用的结构化 `ctx.fs` 结果 | 默认模型投影 | +|---|---|---| +| `read` | 返回的行、返回行数、总行数、目标显示路径、文件版本、部分视图标记 | 带行号的文本及分页页脚 | +| `write` | 创建/更新操作、目标显示路径、新文件版本 | 简洁的创建/更新成功文本 | +| `edit` | 替换次数、全量替换标记、目标显示路径、新文件版本 | 简洁的编辑成功文本 | + +结构化结果不会重复模型参数(如 `file_path`、`old_string` 或 `content`),除非后端已将其解析为新信息(如 `displayPath`、`targetKey` 或新版本)。面向 token 的截断属于模型投影的职责,而非后端规范结果的一部分。 + +## 延后事项 + +以下内容被明确排除在首次文件系统 schema 实现之外: + +- 面向模型的 `expected_hash`、`expected_version` 或 `create_only` 参数。 +- 目录列表、glob、grep 和搜索工具。 +- 二进制安全的读/写操作。 +- PDF/图片/多模态 `read`。 +- 文件系统工具的 Code Mode 投影值。 +- 规范的 edit diff 格式。 + +## 测试 + +schema 测试固定每个工具的必填/可选参数集、空 `old_string` 拒绝、`replace_all` 默认值、snake_case 字段名、描述文字中对观测策略的说明,以及根插件套件注册;集成测试通过 `ctx.tools.execute()` 对真实的 `dsh-fs-local` 提供方执行全部三个工具,并验证模型参数被正确转换为预期的 `ctx.fs` 调用和 `fs/*` 分发。 + +## 曾考虑的替代方案 + +- **Codex 风格的 patch 语法或多模式 edit API**:否决。一种严格的字面替换模式使面向模型的契约保持简单,并让后端掌控精确匹配、重复匹配、行尾和陈旧版本的语义。 +- **camelCase 参数名(OpenCode 风格)**:snake_case 与 Claude Code 及现有 harness 工具 schema 示例一致,且命名一旦发布即成为公开接口。 +- **面向模型的 `expected_hash` / `expected_version` / `create_only` 参数**:否决。陈旧检查由后端产生的版本和策略插件的观测状态驱动,从不依赖模型复制的脆弱令牌。 + +## 后果 + +**首版 schema 有意小于 Claude Code 的。** 去掉 PDF pages、多模态 read、丰富的 grep/list flag 和 expected hash 字段使实现保持聚焦,但用户可能很快就会提出这些需求。它们将以独立 Agent Note 或聚焦的后续工作形式到来,而非对初始 schema 的重载。 + +**v1 中没有显式的面向模型的 stale guard。** schema 不要求模型提供 expected hash/version。这是有意为之:陈旧检查来自后端产生的版本和 `dsh-fs-policy` 插件的观测状态,而非模型复制的脆弱令牌。文件系统安全失败通过 `dsh-fs` 拥有的结构化 `FsError` 代码浮现,而非模型提供的版本字段。 + +**命名成为公开接口。** 一旦发布,将 `file_path` 改为 `filePath` 或 `old_string` 改为 `oldString` 会搅动提示词、示例和下游客户端。本 Agent Note 预先选择 snake_case,并将其视为稳定的面向模型的契约。 diff --git a/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.i18n.yaml b/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.i18n.yaml new file mode 100644 index 0000000000..f9049645c3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-18-acp-terminal-and-tool-rendering.md: e8426dbf1a0e3e4f9d9857baa19945cee6eee4b3 +2026-06-18-acp-terminal-and-tool-rendering.zh.md: ff269e002a0ecea8c0bacf53fe85e553a6b9b9d5 diff --git a/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md b/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md index 8d9c0197eb..e8426dbf1a 100644 --- a/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md +++ b/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md @@ -2,6 +2,10 @@ Status: implemented +English | [中文](2026-06-18-acp-terminal-and-tool-rendering.zh.md) + +> Superseded for ACP by [ACP as an automation-only protocol](../simplification/2026-07-23-acp-automation-only-protocol.md). Tool render intents remain available to UI transports, but ACP no longer projects them into terminal cards. + ## Problem The ACP bridge lets each tool own its call rendering via `presentCall`/`presentResult` (see [tool-call UI presentation](2026-06-14-acp-agent-client-protocol.md) and `packages/core/tools`). For `bash` we surface the exact command as the `tool_call` title, the model's `description` as a content text block, `kind: 'execute'`, and the completed output wrapped in a fenced ` ```console ` text block. diff --git a/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.zh.md b/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.zh.md new file mode 100644 index 0000000000..ff269e002a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.zh.md @@ -0,0 +1,50 @@ +# Agent Note: 富 ACP bash 渲染——通过 `_meta` 约定实现终端卡片 + +Status: implemented + +[English](2026-06-18-acp-terminal-and-tool-rendering.md) | 中文 + +> 就 ACP 而言已被 [ACP 作为仅面向自动化的协议](../simplification/2026-07-23-acp-automation-only-protocol.md)取代。工具渲染意图对 UI 传输层仍然可用,但 ACP 不再将其投影为终端卡片。 + +## 问题 + +ACP(Agent Client Protocol)桥接层允许每个工具通过 `presentCall`/`presentResult` 自行控制调用渲染(见[工具调用 UI 呈现](2026-06-14-acp-agent-client-protocol.md)与 `packages/core/tools`)。对于 `bash`,我们将确切命令作为 `tool_call` 标题呈现,模型的 `description` 作为一个内容文本块,`kind: 'execute'`,完成后的输出包裹在 ` ```console ` 围栏文本块中。 + +参考编辑器将终端元数据渲染为一张专用卡片,包含 cwd、命令、实时风格的输出和退出状态;纯文本则丢失了这些结构。命令之所以作为标题,是因为执行卡片隐藏原始输入,而人类可读的描述保留为卡片上方的独立块。 + +## 关键发现:agent 执行的终端使用 `_meta` 约定,而非 `terminal/create` + +ACP 规范有一个*客户端侧*终端子协议:agent(智能体)调用客户端的 `terminal/create`(传入 `{ command, args, cwd, env }`),由**编辑器**执行进程,然后 agent 读取 `terminal/output` / `wait_for_exit`。这个模型不适合我们:我们的 harness 通过 `dsh-bash` 自行执行 bash(沙箱化的环境清理、后台任务所有权、按会话的 cwd)。将执行路由到编辑器会绕过所有这些机制,并将执行分叉到两个后端。 + +研究两个参考 agent(2026-06-18)发现,二者都没有为自己的 shell 工具使用 `terminal/create`——**两者都保持 agent 侧执行,并发出一套 `_meta` 约定**,由 Zed 特殊处理: + +- **`claude-agent-acp`**(`tools.ts`、`acp-agent.ts`):以 `clientCapabilities._meta.terminal_output` 为门控。`tool_call` 携带 `content: [{ type: 'terminal', terminalId }]` 与 `_meta.terminal_info.{ terminal_id, cwd }`;输出和退出通过 `tool_call_update` 的 `_meta.terminal_output.{ terminal_id, data }` 与 `_meta.terminal_exit.{ terminal_id, exit_code, signal }` 到达。 +- **`codex-acp`**(`CodexToolCallMapper.ts`、`TerminalOutputMode.ts`):调用上同样携带 `terminal_info`;输出通过 `_meta.terminal_output`(完整)或 `_meta.terminal_output_delta`(增量),由同一个 `_meta.terminal_output` 能力选择。 + +Zed 侧(`crates/agent_servers/src/acp.rs`,已验证):收到 `ToolCall` 且其 `_meta.terminal_info.terminal_id` 已设置时,注册一个**仅展示**的终端(header = `terminal_info.cwd`,label = `tool_call.title`);收到 `ToolCallUpdate` 时,`_meta.terminal_output.data` 写入该终端,`_meta.terminal_exit.{exit_code,signal}` 设置状态。客户端通过 `clientCapabilities._meta.terminal_output = true` 声明此能力。`_meta` 本身是 ACP 规范认可的扩展点(在 `ToolCall`/`ToolCallUpdate` 上类型为 `{[k]: unknown} | null`);这里的*具体键*(`terminal_info`/`terminal_output`/`terminal_exit`)是 Zed 约定,不属于 ACP 规范,但它们是 Zed 集成的事实契约,也是在保持 agent 侧执行的前提下获得终端卡片的唯一方式。 + +## 决策 + +保持 `dsh-bash` 的 agent 侧执行;通过 `_meta` 约定渲染终端卡片,以能力声明为门控,以 ` ```console ` 文本块作为保底回退。 + +1. **能力声明。** `initialize` 读取 `clientCapabilities._meta.terminal_output`,桥接层按连接记住它。 +2. **提供方无关的展示词汇。** `dsh-tools` 新增一种终端形态的展示结构,工具可返回它——提供方无关(`cwd`、输出 `data`、`exitCode`/`signal`),不含 ACP 类型。`dsh-tool-bash` 为 `bash` 返回该结构(cwd 来自解析后的工作目录;输出与退出从运行结果解析)。 +3. **桥接映射。** 当客户端声明了该能力时,桥接层将展示结构映射为:在 `tool_call` 上,`content:[…, {type:'terminal', terminalId}]`(工具的任何 `content`,如描述,渲染在终端块之前)+ `_meta.terminal_info.{terminal_id,cwd}`;在 `tool_call_update` 上,`_meta.terminal_output.{terminal_id,data}`(捕获的输出)+ `_meta.terminal_exit.{terminal_id, exit_code|signal}`(解析后的退出),且 update 的文本 `content` 被省略(ACP 的 `tool_call_update.content` 会替换调用的 content 集合,因此重新发送围栏块会覆盖终端内容块)。`terminalId` 由 harness 的 `callId` 派生(稳定、每次调用唯一)。当能力未声明时,桥接层在调用上发送描述内容块,在 update 上发送既有的 ` ```console ` 文本内容——行为不变。 +4. **退出信息从渲染输出中解析;无新执行路径,无实时流式传输。** 输出在完成时附加(来自 agent 自身的 `tool/result`),不逐 token 流式传输。退出状态(`_meta.terminal_exit.{exit_code,signal}`)确实会发出:纯 `presentResult(args, result)` seam 只能看到内容块,因此 `dsh-tool-bash` 通过解析 `renderResult` 追加的状态标记(`[exit code: N]` / `[killed by signal: …]`)来恢复结构化退出信息——解析是标记发出的精确逆操作,二者在同一文件中共同演进,一个往返测试守护这对关系。资源释放不受影响:无需新增拆除逻辑,因为桥接层从未创建客户端侧终端。 + +## 曾考虑的替代方案 + +- **ACP 客户端侧终端子协议(`terminal/create`)**:明确否决。编辑器将执行进程,绕过 `dsh-bash` 的环境清理、后台任务所有权和按会话的 cwd,并将执行分叉到两个后端。两个参考 agent 以同样的方式否决了它(见上述关键发现);agent 侧执行加 `_meta` 约定是在保持 harness 执行策略的同时获得终端卡片的唯一形态。 +- **通过事件 schema 传递结构化退出信息**:否决,改用标记往返方案。纯 `presentResult(args, result)` seam 只能看到内容块,而解析是标记发出的精确逆操作,二者在同一文件中共同演进,由往返测试守护。 + +## 后果 + +- **Zed 约定的 `_meta` 键。** 终端卡片依赖 Zed 特有的键(`terminal_info`/`terminal_output`/`terminal_exit`),位于 ACP 规范认可的 `_meta` 扩展点内,而非 ACP 终端子协议。不识别这些键的客户端仍然获得文本回退(能力门控确保我们仅在客户端通过 `_meta.terminal_output` 声明支持时才发出这些键),因此非 Zed 客户端不会变差。如果 ACP 日后标准化了 agent 执行的终端,则迁移到该标准并移除约定键。 +- **能力诚实。** 仅在客户端声明了 `_meta.terminal_output` 时才发出终端元数据;文本回退是对其他所有客户端的契约,绝不可退化。由一个无能力测试覆盖,断言 ` ```console ` 路径。 +- **terminalId 冲突。** 从每次调用的 `callId` 派生,保证在会话内唯一且在 call/result 对之间稳定;绝不跨调用复用。 +- **退出信息从渲染文本解析。** 退出信息通过解析 `renderResult` 的状态标记恢复 `exit_code`/`signal`,而非通过事件 schema 传递结构化退出(纯 `presentResult` seam 看不到后者)。解析是标记发出的精确逆操作,且位于同一文件中;往返测试固定了这对关系,标记格式变更若破坏解析则测试套件失败。如果标记格式日后需要与退出信息分道扬镳,则改为在 result 事件上暴露结构化退出。 +- **提供方无关词汇的蔓延。** 终端展示结构扩大了 `dsh-tools` 的接口面;保持其中立性(不让 ACP 类型泄漏到 `dsh-tools`),且只提供第二个 UI 消费方同样需要的丰富度。 + +## 超出范围 / 非目标 + +文本块基线仍为无能力声明时的默认行为。以下两项后续工作有意不在此处构建,各自需要单独的 Agent Note:**实时增量流式传输**(在分片到达时发出 `_meta.terminal_output_delta`,需要在 `dsh-bash` 上新增增量输出 seam);**命令分类**(将 `cat`/`sed` 解析为带文件位置的 `read` 卡片,将 `grep` 解析为 `search`,回退到终端卡片——仅展示,绝不改变实际执行内容)。 diff --git a/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.i18n.yaml b/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.i18n.yaml new file mode 100644 index 0000000000..7998dc3257 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-18-compaction-capability-seam.md: a263b5e7d0245bd1279024a50e05b2f33edad521 +2026-06-18-compaction-capability-seam.zh.md: df0cf9d9131978e608d47124ba0f0db0343ee12a diff --git a/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md b/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md index f5beab3eb4..a263b5e7d0 100644 --- a/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md +++ b/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-18-compaction-capability-seam.zh.md) + ## Problem A long-running agent conversation grows without bound. As the event log accumulates turns, the derived message history eventually approaches the model's context window — the model then truncates mid-response (`max-tokens`) or degrades. **Compaction** is the mitigation: replace a run of older history with a concise summary, keeping recent context intact. diff --git a/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.zh.md b/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.zh.md new file mode 100644 index 0000000000..df0cf9d913 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.zh.md @@ -0,0 +1,132 @@ +# Agent Note: 压缩作为能力 seam(抽象契约 + 基础后端) + +Status: implemented + +[English](2026-06-18-compaction-capability-seam.md) | 中文 + +## 问题 + +长时间运行的 agent(智能体)对话会无限增长。随着事件日志不断累积轮次,派生出的消息历史最终逼近模型的上下文窗口,模型随即截断响应(`max-tokens`)或性能退化。**上下文压缩(context compaction)** 是对此的缓解手段:用一段简洁的摘要替换一批较早的历史,保持近期上下文完整。 + +[会话接口面](../architecture/2026-06-18-session-surface.md)正是为此而构建的基础设施:一份建立在事件日志之上的有序投影,带有专门设计的 `surfaceOp: { op: 'replace', start, end }` 操作,用于遮蔽一段条目并插入替换内容,`sourceEventSeqs` 记录溯源信息以便决策可确定性地回放。剩下的是那个*决定压缩什么、并产出摘要*的插件。 + +两股力量塑造了设计。第一,压缩策略与可复用的 token 测量独立变化:测量归 LLM 系列的 [`ctx.tokenMeter` 服务](../architecture/2026-07-15-replay-token-meter-service.md)所有,摘要生成则可以使用模型调用、模板或远程服务。第二,`SurfaceEventType` 封闭为五种事件类型(`user/message`、`assistant/message`、`tool/result`、`context/message`、`steering/message`);只有这些类型可以携带 `surfaceOp`。因此一个专用的 `compaction/*` 事件**不能**出现在 surface 上,编译器与 Session 始终启用的 append/seed 边界都会拒绝在其上附加 `surfaceOp`。 + +## 决策 + +### 压缩是一个能力 seam,接口与实现分离 + +遵循[能力 seam Agent Note(agent 决策记录)](../architecture/2026-06-13-capability-seams.md),压缩以独立包(package)发布,使契约、算法和(后续的)消费方 surface 各自独立演进: + +1. **接口** — `@deepseek-ai/dsh-compact`:抽象 `CompactService`,拥有 `ctx.compact` 键、`CompactionResult` 词汇、`compact/*` 会话事件以及规范的检查点消息来源。它将 `compactIfNeeded()` 和 `compactRegion()` 声明为**抽象方法**——契约说明压缩*做什么*,而非*怎么做*。 +2. **实现** — `@deepseek-ai/dsh-compact-basic`:具体的 `BasicCompactService`,消费 `ctx.tokenMeter`,并拥有尾→头保留遍历、通过 `ctx.llm.stream()` 生成摘要、surface 替换、锁、步骤后压力处理和规范的上下文溢出恢复。`summarize()` 是其唯一的子类钩子;计价与回放仍归 meter 所有。 +3. **无模型配套服务** — `@deepseek-ai/dsh-compact-tool-result-prune`:一个具体的可选服务,在后端选择摘要范围之前,重写当前过大的 `tool/result` 节点。它不是第二种压缩实现,也不实现 `CompactService`。 +4. **消费方** — 推迟。一个 `/compact` 工具和斜杠命令将 `inject: ['compact']` 并调用契约;它们被有意排除在本 Agent Note 范围之外,以便 seam 先稳定下来。 + +### 契约依赖 `dsh-session` 和 `dsh-llm`——有意为之的偏离 + +能力 seam Agent Note 规定接口包「仅依赖 cordis」(对 `dsh-bash` 成立,因为其词汇是自包含的)。压缩**无法**遵守这一点:它的动词作用于 agent 所有的 `Session`(`compactRegion(start, end, agent)`),其输出使用内容词汇(`CompactionResult.summary: ContentBlock[]`)。不引用 `Session`/`SessionEvent`(来自 `dsh-session`)和 `ContentBlock`(来自 `dsh-llm`),契约就无法表达。 + +这不是耦合异味,而是契约的领域所在。「仅 cordis」的指导原则一直是「接口仅依赖契约真正需要命名的东西,绝不依赖实现」的简写。`dsh-session` 和 `dsh-llm` 本身是接口/词汇包,不是实现;`dsh-compact` 仍然不导入任何后端。seam 的真正不变式——*消费方和实现在抽象服务背后独立演进*——完好无损。 + +### 抽象 `compactIfNeeded` / `compactRegion`,算法在后端 + +早期草案将完整算法(保留遍历、token 求和、文本提取)作为接口上的具体方法。这会将契约重新耦合到一种策略:想要不同保留策略或事件排序的后端必须与继承来的具体代码对抗。将两个核心方法都设为抽象,把所有*怎么做*的决策放在后端,并让接口保持为*做什么*的声明。token 测量根本不是压缩钩子;单例服务使多个消费方能够共享逐会话的回放折叠。 + +`compactIfNeeded(agent, trigger, signal)` 接受显式的 `'pressure' | 'context-overflow'` 触发原因与取消信号。它只读取最新的持久化已路由请求;没有 header 就不执行工作,任何已路由的提供方/模型目标都使用单例估算器。`compactRegion(start, end, agent, signal?)` 将 `agent.session` 作为唯一会话身份,并为手动调用方保留可选 signal。默认摘要器依次从显式配置、最新记录的已路由目标和 agent 选项解析目标,并在任何 `llm/stream` 路由后记录提供方/模型对。它回放已路由请求的前缀,并将压缩指令追加为尾部 user 消息,从而复用提供方的热 KV cache;见[摘要前缀缓存 Agent Note](../bug-fix/2026-07-21-compaction-summary-prefix-cache-reuse.md)。该调用将提供方无关的 `GenerateOptions.purpose` 设为 `compaction`;适配器可以将此用途映射为对模型隐藏的传输元数据,DeepSeek 适配器会发送 `x-deepseek-harness-compact: 1`。 + +### 成功的持久步骤工作完成后运行自动压力检查 + +成功调用的压力检查不能在步骤前运行,因为最终的 `agent/request` 路由、提供方输出、工具结果、缓冲上下文与 steering 当时尚不存在。串行的 `agent/post-step(agent, turn, step, signal)` 会在这些事实持久化后、`step/end` 之前触发。`dsh-compact-basic` 通过 `ctx.tokenMeter` 测量规范的已记录请求,因此下一个请求无需推测性覆盖信封即可看到任何替换。压力达到条件后,可选的 `ctx.toolResultPrune` 重写在摘要范围选择前运行;compact-basic 重新测量持久 surface,如果修剪恢复到安全压力便跳过摘要生成。 + +规范的提供方上下文溢出走另一条路径。失败步骤先关闭,`agent/request-error` 接收原始请求错误与连续重试次数,compact-basic 在强制执行一次有效且平衡的缩减前先修剪。仅当 `session.surface.replaceGeneration` 增加时,它才返回 retry;这包括没有摘要范围时仅修剪取得的进展。随后循环开启新的编号步骤,并从持久日志重建请求。没有替换、任何替换前的恢复失败、取消、耗尽的上限或无关错误都会保留原始提供方失败。如果修剪已经推进 generation,而后续摘要工作失败,恢复会从该持久的已修剪 surface 重试,除非取消或资源释放胜出。完整生命周期决策见[调用后恢复 Agent Note](../architecture/2026-07-10-after-call-compaction-pressure-and-overflow-recovery.md)。 + +``` +assistant/message → tool/result/context/steering +await serial agent/post-step ⟵ pressure compaction inside the successful step +step/end + +provider overflow → step/end +await waterfall agent/request-error ⟵ forced compaction between attempts +retry → next numbered step/start ⟵ derives from the replacement surface +``` + +### 保留是轮次无关的;工具配对平衡是唯一的结构守卫 + +自动压缩在**每个成功的**步骤之后检查,而非每轮一次。这对失控轮次存活至关重要:工具密集型的 ReAct 轮次每步追加一个 `assistant/message` + 一个 `tool/result`,因此 surface 会在一轮之内增长。步骤后检查可以在后续步骤开启前压缩早期已关闭的工具对;如果请求率先越过限制,由提供方确认的溢出仍是兜底机制。 + +`compactIfNeeded` 保留估算大小达到解析后保留 token 预算的最小完整 surface 单元尾部,压缩更早的节点。一个单元是一个完整的已关闭步骤或一条无步骤消息。如果 token 截断点落在步骤内部,保留范围会扩展直到切割点满足工具配对平衡。平衡按 surface 顺序检查,而非日志序号,因为替换摘要在旧的 surface 位置拥有新的序号。`dsh-compact` 导出前后边缘辅助函数;只要 `replaceGeneration` 不变,其逐会话缓存就只折叠新增的 surface 尾部节点,面对仅日志增长时不读取事件,并在替换后重建当前成员关系与平衡。`compactRegion` 拒绝将工具调用与其结果拆分的边界。进行中的轮次不享受特殊保留。 + +因此失控轮次的压缩方式与其他历史完全相同:其早期*已关闭*步骤被摘要,近期步骤保持原样。当唯一可压缩的内容只剩一个不可拆分的开放尾部步骤(其工具调用尚无结果)时,压缩拒绝执行(返回 `null`)并在该步骤关闭后重试。 + +**部分单单元溢出仍不在范围内。** 摘要范围选择无法拆分不可分割的单元。当可移除的文本型工具结果内容占据大部分空间,且修剪后的余量能够容纳时,可选修剪器可以修复一个已关闭的工具对。仅信封压力、粘贴的 `user/message` 等不可分割的超大非工具节点,以及不可修剪余量仍然过大的工具单元,依旧不属于压缩范围;限制这些单元是另一个关注点。 + +### 头部锚定:一个自动检查点,始终在头部 + +自动压缩始终从 surface 头部开始,将先前的检查点与新压缩的历史合并,因此只保留一个自动检查点。`shadowedRange` 因此是位置性的而非数值序号区间:一个较新的摘要序号可能占据较旧的 surface 位置。`shadowedSeqs` 记录权威的 surface 顺序。手动的中间范围压缩可能留下多个检查点。 + +### 近似收敛不变式 + +`resolveConfig` 提供可用默认值:阈值比例 `0.8`、保留尾部比例 `0.16`、空的摘要提供方/模型覆盖、`maxTokens: 8192`、`compactionRetries: 1`、`maxOverflowRetries: 1` 以及 `auto: true`。可选的精确提供方/模型策略会部分覆盖顶层默认值;压力根据拥有该路由的 LLM 适配器所报告容量缩放比例,而 `retainTokens` 可以替代按比例保留。保留量必须低于最终阈值。收敛仍然是动态的,因为提供方输出上限可能被隐藏或显式的推理 token 消耗,摘要大小也不可预测。如果压力仍高于阈值,`compactIfNeeded()` 会按配置的重试次数再次压缩头部检查点,但每次提交的摘要必须小于其遮蔽的内容。溢出不需要容量元数据,并会绕过阈值和保留尾部策略,执行一次最大且平衡的头部缩减,留下最新的不可分割单元。所有权划分由[已路由模型上下文与压缩策略 Agent Note](../architecture/2026-07-20-routed-model-context-and-compaction-policy.md)规定。 + +### Surface 替换:`compact/*` 事件仅存在于日志;一条 `user/message` 承载摘要 + +由于 `SurfaceEventType` 是封闭的,摘要不能搭载在 `compact/*` 事件上。后端改为追加一条**单独的 `user/message`**,带有 `source: COMPACT_CHECKPOINT_SOURCE` 和 `surfaceOp: { op: 'replace', start, end }`;其 `content` 是(带框架的)摘要,`sourceEventSeqs` 覆盖被遮蔽的条目*和*簿记事件。接口导出该来源和 `isCompactCheckpointSource()`,使消费方无需依赖后端包身份,即可识别持久化或克隆得到的检查点。`compact/*` 事件是纯日志记录(锁 + 溯源信息)。surface 变更位于锁**内部**,`compact/end` 是最后追加的事件: + +``` +compact/start → log-only. Acquires the lock. +[summarize older range via the backend] +compact/summary → log-only. Provenance: raw summary, range, shadowed seqs, token count. +user/message → canonical checkpoint source + surfaceOp { op:'replace', start, end }. + THE surface mutation (framed summary). + deriveMessages() renders it as a user-role message. +compact/end → log-only. Releases the lock (carries `error` on a recoverable failure). +``` + +`deriveMessages()` 随后产出 `[summary_as_user_message, ...retained_entries]`。复用 `user/message` 是诚实的而非变通:摘要确实*是* user 角色的上下文。 + +### 检查点框架 + 增量合并(后端私有) + +基础后端将摘要包装为已建立的检查点上下文,并标记以便下一轮增量合并。原始摘要保留在 `compact/summary` 上。框架是后端策略;seam 承诺由一条替换 user 消息承载可能带框架的摘要,并使用规范的检查点来源。 + +### 通过日志记录的锁实现阻塞,加上崩溃/可恢复失败的分类 + +`compact/start … compact/end` 括号的存在理由,按当前实际承担的职责排序: + +1. **可检测的崩溃孤儿 + 来源追溯**(首要)。摘要生成是一次慢速模型调用,持久化在 `compact/start` *之后*。摘要生成中途崩溃会留下一个没有匹配 `compact/end` 的 `compact/start`——一个可检测的孤儿。最后释放锁(而非最先)将崩溃窗口从*静默损坏*转变为可检测的孤儿。 +2. **防止并发压缩。** 如果当前轮次持有未匹配的 `compact/start`,`compactRegion` 拒绝启动。(循环在任一 awaited 自动 seam 上都是单线程的,因此这也是重入绊线——抛出「already in progress」表示真正的 bug。) + +该锁只排除另一项压缩,不排除无关的仅日志事实。基础后端会在 `compact/start` 之后对 token meter 的 surface 节点取快照,并在异步摘要后再次比较;任何 surface 变更都会使替换前的检查失败,而标题或其他仅日志追加不会使已选范围失效。 + +两种失败路径,均有文档记录: + +- **崩溃**(循环在摘要生成中途死亡):悬空的 `compact/start`,无关闭事件。由于 `compact/*` 是**仅日志**事件,孤儿是**惰性的**,不会落地摘要替换。派生 surface 保持为 `compact/start` 时已经持久化的 surface:如果修剪未产生替换,就是完整历史;如果已经修剪,就是已修剪历史。通用轮次修复(`interruptedTurnClosers`)用合成的 `turn/end` 关闭轮次;孤儿位于该 `turn/end` *之前*,因此轮次范围内的进行中检查永远看不到它,崩溃不会卡住未来的压缩。 +- **可恢复**(摘要生成抛出异常但循环存活):后端追加设置了 **`error`** 字段的 `compact/end`,但不落地摘要替换。步骤后压力处理发出警告,并从最新的持久 surface 继续:如果尝试前没有替换,就是完整历史;如果修剪已经落地,就是已修剪 surface。溢出恢复只会在没有任何替换前委托;先前修剪带来的 generation 进展允许从该持久 surface 重试,除非取消或资源释放胜出。 + +`compact/end` 保留其 `error?` 字段(与 `tool/result` 的自包含错误一致——一个事件即可区分成功与失败,无需关联兄弟事件)。没有单独的 `compact/error` 事件。 + +**核心会话修复保持对压缩无感知——这是有意为之。** `interruptedTurnClosers` 从不被教导 `compact/*`。如果教导它,每个未来的 `xxx/start … xxx/end` 插件对都必须修补核心模块——这恰好是能力 seam 架构存在的意义所要避免的耦合。由于仅日志的孤儿是惰性的,不需要特殊修复:通用轮次修复加上未落地 surface 变更的惰性就足够了。 + +## 曾考虑的替代方案 + +- **完整算法作为接口的具体方法**——否决,因为它将契约重新耦合到一种保留策略。两个核心方法都是抽象的;可复用测量属于单独的 LLM 系列服务,`summarize()` 是 basic 唯一的钩子。 +- **在 `agent/request` 或临时 `agent/pre-step` 输入上执行压缩**——否决,因为两者都无法证明最终的持久请求,而且都会将通用生命周期耦合到压缩专属的信封数据。步骤后回放与规范溢出恢复同时覆盖成功和被拒绝的调用。 +- **`compact` 布尔值或无类型的请求元数据 map**——否决,因为多个辅助调用种类会变成互斥标志,而开放 map 会丢弃由编译器检查的词汇。一个类型化的 `purpose` 判别字段可以扩展其他调用种类,而无需再为 `GenerateOptions` 添加字段。 +- **单独的 `compact/error` 事件**——否决:`compact/end` 保留 `error?` 字段,与 `tool/result` 的自包含错误一致——一个事件即可区分成功与失败,无需关联兄弟事件。 +- **教导核心轮次修复识别 `compact/*`**——否决:仅日志的孤儿是惰性的,为每个未来的 `xxx/start … xxx/end` 插件对修补核心模块恰好是能力 seam 架构存在的意义所要避免的耦合。 + +## 后果 + +- **包**:`packages/compact/compact` 提供接口,`compact-basic` 提供后端,`compact-tool-result-prune` 提供可选的确定性重写。`packages/llm/token-meter` 独立拥有回放感知的测量。消费方层推迟。 +- **自动 seam**:`agent/post-step`(`@mode serial`)处理成功调用的压力,`agent/request-error`(`@mode waterfall`)处理失败步骤关闭后的最终请求失败。通用 `agent/pre-step` 保持为四参数检查点,不携带压缩专属的提示词/前缀 payload。 +- **`SessionEventMap`** 通过可合并扩展的声明合并获得 `compact/start` / `compact/summary` / `compact/end`;`SurfaceEventType` **未被**触及。这些是会话事件,不是 cordis `Events`,因此事件分类门禁无需新增条目。 +- **`dsh-compact`** 拥有 `COMPACT_CHECKPOINT_SOURCE`、`isCompactCheckpointSource(source)`、`toolPairingBalancedBefore(session, seq)` 与 `toolPairingBalancedAfter(session, seq)`。该标记用于跨后端实现识别替换摘要。带缓存的 surface 边缘检查会防止 `compactRegion` 和 `compactIfNeeded` 拆分工具调用/结果对,按 seq 校验当前成员关系,从每个切割点的一条平衡序列回答两侧边缘,并拒绝陈旧或缺失的 seq 与孤立结果。 +- **`dsh-session`** 通过唯一的 surface 管理器校验位置替换、完整溯源信息和仅内容的单节点 `tool/result` 重写。其不变式配套插件将新追加的工具结果视为执行,要求存在已打开的步骤与待处理调用;已校验的替换仍是位于轮次内的重写。 +- **接线**:`examples/tui-agent/cordis.yml` 依次加载零配置的 `dsh-token-meter`、`dsh-compact-tool-result-prune` 和 `dsh-compact-basic`;服务级默认值使组合无需重复数值策略即可使用。 + +## 测试 + +- **单元测试:** 使用真实 Loader 和 invariant 插件覆盖完整单元保留、修剪配置与回放、富块顺序、元数据保留、收敛、`compact/end` 的两种结果、开放尾部拒绝、仅修剪与带摘要的溢出恢复、generation 证明、上限和原始错误保留。 +- **循环测试:** 测试固定步骤后处理发生在持久工具结果之后、`step/end` 之前,使用实际 `agent/request` 路由,关闭失败步骤,分配新的重试编号,并覆盖完整的抛出/带内溢出 → 压缩 → 重建重试组合。 +- **带密钥 e2e:** 真实模型和 bash 会话在降低的限制下触发压缩,记录完整的 `compact/start…end` 对,缩小 surface,并完成任务。 +- **快照缺口:** 失控轮次压缩尚无法回放,因为摘要调用未记录 `assistant/chunk` 事件或 `sessionId`;交错摘要调用的回放仍是后续工作。 diff --git a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.i18n.yaml b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.i18n.yaml new file mode 100644 index 0000000000..3d1140f5cf --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-21-subagent-capability-seam.md: 9c17a93751de209e5e4e5a0ca7d7b1d8e5656a47 +2026-06-21-subagent-capability-seam.zh.md: 6294c84a8fa11e492316f4b69048aa5f477aa04f diff --git a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md index 3ed2090b22..9c17a93751 100644 --- a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md +++ b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-21-subagent-capability-seam.zh.md) + > The full seam is shipped: the `dsh-subagent` interface and `dsh-tool-subagent` consumer; the two in-process backends (`dsh-subagent-spawn`, `dsh-subagent-fork`); the nested-agent snapshot infrastructure ([per-session snapshot replay](../testing/2026-06-22-subagent-snapshot-replay.md)); and the out-of-process `dsh-subagent-acp` backend ([its Agent Note](2026-06-22-acp-subagent-backend.md)). ## Problem diff --git a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.zh.md b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.zh.md new file mode 100644 index 0000000000..6294c84a8f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.zh.md @@ -0,0 +1,73 @@ +# Agent Note: Subagent 能力 seam + +Status: implemented + +[English](2026-06-21-subagent-capability-seam.md) | 中文 + +> 完整 seam 已交付:`dsh-subagent` 接口与 `dsh-tool-subagent` 消费方;两个进程内后端(`dsh-subagent-spawn`、`dsh-subagent-fork`);嵌套 agent 快照基础设施([逐会话快照回放](../testing/2026-06-22-subagent-snapshot-replay.md));以及进程外后端 `dsh-subagent-acp`([其 Agent Note](2026-06-22-acp-subagent-backend.md))。 + +## 问题 + +harness 有一个长期搁置的 seam 用于 **subagent**:一个 agent(智能体)将工作委派给另一个 agent。这一意图在 `Agent`/`AgentLoop` 接口中已有草案([packages/core/agent/src/types.ts](../../../../packages/core/agent/src/types.ts)、[packages/core/agent-loop/src/index.ts](../../../../packages/core/agent-loop/src/index.ts)):一个创建选项引用父 agent(fork = 用父会话的事件日志初始化子会话;spawn = 全新会话),子 agent 以 `Agent` 句柄返回,使 steering(中途引导)和事件订阅可以统一工作。本 Agent Note 实现了这个 seam;上方横幅列出了已交付的内容。 + +决定整体设计走向的核心需求是:**多种 subagent 实现必须在运行时共存**。一个父 agent 可能在同一个会话中既需要一个廉价的进程内子 agent 处理有限范围的子任务,又需要一个隔离的进程外子 agent(通过 ACP(Agent Client Protocol))。我们预见的传输方式: + +- **进程内**:在同一个 `Context` 上创建一个具体的子 `Agent`(最廉价,且鉴于现有 agent 工厂几乎零成本); +- **ACP**:作为 ACP *客户端*驱动另一个 agent 进程(可以是自身的另一个实例); +- 后续:**A2A**、**Codex app-server** 与 **Claude Code Agent SDK**——每种都与 ACP 后端相同的进程外形状:「启动子 agent、发送提示词、流式接收更新、取消」。 + +## 曾考虑的替代方案 + +### 为何不采用 bash seam 的形状 + +bash seam([能力 seam](../architecture/2026-06-13-capability-seams.md))在每个上下文中只注册恰好一个 `BashExecutor`;加载第二个会抛异常。这对 bash 是正确的(一台机器、一种执行命令的方式),但对这里是错误的:共存才是需求。因此 subagent 服务是一个**命名提供方注册表**——每个实现以唯一名称注册,调用方按名称选择——镜像 **LLM(大语言模型)适配器注册表**(`LlmService.registerAdapter`),而非单服务的 bash 执行器。seam 仍然是由三个包构成的结构(接口 / 实现 / 消费方);只是「一个 vs. 多个实现」这个维度不同。 + +## 决策 + +### 由三个包构成的 seam + +新建包(package)组 `packages/subagent/`: + +| 包 | 角色 | +|---|---| +| `@deepseek-ai/dsh-subagent` | 接口:`SubagentService`(`ctx.subagents`)、`SubagentProvider`、`SubagentRun`、请求/结果/能力词汇、`subagent/*` 事件 | +| `@deepseek-ai/dsh-subagent-spawn` | 实现:通过 `ctx.agents.create` 创建全新的进程内子 agent | +| `@deepseek-ai/dsh-subagent-fork` | 实现:用父 agent 日志快照初始化的进程内子 agent | +| `@deepseek-ai/dsh-subagent-acp` | 实现:作为 ACP 客户端驱动已配置的子进程 | +| `@deepseek-ai/dsh-tool-subagent` | 消费方:基于 `ctx.subagents` 的面向模型的 `subagent` 工具 | + +### 原语:异步 `start → SubagentRun` + +提供方暴露 `start(request) → Promise<SubagentRun>`。完成时发布一个就绪的子 agent 并将其运行句柄转交给调用方。一个信号覆盖就绪前后的取消;`dispose()`(资源释放)取消剩余工作并等待完全停稳。启动失败时清理部分资源,不发出生命周期事件。`start` 与传输方式无关;`spawn` 仅指代全新的进程内后端。 + +### 两类可选能力,两种发现方式 + +- **启动时功能**(`outputSchema`、`depthLimit`、`toolFilter`、`persona`)挂在静态的 `provider.capabilities` 描述符上。服务在委派之前检查每个被请求的功能,如果提供方不支持则**大声拒绝**(`SubagentError('UNSUPPORTED_CAPABILITY')`),绝不接受后静默忽略。这些功能必须在 run 存在之前检查,因此不能是运行时方法。 +- **运行时功能**(通过 `sendMessage` 进行 steering、通过 `resume` 进行后续对话)是 `SubagentRun` 上的**可选方法**。方法的存在本身即为能力,TypeScript 类型收窄即为发现机制:消费方不经收窄就无法调用不存在的方法,因此不存在静默降级路径,也不需要额外的 flags 对象来保持同步。 + +### Fork 与 fresh 是独立后端,而非一个 flag + +全新子 agent 与 fork 子 agent 是独立的提供方,而非请求中的一个 flag。`dsh-subagent-spawn` 启动隔离的子 agent;`dsh-subagent-fork` 用一个平衡前缀初始化子 agent,该前缀仅包含已完成的父轮次。进行中的轮次被排除,因为其 subagent 调用尚无结果,无法构成有效的回放历史。 + +### 子 agent 隔离与父日志 + +每个 subagent 运行在**自己的 `Session`** 中(独立 id、`parentSession` 谱系),独立持久化。父日志仅记录 spawn `tool/call` 及其 `tool/result`(子 agent 的最终输出)——子 agent 的内部步骤和工具调用留在子 agent 自己的会话中,绝不注入父日志。这是唯一在所有传输方式下行为一致的设计:ACP 子 agent 的内部事件在物理上无法注入我们的父日志,因此让进程内行为保持一致,使 seam 真正与传输方式无关。 + +### 同步收集(首版) + +`dsh-tool-subagent` 将其执行信号传给 `start()`,等待子 agent 结果,并在 `finally` 中 dispose 该 run。非完成态的结果变为错误结果,而非成功的部分输出。这个前台消费方不使用 run 的可选 steering 方法。 + +### 提供方选择是配置,不面向模型 + +`dsh-tool-subagent` 绑定到恰好一个提供方名称(`Config.provider`);模型只看到 `{ description, prompt }`。若要暴露多种传输方式,请多次加载该工具插件,每次绑定不同的提供方和不同的 `toolName`(工具注册表拒绝重名)。*服务*持有多提供方注册表;*工具*选择其中一个——本版 schema 中没有提供方/type 参数。 + +## 测试 + +注册表与工具测试仅用包内脚本化提供方替换非确定性的子进程边界,同时运行真实的 `SubagentService`、生命周期、任务集成和面向模型的工具。提供方与消费方的 export 形状仍保留 Loader 回归覆盖,以防止[事后分析 0001](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md) 中描述的失败。注册表测试覆盖重载安全性、重名和启动时能力拒绝;嵌套 agent 场景通过[逐会话快照回放](../testing/2026-06-22-subagent-snapshot-replay.md)进行无密钥回放;进程内后端还有真实循环的单元测试和带密钥的 e2e 测试。 + +## 后果 + +- **递归。** 如果不设限制,进程内子 agent 能看到委派工具并递归调用。进程内后端实现了可选的绝对深度限制和有作用域的实时全局 `toolFilter`;ACP 声明这两项能力为关闭状态,并拒绝此类请求。[subagent 组合控制 Agent Note](2026-07-12-subagent-persona-tool-filter-and-depth.md) 负责定义它们的确切语义和安全边界。 +- **阻塞父轮次。** 前台收集在子 agent 的整个持续时间内保持父 agent 的步骤打开。后台委派使用共享的 `ctx.tasks` 运行时与通用 `task_*` 工具,与后台 bash 共用同一套收集机制;subagent seam 本身仍不感知任务。 +- **实时进度。** 本版仅暴露生命周期事件与最终结果;逐分片的子→父更新流推迟到后台重新设计时一并处理。 +- **ACP 客户端接口。** 将 ACP 子 agent 的 `fs`/`terminal` 代理回父 agent(共享工作区模式)是后续工作;首版不声明这两项能力,子 agent 在自己的进程中自行服务。 diff --git a/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.i18n.yaml b/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.i18n.yaml new file mode 100644 index 0000000000..64d1f57f51 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-22-acp-subagent-backend.md: a45ce5e34873249969bbe4dabb87a89d10246b3d +2026-06-22-acp-subagent-backend.zh.md: 3b6a11efc1ae0427eb5ce3b30029b77b00d6801a diff --git a/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.md b/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.md index d1b61b0af8..a45ce5e348 100644 --- a/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.md +++ b/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-22-acp-subagent-backend.zh.md) + ## Problem The subagent seam ([the seam Agent Note](2026-06-21-subagent-capability-seam.md)) was built so multiple backends coexist by name on `ctx.subagents`. The in-process backends (`-spawn`/`-fork`) run a child as a second `Agent` on the SAME cordis context — cheap, but the child shares the parent's process, model client, and tools. The seam's whole point was to also support an OUT-OF-PROCESS child reached over a protocol, proving the abstraction generalizes across a process boundary. This Agent Note adds the first such backend: an Agent Client Protocol (ACP) client. diff --git a/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.zh.md b/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.zh.md new file mode 100644 index 0000000000..3b6a11efc1 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.zh.md @@ -0,0 +1,62 @@ +# Agent Note: ACP subagent 后端(进程外委派) + +Status: implemented + +[English](2026-06-22-acp-subagent-backend.md) | 中文 + +## 问题 + +subagent seam([seam Agent Note](2026-06-21-subagent-capability-seam.md))的设计使多个后端可以按名称共存于 `ctx.subagents`。进程内后端(`-spawn`/`-fork`)将子 agent(智能体)作为第二个 `Agent` 运行在同一个 Cordis 上下文上:开销低,但子 agent 与父 agent 共享进程、模型客户端和工具。seam 的核心意义在于同时支持通过协议到达的进程外子 agent,以证明该抽象能跨越进程边界泛化。本 Agent Note 添加第一个此类后端:一个 ACP(Agent Client Protocol)客户端。 + +## 决策 + +`@deepseek-ai/dsh-subagent-acp` 注册一个 `SubagentProvider`,将每个子 agent 运行在一个派生的子进程中,并以 ACP *客户端*身份驱动它。它是现有服务端桥接 `@deepseek-ai/dsh-acp`(ACP *agent*)的方向反转孪生体:桥接应答 `initialize`/`newSession`/`prompt`;本后端调用它们并实现 `Client` 回调(`sessionUpdate`、`requestPermission`)。将配置的 spawn 命令指向 `acp-agent` 示例,即可让 harness 与自身进程通信。 + +### 每次运行启动全新进程 + +每次 `start` 都 spawn 一个新的子进程,运行恰好一个 ACP 会话(`initialize` → `newSession` → `prompt`),`dispose` 杀死子进程并等待其退出。这是最简单的生命周期,与进程内「每次运行一个子 agent」的形态一致。 + +### 最小化客户端桩 + +客户端不声明任何可选能力(无 `fs`、无 `terminal`):子 agent 在自己的进程中自行处理文件/终端访问。`session/update` 通知被消费:后端将 `agent_message_chunk` 文本累积为结果输出,在本阶段忽略其余内容(思考、工具调用卡片),仅暴露子 agent 的最终回答。`session/request_permission` 由配置的策略自动应答(`reject` 拒绝所有提示,`allow` 通过第一个允许形态的选项批准)——本阶段不向人类暴露任何权限提示。将 `fs`/`terminal` 代理回父进程(共享工作区模式)仍为后续工作,如 seam Agent Note 所述。 + +### 无启动时能力 + +提供方的 `capabilities` 全部为 `false`。进程外子 agent 无法遵守父 agent 的 `maxDepth`(它无权访问 `parent.options.subagentDepth`)或 `toolFilter`(它拥有自己的工具注册表),本阶段也未实现 `outputSchema`。如果请求需要其中任何一项,服务在 `start` 运行前即拒绝。后端仅注入 `subagents`(而非 `ctx.agents`);它从 `request.parent` 读取的唯一内容是会话 header 的 cwd(见下方工作区解析)——对话上下文、深度和工具状态都不会跨越进程边界。 + +### 工作区 cwd 解析 + +子进程工作目录来自显式解析,绝不使用 harness 进程的 cwd:若已配置部署 `cwd` 覆盖,则相对于启动目录将其转为绝对路径并在加载时验证;否则使用父会话 header 的 cwd 并在启动时验证;如果两者都不存在,则在生成任何进程前大声拒绝。一个 ACP 服务端进程会服务来自多个工作区的会话,因此 `process.cwd()` 不能代替会话工作区——旧的隐式回退会让子进程在服务端启动目录中运行。候选路径必须是 harness 可以进入的绝对目录(要求 `X_OK`;仅 `statSync().isDirectory()` 会接受 mode-600 的目录,而 spawn 会因 EACCES 失败);解析出的同一路径同时用作子进程 cwd 与 ACP `session/new` 工作区。 + +### StopReason 映射 + +ACP `StopReason` → harness `SubagentStopReason`:`end_turn`→`completed`、`max_tokens`→`max-tokens`、`refusal`→`refusal`、`cancelled`→`aborted`、`max_turn_requests`→`error`(无对等语义,任务未完成)、未知→`error`。spawn/传输/RPC 失败解析为 `error`(如果已请求取消则为 `aborted`);按 seam 契约,`result` 在子 agent 级别失败时从不 reject。 + +### 安全:清洗子进程环境 + +子 agent 是独立进程,因此会继承环境变量。形如凭证的环境变量(`/KEY|SECRET|TOKEN/i`)默认不转发——父 harness 自身的密钥不得隐式泄露到派生进程中(与 bash 执行器采用的策略相同)。子 agent 自己的凭证(它需要模型密钥)通过 `config.env` 显式提供,在清洗之后叠加,因此有意传入的 `DEEPSEEK_API_KEY` 得以保留,而偶然存在的 `AWS_SECRET_ACCESS_KEY` 则不会。子进程的 stderr 继承到父进程的 stderr(诊断信息自然浮现);spawn 级别的 `error` 事件(如命令不存在时的 ENOENT)被捕获并与 ACP 驱动竞速,因此错误命令解析为 `error` 而非以未处理错误崩溃父进程。 + +## 测试 + +- **无需密钥的单元/集成测试:** 一个脚本化的 ACP 子进程通过真实 stdio 测试提示词/输出流、所有 stop-reason 映射、信号与 dispose 取消(包括 pre-abort、会话前竞态和管道断裂场景)、两种权限策略、被忽略的非消息更新、命令缺失时的清理、提供方重载以及命名空间导出。 +- **无需密钥的 Loader 组合测试:** 仅用于测试的 cordis.yml 通过真实 Loader 启动 stdio 应用,并省略后端的 `cwd`;脚本化模型委派一次,脚本化子进程则证明它在父会话工作区中运行,且 ACP 也对外公布了该工作区,从而端到端覆盖 cwd 继承分支。 +- **需要密钥的 e2e 测试:** 后端 spawn 真实的 ACP 示例;其模型回答 `PONG`,写入 `proof.txt`,父进程验证该文件。 +- **快照缺口:** 每个 ACP 子 agent 是独立进程,拥有自己的回放会话,不同于进程内的按会话回放。确定性 mock 服务器覆盖率已具备;`TODO(acp-subagent-replay)` 跟踪父进程对回放中子 agent 的回放支持。 + +## 曾考虑的替代方案 + +### 为何继续使用 SDK 0.25.1? + +后端只需要 `ClientSideConnection`、`ndJsonStream`、`PROTOCOL_VERSION` 和客户端协议类型,0.25.1 全部支持。0.28 的 fluent API 需要在 ACP 层同时迁移客户端和服务端连接类,却不会改善本后端,因此升级作为独立变更保留。 + +### 为何不使用持久子进程? + +持久进程池(跨运行复用热子进程)是一项性能优化,推迟到后续工作。它增加了会话生命周期和崩溃恢复的复杂度,本阶段不需要;每次 `start` spawn 全新子进程与进程内「每次运行一个子 agent」的形态一致。 + +## 后果 + +每次运行都要付出一个全新子进程的代价(spawn + `initialize` + `newSession`)。父进程仅暴露子 agent 的最终回答:`session/update` 中的思考和工具调用卡片被消费后丢弃,权限提示从不到达人类——由配置的策略应答。子进程环境默认经过凭证清洗,因此其自身的模型密钥需通过 `config.env` 显式提供。 + +## 后续提供方 + +同样的进程外启动/提示词/流式输出/取消形态可泛化到 seam Agent Note 中列出的其他传输方式——A2A、Codex app-server 和 Claude Code Agent SDK——每个都是按名称注册的兄弟提供方。ACP 后端证明了 seam 支持跨进程边界;其余在机制上类似。 diff --git a/.agents/notes/implemented/feature/2026-06-25-ask-user-question.i18n.yaml b/.agents/notes/implemented/feature/2026-06-25-ask-user-question.i18n.yaml new file mode 100644 index 0000000000..6a06911100 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-25-ask-user-question.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-25-ask-user-question.md: 51b9a67bfc0fdc88d84a9fa51662d02b127f7925 +2026-06-25-ask-user-question.zh.md: 4bd2c2b8664ba085919eb9d4b8c5dee92d4bf72e diff --git a/.agents/notes/implemented/feature/2026-06-25-ask-user-question.md b/.agents/notes/implemented/feature/2026-06-25-ask-user-question.md index cd1a423499..51b9a67bfc 100644 --- a/.agents/notes/implemented/feature/2026-06-25-ask-user-question.md +++ b/.agents/notes/implemented/feature/2026-06-25-ask-user-question.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-25-ask-user-question.zh.md) + ## Problem The agent sometimes cannot proceed safely from model inference alone: it needs the human to choose a path, confirm a risky/default action, or provide missing information. Before this change, the only way to get that answer was for the model to ask in assistant text and then stop, which broke the normal tool-call loop: the agent had no structured way to pause, no option metadata for UIs, no abort/error taxonomy, and no way for non-stdio front doors to present the question consistently. @@ -16,7 +18,7 @@ The model-facing request vocabulary is deliberately aligned with the product-res Providers return `{ answers: [{ id, selected, custom? }] }`. `selected` is always an array of selected option labels, so single-select and `multi_select` answers share one result shape. `custom` carries a free-text "Other" answer; optionless questions collect `custom` directly. When `custom` is present, it overrides any selected choices and `selected` is empty. A provider that supports partial completion represents a deliberately skipped item with the existing `{ id, selected: [] }` shape, preserving the other answers without extending the tool result vocabulary. -`UserInteractionError` extends `HarnessError`, so failures such as `NO_PROVIDER`, `ASK_ABORTED`, ACP cancellation, or missing session routing survive `ctx.tools.execute()` as machine-routable `{ name, code }` tool errors. This matches the structured-error taxonomy and lets the model or a wrapping plugin distinguish "user cancelled" from a generic thrown exception. +`UserInteractionError` extends `HarnessError`, so failures such as `NO_PROVIDER`, `ASK_ABORTED`, or missing request ownership survive `ctx.tools.execute()` as machine-routable `{ name, code }` tool errors. This matches the structured-error taxonomy and lets the model or a wrapping plugin distinguish "user cancelled" from a generic thrown exception. ## UI mappings @@ -26,9 +28,7 @@ The Web composer shows one question at a time while retaining every request in t `dsh-tui` renders each question as a keyboard overlay, shows option descriptions, supports single- and multi-select choices plus free-form custom answers, and rejects pending questions on abort, provider disposal, or terminal shutdown. Batched and simultaneous requests are queued so one overlay owns keyboard focus at a time. -`dsh-acp` provides the same seam for ACP sessions. It resolves the calling `Agent` through `ownedRecord`, requiring the forward session-map record at `agent.session.id` to own that exact agent object, and calls ACP `unstable_createElicitation` with a session-scoped form for each question. Single-select options become a `choice` string enum; `multi_select` options become a `choice` array enum; optionless questions use a required `custom` text field. If the client returns both `choice` and non-empty `custom`, the custom answer wins. ACP `decline`/`cancel`, a missing answer, a missing session, and a client without elicitation support all become structured `UserInteractionError`s. - -The ACP mapping deliberately uses elicitation, not `session/request_permission`. `request_permission` is still reserved for the separate permission gate: it is a yes/no-or-policy authorization protocol around tool execution. `ask_user_question` is a general information-gathering tool with optional free-form answers, so ACP form elicitation is the closer protocol fit. The bridge's session routing is shared with the future permission gate, but the user intent is different. +An ACP elicitation mapping existed while the bridge was an editor UI; [ACP as an automation-only protocol](../simplification/2026-07-23-acp-automation-only-protocol.md) removed that third mapping. ## Alternatives considered @@ -36,18 +36,16 @@ The ACP mapping deliberately uses elicitation, not `session/request_permission`. **Core-owned ask-user packages.** The first implementation split the seam and the model-facing tool across `packages/core` and `packages/ui`, but both names describe one UI-backed human-interaction affordance. The seam remains provider-neutral, but it is not providerless core infrastructure like sessions, tools, or the agent registry. Keeping `dsh-user-interaction` and `dsh-tool-ask-user` together under `packages/ui` makes the package map match the product boundary: apps and bridges provide the human-answer provider, and the stdio app opts into the model-facing tool. -**ACP `session/request_permission`.** Permission requests are authorization around tool execution; `ask_user_question` is information gathering with optional free-form answers. Using permission for general questions would collapse two different product concepts and make the future permission gate harder to reason about. +**Use a permission request for general questions.** Permission requests authorize tool execution; `ask_user_question` gathers information with optional free-form answers. Reusing the permission channel would collapse two different product concepts. **A loop-level pause primitive.** The agent loop already knows how to await a tool call and resume from a tool result. Adding a new loop special case would duplicate that async shape and make every loop implementation learn about a UI concern. ## Consequences -ACP elicitation is currently marked unstable in the SDK. The fallback is still structured: if a client does not implement it, the tool returns `ASK_FAILED` rather than hanging. A later ACP stabilization may rename or reshape the method; that migration should stay inside `dsh-acp` because the core `ctx.userInteraction` vocabulary is provider-neutral. - The feature gives the model a powerful pause primitive, so prompt guidance matters. The tool description tells the model to ask concise questions and use options when possible. Product policy can later wrap `tools/execute` to restrict when the tool is allowed, but the loop should not special-case it. -`dsh-user-interaction` and `dsh-tool-ask-user` both live in `packages/ui` because they form one product-facing human-interaction capability. `agent-core` does not load either the tool or a provider. `dsh-tui-demo` opts into the seam, TUI provider, and model-facing tool. `dsh web` boots the seam/provider in the host runtime and exposes the tool through the selected Web question plugin. `acp-agent` keeps only the `userInteraction` seam/provider by default: ACP elicitation support is still client-dependent, so an ACP leaf must opt into the model-facing tool deliberately once its client can complete elicitation requests. +`dsh-user-interaction` and `dsh-tool-ask-user` both live in `packages/ui` because they form one product-facing human-interaction capability. `agent-core` does not load either the tool or a provider. `dsh-tui-demo` opts into the seam, TUI provider, and model-facing tool. `dsh web` boots the seam/provider in the host runtime and exposes the tool through the selected Web question plugin. The ACP automation app mounts neither the seam nor the tool. ## Testing -Unit coverage pins provider registration/disposal, duplicate-provider rejection, abort-before-provider, empty-question rejection, structured tool errors through `ctx.tools.execute()`, batched answers, multi-select answers, custom answers, explicit per-item skips, and the model schema including the removal of `value`, `recommended`, `allow_custom`, and `desc`. TUI tests cover option descriptions, queued requests, shutdown/abort cleanup, optionless free-form input, invalid choices, duplicate multi-select selections, and batched question flows. ACP bridge tests drive a real in-memory ACP connection with the real `ask_user_question` tool and verify selected-option, custom-overrides-choice, multi-select, and optionless free-form elicitation paths continue the agent loop. Web tests pin stable-id replay, response validation, first-wins settlement, duplicate and late responses, whole-request cancellation versus owner abort, single-select advance, IME-safe Enter submission, per-item skip preservation, composer takeover, structured batch submission, and restoration of the normal composer. +Unit coverage pins provider registration/disposal, duplicate-provider rejection, abort-before-provider, empty-question rejection, structured tool errors through `ctx.tools.execute()`, batched answers, multi-select answers, custom answers, explicit per-item skips, and the model schema including the removal of `value`, `recommended`, `allow_custom`, and `desc`. TUI tests cover option descriptions, queued requests, shutdown/abort cleanup, optionless free-form input, invalid choices, duplicate multi-select selections, and batched question flows. Web tests pin stable-id replay, response validation, first-wins settlement, duplicate and late responses, whole-request cancellation versus owner abort, single-select advance, IME-safe Enter submission, per-item skip preservation, composer takeover, structured batch submission, and restoration of the normal composer. diff --git a/.agents/notes/implemented/feature/2026-06-25-ask-user-question.zh.md b/.agents/notes/implemented/feature/2026-06-25-ask-user-question.zh.md new file mode 100644 index 0000000000..4bd2c2b866 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-25-ask-user-question.zh.md @@ -0,0 +1,51 @@ +# Agent Note: ask-user 提问能力 + +Status: implemented + +[English](2026-06-25-ask-user-question.md) | 中文 + +## 问题 + +agent(智能体)有时仅凭模型推理(inference)无法安全地继续执行:它需要人类选择路径、确认有风险的或默认的操作,或者提供缺失的信息。在此变更之前,获取答案的唯一方式是模型在 assistant 文本中提问然后停止,这打断了正常的工具调用循环:agent 没有结构化的暂停方式,没有供 UI 使用的选项元数据,没有中止/错误分类体系,也没有让非 stdio 前端一致地呈现问题的途径。 + +这是一个面向用户的能力,但它也跨越了包(package)边界。面向模型的工具需要一套提供方无关的请求词汇;每个 UI 界面需要决定如何展示和收集答案;agent loop(智能体循环)应保持不变,因为工具调用本身已具备正确的异步形状。 + +## 决策 + +引入 `dsh-user-interaction` 作为 `ctx.userInteraction` 的提供方无关接口包,与面向模型的消费方 `dsh-tool-ask-user` 一同放在 `packages/ui` 下。这一分组是有意为之的:向人类提问是一种由 UI 支撑的产品功能,不属于无提供方的核心主干。seam 仍然拥有稳定的请求/应答/错误词汇,而 UI 产品界面提供收集答案的具体提供方。该工具注册 `ask_user_question`,转发 `{ questions, agent, signal }`,并将提供方计算出的结构化答案作为工具结果返回。 + +面向模型的请求词汇有意与产品调研 schema 对齐:`ask_user_question({ questions: [{ id, question, header?, options?: [{ label, description? }], multi_select? }] })`。`id` 按问题提供并在结果中回传,使批量请求无需依赖问题文本即可路由。`label` 既是面向用户的显示文本,也是返回给模型的选中值;没有单独的 `value`,没有 `recommended`,没有 `allow_custom`,也没有 `desc` 别名。 + +提供方返回 `{ answers: [{ id, selected, custom? }] }`。`selected` 始终是选中选项 label 的数组,因此单选和 `multi_select` 的答案共享同一种结果形状。`custom` 承载自由文本的「其他」答案;无选项的问题直接收集 `custom`。当 `custom` 存在时,它覆盖任何已选择的选项,`selected` 为空。支持部分完成的提供方使用现有的 `{ id, selected: [] }` 形状表示某项被有意跳过,在不扩展工具结果词汇的前提下保留其他答案。 + +`UserInteractionError` 继承 `HarnessError`,因此 `NO_PROVIDER`、`ASK_ABORTED` 或请求归属缺失等失败会以机器可路由的 `{ name, code }` 工具错误形式通过 `ctx.tools.execute()` 传出。这与结构化错误分类体系一致,使模型或包装插件能够区分「用户取消」与一般的抛出异常。 + +## UI 映射 + +`dsh web` 挂载 `dsh-client-ui-question`:其 host 侧使 Web 产品选择性加载面向模型的工具,浏览器侧则在 conversation 拥有的具名输入区 slot 中注册 `question` 项。`createApiProxy` 使用以 host 生成的 rpcId 为键的进程内 pending 表实现 Web 提供方。它先注册等待项,再广播 `question/requested`;每次 mux 重开时以相同 id 重放;在受理前校验会话和完整答案批次;并在回答、取消、中止或资源释放后广播 `question/resolved`。受理会同步删除该条目,因此首个有效响应胜出,重复或迟到的响应返回 `not-pending`。 + +Web 输入区一次显示一个问题,同时在会话对象层保留每个请求。它支持单选、多选、无选项问题或显式自定义答案、描述文本与可视化推荐标记,但不会自动选中推荐项。选择单选项后会立即进入下一项;当所有项都已回答或显式跳过时,按 Enter 提交;IME 组字期间按 Enter 只会确认输入候选项。页脚只跳过当前项并保留先前的草稿;关闭控件以 `ASK_CANCELLED` 拒绝整个工具调用。常规输入区只有在 host 的 resolved 帧移除待处理项后才会恢复。 + +`dsh-tui` 将每个问题渲染为键盘叠层,展示选项描述,支持单选、多选和自由格式自定义答案,并在中止、提供方 dispose(资源释放)或终端关闭时拒绝待处理的问题。批量请求和并发请求都会排队,确保同一时刻只有一个叠层占用键盘焦点。 + +在桥接层还是编辑器 UI 时曾存在一个 ACP(Agent Client Protocol)elicitation 映射;[ACP 作为仅面向自动化的协议](../simplification/2026-07-23-acp-automation-only-protocol.md)移除了这第三个映射。 + +## 曾考虑的替代方案 + +**Assistant 文本后跟一个停止的轮次。** 模型可以在纯 assistant 文本中向用户提问然后停止。这会丢失结构化选项元数据,UI 没有提供方无关的方式来渲染选择,且下一条人类回答只能作为新的 user 提示词到达,而非作为需要答案的那次操作的结果。 + +**核心拥有的 ask-user 包。** 最初实现将 seam 和面向模型的工具分别放在 `packages/core` 和 `packages/ui`,但两者描述的是同一个由 UI 支撑的人机交互功能。seam 仍然是提供方无关的,但它不是像会话、工具或 agent 注册表那样的无提供方核心基础设施。将 `dsh-user-interaction` 和 `dsh-tool-ask-user` 一起放在 `packages/ui` 下,使包的划分与产品边界一致:应用和 bridge 提供人类答案的提供方,stdio 应用选择性加载面向模型的工具。 + +**用权限请求处理通用提问。** 权限请求是对工具执行的授权;`ask_user_question` 是带可选自由格式答案的信息收集。复用权限通道会混淆两个不同的产品概念。 + +**循环级别的暂停原语。** agent loop 已经知道如何等待工具调用并从工具结果恢复。添加新的循环特殊分支会重复这一异步形状,并迫使每个循环实现都了解一个 UI 关注点。 + +## 后果 + +该功能赋予模型一个强大的暂停原语,因此提示词引导很重要。工具描述告诉模型:提问要简洁,尽可能使用选项。产品策略后续可以包装 `tools/execute` 来限制工具何时可用,但循环不应对其做特殊处理。 + +`dsh-user-interaction` 和 `dsh-tool-ask-user` 都位于 `packages/ui`,因为它们共同构成一个面向产品的人机交互能力。`agent-core` 不加载工具或提供方。`dsh-tui-demo` 选择性加载 seam、TUI 提供方和面向模型的工具。`dsh web` 在 host 运行时启动 seam/提供方,并通过选定的 Web question 插件暴露该工具。ACP 自动化应用既不挂载 seam 也不挂载该工具。 + +## 测试 + +单元覆盖率固定了以下场景:提供方注册/释放、重复提供方拒绝、提供方就绪前中止、空问题拒绝、通过 `ctx.tools.execute()` 传出的结构化工具错误、批量答案、多选答案、自定义答案、显式按项跳过,以及模型 schema(包括移除 `value`、`recommended`、`allow_custom` 和 `desc`)。TUI 测试覆盖选项描述、排队请求、关闭/中止清理、无选项自由格式输入、无效选择、重复多选和批量问题流。Web 测试固定稳定 id 重放、响应校验、首个响应胜出的结算、重复和迟到响应、整个请求的取消与拥有方中止的区别、单选后前进、IME 安全的 Enter 提交、按项跳过保留、输入区接管、结构化批量提交,以及常规输入区的恢复。 diff --git a/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.i18n.yaml b/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.i18n.yaml new file mode 100644 index 0000000000..d7babf16b3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-29-todo-write-tool.md: df1bee2801b0e01b290b63f6edbe2e5b1be80cb7 +2026-06-29-todo-write-tool.zh.md: 7fa5cb2aad2b32ef0662df04ff6576be14a3a8e7 diff --git a/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.md b/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.md index ab9421c2ed..df1bee2801 100644 --- a/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.md +++ b/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.md @@ -2,33 +2,31 @@ Status: implemented +English | [中文](2026-06-29-todo-write-tool.zh.md) + ## Problem -The harness gives the model bash and subagent tools but no way to record a structured task list. A todo list serves two co-equal purposes: it steers the model to plan multi-step work and keep the active task unambiguous (at most one active, exactly one while work remains), and it gives the human a live progress checklist. The ACP protocol has a native `plan` sessionUpdate that editors (Zed) already render, but the bridge never emitted one. Every reference coding agent surveyed (claude-code, opencode, codex, oh-my-pi, pi) ships some form of this; the harness had nothing. +The harness gives the model bash and subagent tools but no way to record a structured task list. A todo list serves two co-equal purposes: it steers the model to plan multi-step work and keep the active task unambiguous (at most one active, exactly one while work remains), and it gives an interactive host a live progress checklist. Every reference coding agent surveyed (claude-code, opencode, codex, oh-my-pi, pi) ships some form of this; the harness had nothing. ## Decision -Add a model-facing `todo_write(todos: [{ content, status }])` tool whose whole-list state lives on the event-sourced session log as a new `todo/write` `SessionEventMap` variant. Both the stdio UI and the ACP bridge render off the existing `session/event` — the ACP bridge maps the list to a `plan` sessionUpdate. +Add a model-facing `todo_write(todos: [{ content, status }])` tool whose whole-list state lives on the event-sourced session log as a new `todo/write` `SessionEventMap` variant. Interactive hosts render from the durable event; the TUI folds it directly, while the [automation-only ACP bridge](../simplification/2026-07-23-acp-automation-only-protocol.md) deliberately omits todo presentation. ### Whole-list replace, three-state status -The model sends the ENTIRE list every call; the new list replaces the old (last-write-wins on replay). This is the shape claude-code V1, opencode, and codex `update_plan` all use, and the shape the model is most trained on — no per-item ids, no delta protocol. `status` is exactly `pending | in_progress | completed`: the same triple as codex `update_plan` and, crucially, **identical to the ACP `PlanEntryStatus`**, so the bridge maps it 1:1 with no lossy translation. +The model sends the entire list every call; the new list replaces the old (last-write-wins on replay). This is the shape claude-code V1, opencode, and codex `update_plan` all use, and the shape the model is most trained on — no per-item ids, no delta protocol. `status` is exactly `pending | in_progress | completed`, the same triple as codex `update_plan`; it also matched the ACP `PlanEntryStatus` 1:1 while the bridge projected todo lists as `plan` updates, a mapping retired with the [automation-only ACP contract](../simplification/2026-07-23-acp-automation-only-protocol.md). ### State on the session log, not a service -The list is appended as a `todo/write` event carrying the full `{ todos }` snapshot. The harness is event-sourced — the LLM history, tool calls, and turn structure all live on the log — so the todo list lives there too. This buys durability, replay, and `session/load` reconstruction for free: a reopened session re-derives the current list (the last `todo/write`) and the ACP bridge re-emits the `plan` on load, with no separate persistence backend, no in-memory service to rehydrate, and no extra wiring. An in-memory `ctx.todos` service would have had to reinvent all of that. +The list is appended as a `todo/write` event carrying the full `{ todos }` snapshot. The harness is event-sourced — the LLM history, tool calls, and turn structure all live on the log — so the todo list lives there too. This buys durability, replay, and resume reconstruction for free: a reopened session re-derives the current list from the latest `todo/write`, with no separate persistence backend, in-memory service to rehydrate, or extra wiring. An in-memory `ctx.todos` service would have to reinvent all of that. ### NOT a surface event `todo/write` is deliberately excluded from `SurfaceEventType`. The surface is the projection that produces the LLM message history (`deriveMessages()`); a todo write produces no conversation message. So it carries no `surfaceOp`, never joins the ordered surface, and never reaches `deriveMessages()` — it is durable, replayable *UI* state that travels alongside the conversation without being part of it. (The dev-mode invariants still require it to sit inside an open turn, which it always does: it is appended mid-step during a tool call.) -### Priority synthesized only at the ACP boundary - -ACP's `PlanEntry` requires `content` + `priority` + `status`, but a `TodoItem` has no priority — the model never reasons about it. Rather than burden the schema with a field the model must always supply, the bridge synthesizes a constant `priority: 'medium'` on every entry when it builds the `plan`. Priority is an ACP wire requirement, not a harness concept, so it lives at exactly the boundary that needs it. - ### Dropped vs claude-code V1: `activeForm`, id, priority -claude-code V1's item is `{ content, status, activeForm }`; later (V2) it grew ids, dependencies, and ownership — but only to support agent *swarms* (disk-backed, lock-guarded, per-item mutation). This tool keeps the item at the minimum: `{ content, status }`. No `activeForm` (the present-continuous label) — the UI shows `content`; no id — whole-list replace needs no stable identity; no priority — see above. Each dropped field is one less thing the model must produce on every call. +claude-code V1's item is `{ content, status, activeForm }`; later (V2) it grew ids, dependencies, and ownership — but only to support agent *swarms* (disk-backed, lock-guarded, per-item mutation). This tool keeps the item at the minimum: `{ content, status }`. No `activeForm` (the present-continuous label) — the UI shows `content`; no id — whole-list replace needs no stable identity; no priority — that was only ever an ACP `PlanEntry` wire requirement, synthesized as a constant at the bridge boundary rather than modeled, and it left with that projection. Each dropped field is one less thing the model must produce on every call. ### Single owner — no swarm machinery (YAGNI) @@ -45,18 +43,18 @@ The schema enforces type/required/enum. Beyond that, `execute` rejects empty or ## Testing Four tiers, designed up front: -- **Unit** — the session event (append/snapshot-clone/last-write-wins/not-on-surface); the tool (schema shape, arg validation via the real `ctx.tools.execute`, value validation, the event append + replacement, no-agent rejection, `presentCall`, HMR-safety); the ACP `todosToPlan` mapping; the stdio render arm. +- **Unit** — the session event (append/snapshot-clone/last-write-wins/not-on-surface); the tool (schema shape, arg validation via the real `ctx.tools.execute`, value validation, the event append + replacement, no-agent rejection, `presentCall`, HMR-safety); and TUI folding. - **Real-Loader path** — the plugin run through `Loader.unwrapExports`, asserting the namespace export shape survives (it HAS `inject`, so a stray default would crash at load — postmortem/0001). - **Full-loop integration** — a scripted mock model calls `todo_write` through the real agent loop; the `todo/write` event lands and a second call replaces it. -- **`session/load` replay** — a persisted `todo/write` re-emits the `plan` update when a fresh ACP bridge loads the session. -- **With-key e2e + snapshot** — a real prompt induces a `todo_write`; the snapshot expected output gains the `plan` notification and the log event. +- **Resume/replay** — a persisted `todo/write` folds back into the current task list. +- **With-key e2e + snapshots** — a real prompt induces `todo_write`; assembled snapshots pin the log event and interactive rendering. ## Alternatives considered -- **In-memory `ctx.todos` service** — would reinvent durability, replay, and `session/load` reconstruction the log gives for free. +- **In-memory `ctx.todos` service** — would reinvent durability, replay, and resume reconstruction the log gives for free. - **Per-item delta protocol** — only needed for a shared multi-owner list, which is out of scope; whole-list replace is simpler and matches the references. - **Tool in `core/`** — `todo_write` is an extension tool registering on `ctx.tools`, not part of the spine; it lives in its own `packages/todo/` group like other tool families. ## Consequences -The todo list is durable, replayable session state: a persisted `todo/write` re-emits the editor's `plan` update on `session/load`, and the log — not plugin memory — is the single source of truth. Whole-list replace means one tool call per update with last-write-wins; there is no delta protocol to reconcile. The event stays off the surface, so a todo update never perturbs the derived model history — the model sees only its own tool call and result. +The todo list is durable, replayable session state: an interactive host re-derives it from the latest persisted `todo/write`, and the log — not plugin memory — is the single source of truth. Whole-list replace means one tool call per update with last-write-wins; there is no delta protocol to reconcile. The event stays off the model surface, so a todo update never perturbs derived model history — the model sees only its own tool call and result. diff --git a/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.zh.md b/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.zh.md new file mode 100644 index 0000000000..7fa5cb2aad --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.zh.md @@ -0,0 +1,60 @@ +# Agent Note: `todo_write` 工具——将模型任务列表作为事件溯源的会话状态 + +Status: implemented + +[English](2026-06-29-todo-write-tool.md) | 中文 + +## 问题 + +harness 为模型提供了 bash 和 subagent 工具,却没有办法记录结构化的任务列表。todo 列表有两个同等重要的用途:引导模型规划多步骤工作并保持当前活跃任务明确(最多一个活跃,有剩余工作时恰好一个);同时为交互式宿主提供实时进度清单。调研的所有参考编码 agent(智能体)(claude-code、opencode、codex、oh-my-pi、pi)都提供了某种形式的此功能;本 harness 此前没有。 + +## 决策 + +新增一个面向模型的 `todo_write(todos: [{ content, status }])` 工具,其整列表状态作为新的 `todo/write` `SessionEventMap` 变体存储在事件溯源的会话日志上。交互式宿主从持久事件渲染;TUI 直接折叠它,而[仅面向自动化的 ACP(Agent Client Protocol)桥接层](../simplification/2026-07-23-acp-automation-only-protocol.md)有意省略 todo 展示。 + +### 整列表替换,三态 status + +模型每次调用发送完整列表;新列表替换旧列表(回放时 last-write-wins)。这是 claude-code V1、opencode 和 codex `update_plan` 共同采用的形状,也是模型训练最多的形状——没有逐项 id,没有 delta 协议。`status` 恰好是 `pending | in_progress | completed`,与 codex `update_plan` 相同的三元组;在 bridge 还把 todo 列表投影为 `plan` 更新时,它也与 ACP `PlanEntryStatus` 1:1 对应,该映射已随[仅面向自动化的 ACP 契约](../simplification/2026-07-23-acp-automation-only-protocol.md)退役。 + +### 状态在会话日志上,而非服务 + +列表作为 `todo/write` 事件追加到日志,携带完整的 `{ todos }` 快照。harness 是事件溯源的——LLM(大语言模型)历史、工具调用和轮次结构都在日志上——所以 todo 列表也在那里。这免费获得了持久性、回放和恢复重建:重新打开的会话从最新的 `todo/write` 重新推导当前列表,无需独立的持久化后端、无需重新注水的内存服务、无需额外接线。一个内存中的 `ctx.todos` 服务需要重新发明以上所有。 + +### 不是 surface 事件 + +`todo/write` 被有意排除在 `SurfaceEventType` 之外。surface 是产出 LLM 消息历史(`deriveMessages()`)的投影;todo write 不产生对话消息。因此它不携带 `surfaceOp`,不加入有序 surface,不进入 `deriveMessages()`——它是持久、可回放的 *UI* 状态,与对话并行传输但不属于对话的一部分。(dev-mode 不变式仍要求它位于一个打开的轮次内,而它始终如此:它在工具调用的步骤中途追加。) + +### 相比 claude-code V1 舍弃的字段:`activeForm`、id、priority + +claude-code V1 的条目是 `{ content, status, activeForm }`;后来(V2)增加了 id、依赖和所有权——但仅为支持 agent *集群*(磁盘持久、锁保护、逐项变更)。本工具将条目保持在最小集:`{ content, status }`。不要 `activeForm`(现在进行时标签)——UI 直接展示 `content`;不要 id——整列表替换不需要稳定标识;不要 priority——它只曾是 ACP `PlanEntry` 的协议格式(wire format)要求,在 bridge 边界合成为常量而非建模,并已随该投影一起离开。每舍弃一个字段,模型每次调用就少产出一项。 + +### 单一所有者——无集群机制(YAGNI) + +每个列表属于调用它的 agent 会话,非 agent 调用被拒绝。没有共享作用域、resolver 或 delta 协议。跨 agent 列表需要逐项日志 delta 和显式作用域选择,因此留作未来独立设计。 + +### 校验:低成本的中间路线 + +schema 强制 type/required/enum。在此之上,`execute` 拒绝为空或重复的 `content`,以及超过一个 `in_progress` 任务。claude-code 将单一 in_progress 交给提示词约束;oh-my-pi 在代码中强制。我们取中间路线:强制执行使计划*连贯*的低成本不变式(无空任务、无重复、最多一个活跃),但将排序和保持列表最新的纪律通过工具描述交给模型。被拒绝的写入返回 `isError` 结果,使模型自行修正。 + +## 为何没有 cordis-catalog 条目 / 没有 `@mode` + +`todo/write` 是 `SessionEventMap` 的成员,不是一等的 cordis `interface Events` 事件。catalog 生成器(`scripts/gen-cordis-catalog.ts`)扫描 `interface Events` 声明;`SessionEventMap` 变体搭载现有的 `session/event` emit,不产生新的 catalog 行。因此它不携带 `@mode` 标签(生成器仅对 `interface Events` 成员要求该标签)——添加一个毫无意义。 + +## 测试 + +四个层级,预先设计: +- **单元测试**——会话事件(append/snapshot-clone/last-write-wins/not-on-surface);工具(schema 形状、通过真实 `ctx.tools.execute` 的参数校验、值校验、事件追加与替换、非 agent 拒绝、`presentCall`、HMR(热模块替换)安全性);以及 TUI 折叠。 +- **真实 Loader 路径**——插件通过 `Loader.unwrapExports` 运行,断言命名空间导出形状存活(它有 `inject`,因此一个意外的 default 导出会在加载时崩溃——postmortem/0001)。 +- **全循环集成**——一个脚本化的 mock 模型通过真实 agent loop(智能体循环)调用 `todo_write`;`todo/write` 事件落地,第二次调用替换它。 +- **恢复/回放**——持久化的 `todo/write` 折叠回当前任务列表。 +- **带密钥 e2e + 快照**——真实提示词诱导 `todo_write`;组装后的快照固定日志事件和交互式渲染。 + +## 曾考虑的替代方案 + +- **内存中的 `ctx.todos` 服务**——需要重新发明日志免费提供的持久性、回放和恢复重建。 +- **逐项 delta 协议**——仅在共享多所有者列表时需要,超出当前范围;整列表替换更简单,且与参考实现一致。 +- **工具放在 `core/` 中**——`todo_write` 是注册在 `ctx.tools` 上的扩展工具,不属于主干;它像其他工具族一样位于自己的 `packages/todo/` 分组中。 + +## 后果 + +todo 列表是持久、可回放的会话状态:交互式宿主从最新持久化的 `todo/write` 重新推导它,日志(而非插件内存)是唯一真源。整列表替换意味着每次更新一次工具调用,last-write-wins;没有需要协调的 delta 协议。事件不进入模型 surface,因此 todo 更新永远不会扰动推导出的模型历史——模型只看到自己的工具调用和结果。 diff --git a/.agents/notes/implemented/feature/2026-06-30-hook-bridges.i18n.yaml b/.agents/notes/implemented/feature/2026-06-30-hook-bridges.i18n.yaml new file mode 100644 index 0000000000..1ad47cd1f6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-hook-bridges.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-30-hook-bridges.md: c207b6901155925215548676364e903f5de2f29b +2026-06-30-hook-bridges.zh.md: d396279d7ed1991536da2cea39e2aec5e50960c2 diff --git a/.agents/notes/implemented/feature/2026-06-30-hook-bridges.md b/.agents/notes/implemented/feature/2026-06-30-hook-bridges.md index 0c3c1e13ef..c207b69011 100644 --- a/.agents/notes/implemented/feature/2026-06-30-hook-bridges.md +++ b/.agents/notes/implemented/feature/2026-06-30-hook-bridges.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-30-hook-bridges.zh.md) + ## Problem The harness's extension surface is its typed interception seams ([the interception-seams Agent Note](2026-06-30-interception-seams.md)): a "native hook" is just an ordinary cordis plugin subscribing to `agent/session-start`, `agent/prompt-submit`, `tools/pre-execute`, `tools/post-execute`, `agent/turn-continuation`, `subagent/start`, `subagent/end`. But users arrive with **existing** Claude Code (CC) and Codex hook configs — a `hooks.json` (or a settings file's `hooks` key) full of shell-command hooks — and want those to run unmodified. This Agent Note introduces the two **bridge plugins** that translate that external shell-hook protocol onto the typed seams, built on the shared wire-protocol library ([the hook-protocol-lib Agent Note](2026-06-30-hook-protocol-lib.md)). @@ -29,7 +31,7 @@ Each bridge maps the neutral `MergedHookOutcome` from the shared lib onto the se | `subagent/start` (emit) | additionalContext → inject into a live in-process child; a remote child has no local injection target | unsupported by this bridge | | `subagent/end` (emit) | observe-only | unsupported by this bridge | -The CC bridge's `ask` result is a real permission path, not a terminal bridge decision: `dsh-tools` resolves it through the optional [approval seam](2026-07-06-approval-seam.md). A composed ACP answerer prompts the owning editor session and `allowed-once` proceeds; without an ApprovalService or answerer, the call fails closed to `deny`. +The CC bridge's `ask` result is a real permission path, not a terminal bridge decision: `dsh-tools` resolves it through the optional [approval seam](2026-07-06-approval-seam.md). An ACP automation client may answer the owning session's one-shot machine-policy request and `allowed-once` proceeds; without an ApprovalService or answerer, the call fails closed to `deny`. ### Context source is always the plugin (the mislabel guard) @@ -53,7 +55,7 @@ Hooks run in the agent's session workspace, so relative paths target the user's ## Deferred compatibility gaps -- **Tool-input rewrite.** A CC/Codex `updatedInput` is logged + warned, not honored — input rewrite is a deferred consistency-design problem ([the pre-tool-input-rewrite Agent Note](../../proposed/feature/2026-06-30-pre-tool-input-rewrite.md)), because the pre-execution args are read by `tool/call` audit + `assistant/message` history + ACP/tool-bash presentation, so an honest rewrite is a design unit, not a field. +- **Tool-input rewrite.** A CC/Codex `updatedInput` is logged + warned, not honored — input rewrite is a deferred consistency-design problem ([the pre-tool-input-rewrite Agent Note](../../proposed/feature/2026-06-30-pre-tool-input-rewrite.md)), because the pre-execution args are read by `tool/call` audit + `assistant/message` history + tool presentation, so an honest rewrite is a design unit, not a field. - **Stop loop-guard** (`TODO(stop-loop-guard)`). Claude Code supplies `stop_hook_active` and overrides a hook after eight consecutive blocks; Codex supplies `stop_hook_active` but documents no equivalent cap. Both bridges always report `false`, so a Stop hook that unconditionally blocks force-continues every step — a hook author must self-limit until state tracking lands. - **Hook `continue:false` (hard halt).** A hook can ask to halt the whole run (CC/Codex `continue:false`); the shared merge folds it into `MergedHookOutcome.stop`/`stopReason`, but no bridge acts on it (`TODO(hook-continue-false)`) — the interception seams have no "hard-halt the agent" primitive yet (a Decision blocks/steers a single point, not the run). Deferred with the loop-guard work; the halt request is recorded in the `hook/result` log, and the hook keeps its per-point effect (decision/context) meanwhile. - **Config discovery.** The path is explicit in `cordis.yml` and process-level (see above); the full multi-layer CC/Codex precedence walk, per-session project-local discovery, and the trust/hash model are not reimplemented (`TODO(per-session-hook-config)`). diff --git a/.agents/notes/implemented/feature/2026-06-30-hook-bridges.zh.md b/.agents/notes/implemented/feature/2026-06-30-hook-bridges.zh.md new file mode 100644 index 0000000000..d396279d7e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-hook-bridges.zh.md @@ -0,0 +1,70 @@ +# Agent Note: dsh-hooks-claude + dsh-hooks-codex —— Claude Code / Codex 钩子桥接插件 + +Status: implemented + +[English](2026-06-30-hook-bridges.md) | 中文 + +## 问题 + +harness 的扩展面是其类型化的拦截 seam(见[拦截 seam Agent Note](2026-06-30-interception-seams.md)):所谓「原生钩子」不过是一个普通的 Cordis 插件,订阅 `agent/session-start`、`agent/prompt-submit`、`tools/pre-execute`、`tools/post-execute`、`agent/turn-continuation`、`subagent/start`、`subagent/end`。但用户带着**既有的** Claude Code(CC)和 Codex 钩子配置到来,一个 `hooks.json`(或 settings 文件中的 `hooks` 键)里满是 shell 命令钩子,并希望它们原样运行。本 Agent Note 引入两个**桥接插件**,将外部 shell 钩子协议翻译到类型化 seam 上,构建于共享的协议格式(wire format)库之上(见 [hook-protocol-lib Agent Note](2026-06-30-hook-protocol-lib.md))。 + +贯穿整个设计的定位:**桥接是兼容性适配器,不是高级工具。** 桥接能做的事(阻止工具、注入上下文、强制继续、观察 subagent),原生 Cordis 插件都能做得更强——类型化返回值、完整 `ctx`、无序列化边界。桥接存在的理由是运行外部 CC/Codex 命令钩子中被明确支持的子集。这使每个桥接保持精简:解析配置、选择匹配模式、构建每事件的 payload、调用共享库的 `runHook` + `mergeHookOutputs`,再将中性结果映射为 seam Decision。各包的 README 维护着当前不支持的事件和部分字段的完整清单,以官方协议为参照。 + +## 决策 + +`packages/hooks/` 组下两个独立插件,各为 function/namespace 插件(`name`/`inject`/`Config`/`apply`,无 default export——见[事后复盘 0001](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md)),仅注入 `bash`: + +- **`dsh-hooks-claude`**——CC 方言。Claude Code 当前七个钩子点中的七个:`SessionStart`、`UserPromptSubmit`、`PreToolUse`、`PostToolUse`、`Stop`、`SubagentStart` 和 `SubagentStop`。拥有 CC 形态的每事件 stdin payload(基础字段 `session_id`/`transcript_path`/`cwd`/`hook_event_name` 加每事件字段)、`CLAUDE_PROJECT_DIR` 环境变量加 `${CLAUDE_PLUGIN_ROOT}`/`${CLAUDE_PROJECT_DIR}` 替换,以及字面量或正则的匹配模式。`transcript_path` 是持久化定位器结果或 `''`;stdin 带有**尾部换行**。 +- **`dsh-hooks-codex`**——Codex 当前五个钩子点中的五个:`PreToolUse`、`PostToolUse`、`SessionStart`、`UserPromptSubmit` 和 `Stop`。使用始终为正则的匹配模式、Codex 形态的 snake_case payload(含 `turn_id`/`model`/`permission_mode` 额外字段),写入时不带尾部换行,不注入 Codex 插件环境变量,不做配置时占位符替换,也没有 pre-tool 审批或重写路径。`transcript_path` 是同一定位器结果或 `null`;工具 payload 在精简后的 `tool_input: { command }` 形态中携带真实的 `tool_name`。 + +### Outcome → Decision 映射 + +每个桥接将共享库返回的中性 `MergedHookOutcome` 映射到 seam 的类型化 Decision: + +| Seam | CC | Codex | +|---|---|---| +| `agent/session-start`(emit) | additionalContext → `agent.inject()` | 纯 stdout 输出 → additionalContext → `agent.inject()` | +| `agent/prompt-submit` | `deny`→`block`;仅上下文→delegate+fold | `block`→`block`;仅上下文→delegate+fold | +| `tools/pre-execute` | `deny`→`deny`;`ask`→`ask` | `block`→`deny`(无 allow/ask) | +| `tools/post-execute` | `deny`→`block`+feedback;仅上下文→delegate+fold | 同上 | +| `agent/turn-continuation` | 阻塞的 Stop → `continue`(reason = 下一步 steering(中途引导)) | 同上 | +| `subagent/start`(emit) | additionalContext → 注入到存活的进程内 subagent;远程 subagent 无本地注入目标 | 本桥接不支持 | +| `subagent/end`(emit) | 仅观察 | 本桥接不支持 | + +CC 桥接的 `ask` 结果是一条真正的权限路径,而非终态桥接决策:`dsh-tools` 通过可选的[审批 seam](2026-07-06-approval-seam.md) 来解析它。ACP 自动化客户端可以应答所属会话的一次性机器策略请求,`allowed-once` 后继续执行;如果没有 ApprovalService 或应答器,调用以 `deny` 安全关闭。 + +### 上下文来源始终是插件(误标签防护) + +`agent.inject()` 在缺少 `MessageSource` 时默认为 `{ kind: 'user' }`,因此每个桥接的 `inject()` 和 `HookContext` 都传入 `{ kind: 'plugin', plugin: 'hooks-claude' | 'hooks-codex' }`。单元测试覆盖率固定验证结果中的 `context/message.source` 为插件而非用户。 + +### 添加上下文不是否决——先 delegate,再 prepend + +仅附加 `additionalContext`(没有 block/deny)的钩子并不是桥接可以独自返回的决策:在 waterfall 监听器中不调用 `next()` 就返回 `allow`/`accept`,会短路其后的每个 `agent/prompt-submit` / `tools/post-execute` 监听器,使注册在桥接之后的策略/沙箱插件看不到该提示词。因此,每个桥接都会先通过 `next()` 委托,再将自身上下文加入下游决策。两个 seam 都携带有序的 `additionalContexts` 数组,因此桥接会在保留所有下游来源、信封和元数据字段的同时,前置加入其独立来源的条目;下游提示词阻止仍会丢弃所有上下文,因为提示词从未到达模型,而工具后阻止语义可以显式保留上下文。Code Mode 会通过外层 `run_code` 结果转送同一数组。只有钩子本身真正返回 `deny`/`block` 才会短路。测试断言:上下文钩子允许后,较晚的监听器仍能阻止提示词,且保留的提示词和工具后上下文仍彼此分离。 + +### CLAUDE_PROJECT_DIR 默认为会话工作区 + +Claude Code 始终导出 `CLAUDE_PROJECT_DIR`,常见的未修改钩子引用 `$CLAUDE_PROJECT_DIR` 来构造项目相对路径。显式的 `config.projectDir` 优先;当它被省略时(默认 ACP 接线只配置 `configPath`),桥接将该环境变量按每次运行默认为 agent(智能体)的会话工作区——即钩子已经在其中运行的 `session.header.cwd`——而非留空。这样,一个标准的项目相对路径钩子在默认配置下即可正常工作。 + +### 隔离 + +配置在加载时一次性解析;读取/解析失败时记录日志并不注册任何内容,而非崩溃启动(一个拼错的路径不应拖垮 agent)。CC 桥接只运行 shell 形式的 `type: 'command'` 钩子;`http`、`mcp_tool`、`prompt` 和 `agent` 处理器被解析后跳过。Codex 桥接只运行同步命令处理器,跳过 `async: true` 或非命令条目。emit 监听路径(`session-start`、`subagent/start`)以 detached 方式运行,其 `inject` 包裹在 `.catch` 中记录日志(抛异常的 inject 不得中断会话启动或循环)。 + +### 钩子在哪里运行,配置从哪里来 + +钩子在 agent 的会话工作区中运行,因此相对路径指向用户的项目。`configPath` 相对于进程启动时的 cwd 解析一次,适用于所有会话。按会话的项目本地发现仍推迟在 `TODO(per-session-hook-config)` 下。 + +## 推迟的兼容性缺口 + +- **工具输入重写。** CC/Codex 的 `updatedInput` 被记录日志并发出警告,但不予执行——输入重写是一个推迟的一致性设计问题(见 [pre-tool-input-rewrite Agent Note](../../proposed/feature/2026-06-30-pre-tool-input-rewrite.md)),因为 pre-execution 参数被 `tool/call` 审计、`assistant/message` 历史和工具展示共同读取,诚实的重写是一个设计单元,而非一个字段。 +- **Stop 循环防护**(`TODO(stop-loop-guard)`)。Claude Code 提供 `stop_hook_active` 并在连续八次阻塞后覆盖钩子;Codex 提供 `stop_hook_active` 但未记录等效上限。两个桥接始终报告 `false`,因此一个无条件阻塞的 Stop 钩子会在每一步强制继续——在状态追踪落地之前,钩子作者必须自行限制。 +- **钩子 `continue:false`(硬停止)。** 钩子可以请求终止整个运行(CC/Codex `continue:false`);共享合并将其折叠为 `MergedHookOutcome.stop`/`stopReason`,但没有桥接对其采取行动(`TODO(hook-continue-false)`)——拦截 seam 尚无「硬停止 agent」原语(Decision 阻塞/引导的是单个点,而非整个运行)。与循环防护工作一同推迟;停止请求记录在 `hook/result` 日志中,钩子在此期间保留其逐点效果(决策/上下文)。 +- **配置发现。** 路径在 `cordis.yml` 中显式指定且为进程级(见上文);完整的多层 CC/Codex 优先级遍历、按会话的项目本地发现以及信任/hash 模型未被重新实现(`TODO(per-session-hook-config)`)。 +- **Session-start / subagent-start 上下文为尽力而为(`TODO(session-start-gating)`)。** 两个钩子以 detached 方式运行于启动过程之外,因此其上下文在就绪时注入,但可能错过首个请求或短命的 subagent。要保证首请求送达,需要一个 awaited 的启动 seam。 + +## 曾考虑的替代方案 + +**每点钩子并发执行。** 参考引擎对一个点匹配到的钩子并发运行并折叠结果。本桥接**串行**运行(匹配循环内每个钩子 `await`),并以相同的最严格合并策略折叠。串行是刻意的:它使每个钩子的 `hook/invoked`/`hook/result` 对在会话日志中相邻且顺序确定,而折叠对决策是顺序无关的(`deny > ask > allow`),因此结果一致。代价是延迟(钩子 *N* 等待钩子 *N−1*)以及每钩子超时不重叠——对真实配置中的钩子数量可以接受;如果某配置的扇出大到影响总耗时,再重新评估。 + +## 后果 + +匹配语义、退出码处理和合并优先级位于 `dsh-hook-protocol`;每个桥接只负责解析配置、构建方言 payload 和映射结果。逐文件覆盖率包含配置分支以及通过真实循环、`dsh-bash-local` 和 shell 脚本的端到端映射,同时一个真实 Loader 冒烟测试守护包的导出形态。原生插件绕过协议格式,直接返回类型化决策。 diff --git a/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.i18n.yaml b/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.i18n.yaml new file mode 100644 index 0000000000..de9949114b --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-30-hook-protocol-lib.md: 19a69119befde99417b736edf38923ec6ac5fa7c +2026-06-30-hook-protocol-lib.zh.md: f4950eea2b02e86ed7109f8ebdaab29dd77428d8 diff --git a/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.md b/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.md index bb1822504a..19a69119be 100644 --- a/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.md +++ b/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-30-hook-protocol-lib.zh.md) + ## Problem The hooks subsystem ships two bridge plugins: one that runs a user's existing Claude Code (CC) hooks, one for Codex hooks. Studying the reference implementations (`~/repos/refs/claude-code`, `~/repos/refs/codex`) surfaced a decisive fact: **Codex deliberately reimplements a SUBSET of the CC hook protocol.** Its engine reads the same `hooks.json`, uses the same matcher-group shape, the same exit-code/structured-stdout output contract, and the same command-hook execution model — Codex's source even names the engine after Claude's and comments where it "intentionally diverges." So the two bridges would otherwise duplicate the bulk of the protocol. diff --git a/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.zh.md b/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.zh.md new file mode 100644 index 0000000000..f4950eea2b --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.zh.md @@ -0,0 +1,32 @@ +# Agent Note: dsh-hook-protocol——Claude Code / Codex 钩子协议格式共享核心库 + +Status: implemented + +[English](2026-06-30-hook-protocol-lib.md) | 中文 + +## 问题 + +钩子子系统提供两个桥接插件:一个运行用户既有的 Claude Code(CC)钩子,另一个运行 Codex 钩子。研究参考实现(`~/repos/refs/claude-code`、`~/repos/refs/codex`)后发现一个决定性事实:**Codex 有意重新实现了 CC 钩子协议的一个子集。** 它的引擎读取相同的 `hooks.json`,使用相同的 matcher-group 形状、相同的 exit-code/structured-stdout 输出契约,以及相同的命令钩子执行模型。Codex 的源码甚至以 Claude 的引擎命名,并在注释中标注了「有意偏离」之处。因此,如果不做抽取,两个桥接插件将大量重复协议逻辑。 + +本 Agent Note 引入 `@deepseek-ai/dsh-hook-protocol`,一个**库**(不是插件——它不注册也不注入任何东西),持有两个桥接插件共同依赖的真正相同的原语。共享与方言专属之间的分界是本设计的重心。 + +## 决策 + +在 `packages/hooks/` 分组下新建 `hook-protocol` 作为纯库。它拥有四个原语族和 `hook/*` 会话事件;每个桥接插件(`dsh-hooks-claude`、`dsh-hooks-codex`)拥有真正不同的部分。 + +**共享(本库):** +- **Matcher** — `matchesMatcher(pattern, query, mode)`。两种方言唯一不同的轴被收敛为 `mode` 参数:`claude` 将纯 `[A-Za-z0-9_|]+` 模式视为字面量(管道符 = 精确匹配的多选),其余视为正则;`codex` 始终是无锚定正则。缺省/`''`/`'*'` 匹配一切;无效正则匹配空集(绝不向 agent loop(智能体循环)抛异常)。 +- **执行** — `runHook(bash, hook, options)`。通过 `ctx.bash` seam 而非自建 `spawn` 运行命令钩子:执行器已提供清洗但可覆盖的 env、进程组 kill 和超时,正是协议所需的能力;`dsh-bash` 的 `stdin`/`env` 字段(正是为此添加的)是进程内桥接插件被允许使用的受信插件接口。它将桥接插件构建的 payload 序列化到 stdin(CC 时追加尾部换行),遵守钩子的 `timeoutSec`(否则使用 `DEFAULT_HOOK_TIMEOUT_MS`,即两种方言共享的 10 分钟参考默认值),且从不抛异常(执行器拒绝变为 non-blocking-error 的 `HookOutput`)。 +- **解码** — `parseHookOutput(exit, stdout, stderr)`,exit-code + structured-stdout 编解码器,产出方言无关的 `HookOutput`。Exit `0` → 宽松 JSON 解析 stdout;exit `2` → blocking error,`stderr` 为原因(以 `decision: 'block'` 呈现,调用方无需单独处理 exit-code 分支);其他 → non-blocking error。解析 CC structured-stdout 中在某条路径上有消费方的字段(`continue`/`stopReason`/`decision`/`hookSpecificOutput.{permissionDecision,additionalContext,updatedInput}`/`systemMessage`);桥接插件只采纳对其方言有意义的子集。在任何路径上都没有消费方的字段不予解析(CC 的 `suppressOutput`——钩子 stdout 在此处从不进入 transcript(文本记录),因此无需抑制;见 [收紧钩子协议契约 Agent Note](../simplification/2026-07-04-tighten-hook-protocol-contract.md))。 +- **合并** — `mergeHookOutputs(outputs)`,将多个匹配钩子的输出折叠为一个最严格的 `MergedHookOutcome`:权限优先级 **deny > ask > allow**,halt 在首个 `continue:false` 时粘滞,阻止原因以 `\n\n` 拼接,context/system-messages 按序累积。 +- **`hook/*` 会话事件** — `hook/invoked` / `hook/result`,通过声明合并进入 `SessionEventMap`(仅日志,如 `compact/*`——不是 `SurfaceEventType`),配有 `appendHookInvoked`/`appendHookResult` 辅助函数,确保 invoked/result 配对与轮次包含关系在各桥接插件间保持一致。`appendHookResult` 还拥有持久化记录的语义:decision 字符串(钩子解析出的 decision,否则 `continue:false` 时为 `'stop'`,否则为 `'pass'`)和 500 字符的 `stderrSummary` 截断均从本库的 `HookOutput` 派生,而非各桥接插件各自实现。 + +**方言专属(桥接插件):** 构建每个事件的 stdin payload(CC 的 base+per-event 字段集 vs Codex 的 snake_case 加 `turn_id`/`model` 额外字段)、方言的 env 与 `${CLAUDE_PLUGIN_ROOT}` 替换(CC)vs 无替换(Codex),以及将方言无关的 `HookOutput`/`MergedHookOutcome` 映射为 harness seam 专属的类型化 Decision(`PreToolDecision`、`PromptDecision`、`ContinuationDecision`、`PostToolDecision`)。 + +## 曾考虑的替代方案 + +**单一参数化引擎。** 否决,因为 payload 构建与 decision 映射在方言间确实不同。Matcher、编解码器、执行、合并规则和事件保持共享;每个桥接插件保留自己的 payload 和映射,使其协议格式行为在代码中可就地阅读。 + +## 后果 + +每个桥接插件解析配置、构建方言 payload、调用共享的 runner 与合并逻辑、映射 decision、追加 `hook/*`。协议测试覆盖每种 matcher 模式、exit-code 与编解码器字段、runner 管道、合并优先级和审计辅助函数,逐文件 100% 覆盖率;桥接插件测试验证库的真实加载路径。`updatedInput` 已解析但仅记录日志并发出警告,直到 [input-rewrite 提案](../../proposed/feature/2026-06-30-pre-tool-input-rewrite.md)落地。 diff --git a/.agents/notes/implemented/feature/2026-06-30-interception-seams.i18n.yaml b/.agents/notes/implemented/feature/2026-06-30-interception-seams.i18n.yaml new file mode 100644 index 0000000000..ff40078df0 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-interception-seams.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-30-interception-seams.md: 81799f4c6e3e7a4c6b9605cd97f5728b99d11995 +2026-06-30-interception-seams.zh.md: 65ae16842c632641e7ac65908162f4784dc6e1e0 diff --git a/.agents/notes/implemented/feature/2026-06-30-interception-seams.md b/.agents/notes/implemented/feature/2026-06-30-interception-seams.md index a0504893d9..81799f4c6e 100644 --- a/.agents/notes/implemented/feature/2026-06-30-interception-seams.md +++ b/.agents/notes/implemented/feature/2026-06-30-interception-seams.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-30-interception-seams.zh.md) + ## Problem The harness needs a hooks subsystem: users extend or gate the agent at lifecycle points the way Claude Code (CC) and Codex do. The key reframe driving this design is that **"native hooks" are not a package** — a native hook is just an ordinary Cordis plugin subscribing to the canonical lifecycle events. So the real product is a *powerful, well-typed canonical event surface*; the CC/Codex bridges (the `dsh-hooks-claude` / `dsh-hooks-codex` packages) are merely translators that map an external shell-hook protocol onto that same surface. Anything a bridge can do, a plain plugin can do directly — more powerfully (no serialization boundary, full `ctx`, typed returns). @@ -43,7 +45,7 @@ Core dispatch and the tool body sit inside normalization boundaries, so tool, li ### Pre-tool input rewrite is a separate consistency decision -`PreToolDecision` cannot rewrite arguments. History and the audit call are logged before execution, and ACP presentation reads the same input, so the registry seals arguments before policy. A valid rewrite must update history, audit, presentation, and execution before identity is created; that contract belongs to the [input-rewrite proposal](../../proposed/feature/2026-06-30-pre-tool-input-rewrite.md). +`PreToolDecision` cannot rewrite arguments. History and the audit call are logged before execution, and UI presentation reads the same input, so the registry seals arguments before policy. A valid rewrite must update history, audit, presentation, and execution before identity is created; that contract belongs to the [input-rewrite proposal](../../proposed/feature/2026-06-30-pre-tool-input-rewrite.md). ### Boundaries diff --git a/.agents/notes/implemented/feature/2026-06-30-interception-seams.zh.md b/.agents/notes/implemented/feature/2026-06-30-interception-seams.zh.md new file mode 100644 index 0000000000..65ae16842c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-interception-seams.zh.md @@ -0,0 +1,61 @@ +# Agent Note: 拦截 seam——钩子编程所面对的类型化 Decision 表面 + +Status: implemented + +[English](2026-06-30-interception-seams.md) | 中文 + +## 问题 + +harness 需要一套钩子子系统:用户像 Claude Code(CC)和 Codex 那样在生命周期节点扩展或管控 agent(智能体)。驱动本设计的关键视角转换是:**「原生钩子」不是一个包**——原生钩子只是一个普通的 Cordis 插件,订阅规范的生命周期事件。因此真正的产品是一个*强大、类型完备的规范事件表面*;CC/Codex 桥接(`dsh-hooks-claude` / `dsh-hooks-codex` 包)只是将外部 shell 钩子协议映射到同一表面的翻译层。桥接能做的事,普通插件可以直接做——而且更强大(无序列化边界、完整 `ctx`、类型化返回值)。 + +该表面需要为以下场景提供各自独立的契约:逐提示词策略(CC 的 `UserPromptSubmit`)、会话启动观测(CC 的 `SessionStart`)、工具执行前策略、环绕调度控制、工具执行后变换、最终结果观测,以及携带面向模型的原因的继续执行。如果把这些阶段混为一谈,插件就会获得不需要的 mutation 通道,而终结性将依赖监听器的注册顺序。[事件域语义 Agent Note](../architecture/2026-06-30-event-domain-semantics.md)提供了三域规则与类型化 Decision 惯用法;本 Agent Note 将其应用于生命周期 seam。 + +## 决策 + +规范表面将可变换策略、环绕调度控制与仅观测通知分离。策略 waterfall(瀑布式事件)返回小型的、seam 专属的**类型化 Decision 联合类型**;包装层返回规范化结果;通知接收不可变快照,无法影响结果。覆盖的钩子点包括 `session-start`、`prompt-submit`、`pre-tool`、`post-tool`、通过 continuation 实现的 `stop`,同时将非钩子的执行策略留作独立可组合。 + +**Agent 事件**(`dsh-agent`): +- `agent/session-start(agent, source)` ——emit,在第 1 轮次之前触发一次,携带 `SessionStartSource`(`startup` 表示全新/fork 创建,`resume` 表示重新加载的持久化会话;`clear`/`compact` 保留)。纯通知,不能阻塞启动(这是有意的空白:桥接可以记录/注入,但不管控启动)。监听器通过 `agent.inject()` 注入上下文。 +- `agent/prompt-submit(agent, content, source, signal, next) → PromptDecision` ——waterfall,在轮次唯一取得所有权的排队消息追加为 `user/message` 之前触发。显式轮次 signal 位于最后的 `next` 之前;`allow` 可以重写提示词 `content` 或附加来源各自独立的 `additionalContexts[]`,而 `block` 会追加一条持久的 `prompt/blocked`,并拒绝这个零步骤轮次。 + +**`agent/turn-continuation`** 接收并返回一个 `ContinuationDecision`。`{action:'continue', reason?}` 可携带面向模型的内容和来源,记录为同一轮次内的下一步 steering(中途引导)——与 `/goal` step-end-steer 模式互为类型化孪生。它不是 `context/message`,因此其类型不提供持久上下文元数据。 + +### 工具流水线为每个阶段赋予一种权限 + +每次调用遵循 `tools/pre-execute` → guards → `tools/execute` → dispatch → `tools/post-execute` → 由定义拥有的 `finalizeContent` → `tools/result`。注册表对调用方输入创建快照、实体化并冻结参数、分配一个不透明 token,并在策略开始前对可见定义的最终内容回调创建快照。嵌套调用仅携带父 token。身份始终不可变;只有 `signal` 可在环绕调度时改变。日志、UI 和工具体因此对「执行了什么」达成一致。 + +- **`tools/pre-execute`** 是可扩展的 waterfall 门禁。其 `PreToolDecision` 允许、拒绝或询问。拒绝跳过 `tools/execute` 与核心调度。询问通过可选的审批 seam 解析:只有 `allowed-once` 继续通过 guards 和调度;拒绝、取消、通道不可用、审批服务缺失或无 agent 调用均规范化为拒绝。每个已解析的 decision 仍会到达后策略;抛出异常的监听器会成为最终的规范化失败。 +- **`ctx.tools.guard()`** 在整个 pre-execute waterfall 之后安装同步的、作用域感知的策略。guard 可以拒绝或弃权,永远不能强制允许,因此监听器顺序无法复活一个被最终不变式禁止的操作。 +- **`tools/execute`** 是用于超时、重试和指标插件的环绕调度 waterfall。包装层通过 `next()` 委托给核心调度,在此之前可以替换并恢复必需的 `exec.signal`,但不能移除它;包装层接收抛出异常或未知工具产生的、已完成规范化的规范成功/失败结果。包装层自行产生的成功结果会短路调度,并通过已解析的输出声明重新规范化。 +- **`tools/post-execute`** 是检查/变换 waterfall。其 `PostToolDecision` 接受、以反馈阻止、替换呈现内容或规范值,或附加 `additionalContexts`。替换值会重新校验并重新计算呈现;替换内容会保留程序化值,且不构成保密边界。返回的 decision 是受支持的变换通道。 +- **`ToolDefinition.finalizeContent`** 是一个可选、同步、完备且仅能处理内容的边界,在调用创建时随可见定义一起被快照。注册表将候选结果规范化并创建无损快照后,它恰好运行一次;候选结果包括绕过后续 waterfall 的 pre、around 或 post 监听器失败,以及为另一个结果字段创建快照时发现的错误。它可以替换 `content`,也可返回 `undefined` 保留原内容,但不能重写 `isError`、结构化错误身份、上下文或呈现元数据。工具在此执行自身最后一道内容不变式,而无需将策略失败转换为更弱的阻止 decision。 +- **`tools/result`** 是在所有变换、无损 JSON 实体化和外层错误边界之后的同步封闭通知。它接收相同的冻结执行身份和权威结果的不可变快照;观测者的失败按监听器隔离,无法改变或拒绝 `ToolRegistry.execute()` 返回的结果。 + +核心调度与工具体位于规范化边界内部,因此工具、监听器、无效规范值、渲染器/投影器、非 JSON 呈现和身份形状错误均解析为 JSON 安全的 `isError` 结果,而非逃逸出轮次。post-execute 监听器因此可以检查一个抛出异常的工具;由定义拥有的最终内容不变式也会覆盖外层流水线与候选结果实体化失败;最终观测者会同时看到执行期间的规范值,以及会话日志能够持久化的确切呈现字段。[规范工具输出契约](../architecture/2026-07-20-canonical-tool-output-contract.md)定义值/投影与持久性规则。 + +**`TurnEndReason.rejected`**(`dsh-session`):取得所有权的提示词被 `prompt-submit` 阻止的零步骤轮次。 + +### 三个承重的循环决策 + +1. **在提示词策略之前开启轮次。** 被阻止的提示词成为零步骤的 `rejected` 轮次,保持封闭性并为 ACP(Agent Client Protocol)提供持久的终结事件。否决记录 `prompt/blocked`(含原始提示词和原因),而每个允许的 `additionalContexts` 条目都注入到已开启的轮次中。依照[一次 send 对应一个轮次的简化](../simplification/2026-07-17-one-send-one-turn.md),每个取得所有权的 ordinary-send 条目都是其轮次中的唯一消息;启动前丢弃不会创建轮次。 + +2. **工具执行后的 `additionalContexts` 与异步注入进入活跃批次 FIFO,并在该批次结算时追加。** `content`/`feedback` 塑造 `execute()` 返回的结果,但每项上下文都是独立的 `context/message`,而单个步骤或组合工具可以产生许多上下文。立即追加上下文会产生 `result(c1) → context → result(c2)` 的交错,或把嵌套上下文放在外层结果之前,破坏工具调用/结果邻接性。因此 `ToolRunContext.deferContext()` 会在失败路径上也收集嵌套调度上下文,`execute()` 在 `ToolExecutionResult` 上暴露有序数组,循环再把它接纳到与执行期间 `agent.inject()` 调用相同的 FIFO 中。FIFO 在批次结算时,于每个已记录结果之后追加,其中也包括被中断轮次关闭之前。被接受的外层调用将 deferred contexts 保留在 decision contexts 之前;被外层阻止时则丢弃 deferred contexts,只暴露阻止 decision 显式提供的上下文。 + +3. **强制 `continue` 的 `reason` 通过 steering 通道入队**,使得下一步骤在循环顶部排空时将其记录为当前轮次的 steering——同一轮次内的下一*步骤* steering,而非下一*轮次*的提示词(与现有的 `hasSteering` 强制继续覆盖一致)。 + +### 工具执行前输入重写是一个独立的一致性决策 + +`PreToolDecision` 不能重写参数。历史和审计调用在执行前记录,UI 展示读取相同的输入,因此注册表在策略之前封存参数。有效的重写必须在身份创建之前同时更新历史、审计、展示和执行;该契约属于[输入重写提案](../../proposed/feature/2026-06-30-pre-tool-input-rewrite.md)。 + +### 边界 + +seam 包**不**声明 `hook/*` 会话事件(持久的钩子调用日志);那些属于 `dsh-hook-protocol`,因为原生插件使用类型化 decision 而无需外部钩子日志。原生插件集成测试(`packages/core/agent-loop/tests/interception.spec.ts`)通过真实循环组合这些 seam,不涉及 `hook/*` 协议。压缩(compaction)(`PreCompact`/`PostCompact`)、Notification 和 Codex `PermissionRequest` 不在本决策范围内。[审批 seam](2026-07-06-approval-seam.md) 通过 `ctx.approval` 解析 `ask` decision,而终结性的单调停止由 `agent/turn-stop` 独立负责。 + +## 曾考虑的替代方案 + +- **将工具执行前输入重写作为本 seam 集的一部分发布**:推迟,视为越界信号;上文已阐述一致性问题(审计、历史和展示都读取执行前记录的 `tool/call.arguments`),[工具执行前输入重写提案](../../proposed/feature/2026-06-30-pre-tool-input-rewrite.md)负责该设计。 +- **将持久的 `hook/*` SessionEvents 与 seam 一起声明**:否决。原生插件使用类型化 Decision 而完全不需要钩子日志(实际示例已证明),因此持久日志属于[钩子协议库](2026-06-30-hook-protocol-lib.md),而非 seam 表面。 + +## 后果 + +规范拦截表面具有统一的类型化,同时不给每个扩展相同的权力:钩子返回 decision,执行包装层做包装,终结 guard 只能拒绝,最终观测者只能观测。循环负责 session-start、prompt-submit、工具执行后上下文缓冲和 continuation;`dsh-tools` 负责身份封存与五阶段执行流水线。它们的契约记录在 [architecture.md](../../../../docs/architecture.md)、各包 README、[核心拦截 decision](../../../../docs/core-data-structures/core.md#interception-decisions) 与[工具结构](../../../../docs/core-data-structures/tools.md)中。ACP 桥接将 `rejected` 轮次映射为其 `cancelled` 编解码值,而钩子驱动的快照端到端验证可观测的桥接行为。 diff --git a/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.i18n.yaml b/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.i18n.yaml new file mode 100644 index 0000000000..b535ef6081 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-30-session-store-fork-api.md: 13d411e915b2e34b15a12e632f1a5e047f4aeedc +2026-06-30-session-store-fork-api.zh.md: bcf15eb581af3993ed2d71a2b7dc604faa6e4433 diff --git a/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.md b/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.md index ee67af7d96..13d411e915 100644 --- a/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.md +++ b/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-30-session-store-fork-api.zh.md) + ## Problem The event-sourced session log already has the primitive a fork needs: create a new session with a seed event prefix, then derive model history from that seeded log exactly as replay does. That primitive is intentionally low-level: `ctx.sessions.create(id, { seed, meta })` accepts any valid seed, but ordinary live-session branching needs policy around which prefix can be copied, which metadata is stamped on the child, and how errors are classified. @@ -38,4 +40,4 @@ An empty prefix is forkable; any non-empty boundary must be a safe existing sequ The public surface stays small and discoverable: live session branching is part of `ctx.sessions`, next to `create({ seed })`, rather than a standalone service or a two-step helper pair. Persistence continues to work through existing `session/created` and `session/flush` behavior: a forked child starts life with seeded events, so existing backends persist that seed once and preserve `parentSession` / `seedLength` in the header. -The v1 scope still excludes ACP `session/fork`, unloaded persisted-session forking, model-facing tools, and subagent refactors. If a future ACP method is added, it should advertise the capability only after it has transcript/snapshot coverage; this Agent Note adds no editor-facing updates, so no ACP snapshot is required now. Fork-child replay remains covered by the existing [seed-boundary testing Agent Note](../testing/2026-06-22-fork-child-replay-seed-boundary.md), while this API gets focused `dsh-session` unit tests plus JSONL persistence coverage. +The v1 scope still excludes ACP `session/fork`, unloaded persisted-session forking, model-facing tools, and subagent refactors. If a future ACP method is added, it should advertise the capability only after it has protocol and snapshot coverage; this Agent Note adds no ACP wire behavior, so no ACP snapshot is required. Fork-child replay remains covered by the existing [seed-boundary testing Agent Note](../testing/2026-06-22-fork-child-replay-seed-boundary.md), while this API gets focused `dsh-session` unit tests plus JSONL persistence coverage. diff --git a/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.zh.md b/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.zh.md new file mode 100644 index 0000000000..bcf15eb581 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-session-store-fork-api.zh.md @@ -0,0 +1,43 @@ +# Agent Note: SessionStore fork API + +Status: implemented + +[English](2026-06-30-session-store-fork-api.md) | 中文 + +## 问题 + +事件溯源的会话日志已经具备 fork 所需的原语:创建一个带有种子事件前缀的新会话,然后像回放一样从该种子日志推导模型历史。这个原语有意保持底层:`ctx.sessions.create(id, { seed, meta })` 接受任何合法种子,但常规的活跃会话分支需要围绕以下问题制定策略:哪些前缀可以被复制、子会话应打上哪些元数据、以及错误如何分类。 + +语义上的风险在于 fork 边界。一个合法的用户可见 fork 种子必须是连续的且封闭在轮次内。如果在一个活跃轮次内部 fork,会复制一个未关闭的 `turn/start`、可能还有一个未关闭的 `step/start`,以及可能悬空的工具调用。这违反了轮次封闭性与提供方 transcript 不变式,并且会创建一段误导性的子历史——看起来子会话参与了父会话中一个尚未完成的轮次。现有的 [subagent seam](2026-06-21-subagent-capability-seam.md) 有意解决的是另一个问题:工具触发的 subagent fork 通常发生在父轮次仍然打开时,因此 `dsh-subagent-fork` 会将种子裁剪到父会话最后一个已完成轮次的前缀。通用的会话 fork 不应静默裁剪;它应当要么在请求的边界处 fork,要么拒绝请求。 + +## 决策 + +`dsh-session` 直接在 `ctx.sessions` 上拥有常规活跃会话 fork 的能力。不设独立的 `dsh-session-fork` 包(package),也不设 `ctx.sessionFork` 服务:该 API 没有独立的后端、事件词汇、生命周期或持久化行为,所有持久化工作都委托给现有的会话存储和持久化后端。 + +store 暴露一个操作: + +```ts ignore-check +type SessionForkSource = Session | SessionId + +class SessionStore extends Service { + fork(source: SessionForkSource, boundary?: number, childSessionId?: SessionId): Session +} +``` + +`boundary` 是要复制到的源事件 `seq`(含该序号)。省略时默认为源会话当前的最后一个事件;对空源会话省略 `boundary` 则创建一个空的子会话。fork 特有的校验仅检查请求的边界是否存在且为 `turn/end`。选定的前缀随后被深拷贝到子会话的种子中。子会话继承源会话的 `cwd`,将 `parentSession` 设为源会话 id,并将 `seedLength` 设为已复制前缀的长度。省略 `childSessionId` 时,`SessionStore` 使用其现有的 id 策略生成一个。 + +空前缀可以被 fork;任何非空边界都必须是一个安全的、已存在的、位于 `turn/end` 的序号,无论结束原因为何。类型化的错误区分源缺失、对象陈旧、子 id 重复和边界无效等情况。更广泛的日志校验与崩溃恢复仍由其现有的负责方处理。 + +## 曾考虑的替代方案 + +**独立的 `ctx.sessionFork` 服务。** 这是最初的实现,但评审表明它过度套用了 capability-seam 模式。代码没有可替换的后端、没有额外的事件面、没有独立的所有权生命周期,也没有超出 `ctx.sessions.create({ seed, meta })` 的持久化行为。保留独立包会迫使调用方为了在会话存储原语之上执行一层策略而去发现并安装第二个服务。 + +**两个函数:`snapshot()` 加 `fork()`。** 这保留了一个可复用的种子/元数据计算,但唯一支持的消费方会立即创建会话。它还使接口看起来比用户实际需要的具体操作更抽象。单一的 `fork()` 加显式 `boundary` 使 API 保持直接,同时仍支持对先前时间点的 fork。 + +**静默裁剪未关闭轮次到最后一个已完成边界。** 这对 `dsh-subagent-fork` 是正确的——委托通常在父轮次仍然打开时开始,子会话应只继承已完成的前缀。但对常规的用户/会话分支而言是错误的,因为它隐藏了请求的 fork 点实际上不是合法边界这一事实,并且静默丢弃了父轮次的尾部。 + +## 后果 + +公开接口保持精简且易于发现:活跃会话分支是 `ctx.sessions` 的一部分,紧邻 `create({ seed })`,而非一个独立服务或一对两步辅助函数。持久化继续通过现有的 `session/created` 和 `session/flush` 行为运作:fork 出的子会话以种子事件开始生命,因此现有后端只需持久化该种子一次,并在 header 中保存 `parentSession`/`seedLength`。 + +v1 范围仍然排除 ACP(Agent Client Protocol) `session/fork`、对未加载的已持久化会话的 fork、面向模型的工具,以及 subagent 重构。如果未来添加 ACP 方法,应在具备协议与快照覆盖后才广播该能力;本 Agent Note 不添加任何 ACP 协议行为,因此不需要 ACP 快照。fork 子会话的回放仍由现有的[种子边界测试 Agent Note](../testing/2026-06-22-fork-child-replay-seed-boundary.md) 覆盖,而本 API 则获得专门的 `dsh-session` 单元测试加 JSONL 持久化覆盖。 diff --git a/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.i18n.yaml b/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.i18n.yaml new file mode 100644 index 0000000000..c7281e3189 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-30-subagent-observe-enrich.md: a07cef95630689d1ca8cacd3eb7c50e691cb304a +2026-06-30-subagent-observe-enrich.zh.md: 578aae0a7273defcc1f88fb2a50c83ef454e3c16 diff --git a/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.md b/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.md index 861779fc50..a07cef9563 100644 --- a/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.md +++ b/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-30-subagent-observe-enrich.zh.md) + ## Problem The hooks subsystem ([interception seams Agent Note](2026-06-30-interception-seams.md)) lets a plugin observe and gate the agent at lifecycle points. Claude Code and Codex both expose **SubagentStart / SubagentStop** hooks, and CC's carry the subagent's final message. The harness already emits `subagent/start` and `subagent/end` lifecycle events ([the subagent capability-seam](2026-06-21-subagent-capability-seam.md)), but their payloads were minimal (`provider`, `id`, and on end `stopReason`) — not enough for a hooks bridge to report WHAT a subagent produced without separately reaching for the live run. diff --git a/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.zh.md b/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.zh.md new file mode 100644 index 0000000000..578aae0a72 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.zh.md @@ -0,0 +1,31 @@ +# Agent Note: Subagent 生命周期丰富化——lastAssistantMessage(仅观察) + +Status: implemented + +[English](2026-06-30-subagent-observe-enrich.md) | 中文 + +## 问题 + +钩子子系统([拦截 seam Agent Note](2026-06-30-interception-seams.md))允许插件在生命周期节点观察和拦截 agent(智能体)。Claude Code 和 Codex 都暴露了 **SubagentStart / SubagentStop** 钩子,且 CC 的钩子携带 subagent 的最终消息。harness 已经发出 `subagent/start` 和 `subagent/end` 生命周期事件([subagent 能力 seam](2026-06-21-subagent-capability-seam.md)),但其载荷极为精简(`provider`、`id`,以及 end 时的 `stopReason`),不足以让钩子桥接层在不单独访问活跃 run 的情况下报告 subagent 产出了什么。 + +本 Agent Note 丰富 end 载荷。它刻意限定为**仅观察**:不改变控制流,不引入 waterfall(瀑布式事件)。影响 run 的 subagent-stop 决策(续行、改变 run 的注入)属于另一个更大的重设计,不在本 Agent Note 范围内。 + +## 决策 + +**在 `SubagentRunEndInfo` 中添加 `lastAssistantMessage`——子 agent 的最终输出。** 在正常结束路径上,它是只读的类型化 `SubagentResult.output`,观察者无需持有 run 即可看到子 agent 产出了什么。在基础设施拒绝(不存在 `SubagentResult`)的情况下,该字段缺失,事件报告 `stopReason: 'error'`。提供方与监听方是受信任的同进程协作者,遵守借用不可变载荷的契约。 + +两个事件仍为普通 **`emit`**。异步的 `SubagentService.start()` 将结果观察附加到就绪的提供方 run 上,发出 `subagent/start`,然后返回该 run;进程内监听方因此可以通过 `ctx.agents.get(info.id)` 访问已发布的子 agent,而远程提供方无需在本地注册表中有对应条目。提供方启动被拒绝时不发出任何事件。回调保持仅观察,且逐监听方隔离确保一个异常订阅者不会阻塞活跃 run 或饿死后续监听方。 + +## 曾考虑的替代方案 + +**`agentType` subagent 类别标签**(CC 的 `subagent_type` 在 harness 中的对应物),放在请求与两个生命周期载荷上。早期草案曾包含它;评审中移除,因为它是 Claude Code 的概念,不适合我们自己的 seam(此处没有任何逻辑解释它,唯一消费方是 CC 方言桥接层)。CC 桥接层改为直接为其 SubagentStart/Stop 的 `agent_type` matcher 填入 Claude Code 自身的默认值 `"general-purpose"`,因此本 Agent Note 只交付**一项**丰富化:`lastAssistantMessage`。 + +**控制流式 `subagent/end`**:推迟;见下文。 + +## 为何仅观察,以及推迟了什么 + +控制流式 `subagent/end`(一个被 await 的 waterfall,返回停止/继续决策,与其他拦截 seam 一致)需要:将 `subagent/end` 从 emit 改为 waterfall、重构 `SubagentService.start` 使其在结算前 await 监听方、在进程内提供方中实现 `resume` 能力以便「继续」能真正重新运行子 agent。这属于[能力 seam Agent Note](2026-06-21-subagent-capability-seam.md) 已推迟的后台/steering(中途引导)subagent 重设计(同一个重设计还将统一 subagent 与 bash 之间的长时间运行工具处理)。本 Agent Note 交付钩子桥接层当前所需的仅观察丰富化;`FIXME(subagent-continuation)` / `TODO` 锚点标记了控制流版本在重设计发生时的落点。 + +## 后果 + +钩子桥接层(或原生插件)现在可以通过订阅既有 emit 将子 agent 的 `lastAssistantMessage` 转发给 SubagentStop 处理器,无需新的控制流接口。词汇新增记录在 [docs/core-data-structures/subagent.md](../../../../docs/core-data-structures/subagent.md)(事件行文部分)与两个 subagent README 中;catalog 已重新生成。生产行为无变化——事件触发方式与之前完全一致,end 载荷上多了一个可选字段——因此无需更新快照或 e2e 测试。 diff --git a/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.i18n.yaml b/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.i18n.yaml new file mode 100644 index 0000000000..cc2e199e60 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-05-dynamic-workflows.md: bba62098c66477a3f1929f9029e81c645bfc4d41 +2026-07-05-dynamic-workflows.zh.md: 6aa1ce63f0edf9dbf296d12d3bc0c62594fa33a6 diff --git a/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md b/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md index fcd0b66062..bba62098c6 100644 --- a/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md +++ b/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-05-dynamic-workflows.zh.md) + ## Problem The harness can delegate ONE task to ONE child (`dsh-tool-subagent`), but work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — forces the model to orchestrate turn by turn: every intermediate result lands in the parent context, the plan lives nowhere durable, and coordination costs a model round-trip per step. Claude Code ships this capability as [dynamic workflows](https://code.claude.com/docs/en/workflows): the model writes a JavaScript orchestration script, a runtime executes it, and the script — not the conversation — holds the loop, the branching, and the intermediate results. @@ -58,7 +60,7 @@ Worker-side logic runs through an in-process `MessageChannel` so V8 coverage mea - **Nested `workflow()`**, **token `budget`**, and the `effort`/`isolation`/`agentType` agent options (each rejects loud with a message naming it deferred). - **An overall run wall-clock timeout** — cancellation always frees the caller (result settles within the grace), so a cap on total run time is a policy knob for the background redesign, not a correctness need here. - **Engine hardening beyond worker threads**: an isolated-vm or separate-process engine behind the same seam (actual sandboxing; memory limits). -- **ACP progress UI** over the `workflow/*` events (a `/workflows`-style view); the events exist for it. +- **Human-interface progress UI** over the `workflow/*` events (a `/workflows`-style view); the events exist for it. - **ACP-backend structured output** and **`toolFilter`** (both still capability-gated `false`). ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.zh.md b/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.zh.md new file mode 100644 index 0000000000..6aa1ce63f0 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.zh.md @@ -0,0 +1,80 @@ +# Agent Note: 动态工作流——脚本驱动的多 agent 编排 seam + +Status: implemented + +[English](2026-07-05-dynamic-workflows.md) | 中文 + +## 问题 + +harness 可以将一个任务委派给一个子 agent(`dsh-tool-subagent`),但需要扇出到多个独立部分的工作——跨多文件审计、迁移、多角度调研、对抗式验证——迫使模型逐轮次编排:每个中间结果都落入父上下文,计划无处持久存储,每一步的协调都要消耗一次模型往返。Claude Code 以[动态工作流](https://code.claude.com/docs/en/workflows)的形式提供了这一能力:模型编写一段 JavaScript 编排脚本,运行时执行它,由脚本(而非对话)持有循环、分支和中间结果。 + +## 决策 + +在 `packages/workflow/` 下以 bash seam 的形态(接口/实现/消费方)提供一组工作流能力,以及它在 subagent seam 上所需的结构化输出基础。 + +### 脚本契约(兼容 Claude Code) + +一次工作流调用包含 JSON `meta`(`name`、`description`,以及可选的 `whenToUse`/`phases`)和一段支持顶层 `await` 并返回 JSON 值的 JavaScript `script` 正文。元数据作为数据校验,从不被执行。正文接收 `agent(prompt, options)`、`parallel(thunks)`、`pipeline(items, ...stages)`、`phase(title)`、`log(message)` 和 `args`。流水线各阶段接收 `(prev, item, index)`,阶段之间无屏障;失败的子 agent 和普通阶段错误将受影响的 item 解析为 `null` 并跳过其剩余阶段。Claude Code 的确定性限制通过日志化延迟处理,因此兼容的脚本正文在将 meta 头移入参数后可以使用时钟和随机数。 + +与 CC 有一处刻意的严格性差异:钩子误用——未知或延迟的选项(`effort`/`isolation`/`agentType`)、格式错误的参数、超出支持子集的 schema、触发上限、seam 启动失败——会抛出带 `fatal: true` 的 `WorkflowError`,组合器会重新抛出 fatal 错误而非将 item 置为 null。如果不这样做,一个拼错的选项会悄然变成一个与子 agent 失败无法区分的 `null`——这正是本仓库禁止的「被接受后被忽略」的失败模式。另有一处新增:工具的 `args` 参数是一个 JSON 对象(裸列表被包装为一个字段),使协议格式(wire format)保持诚实。 + +### seam(dsh-workflow) + +`ctx.workflows` 是 bash 形态的抽象 `WorkflowService`——每个上下文一个引擎,无命名提供方注册表(引擎是部署级替换,不是共存者)。`start(request)` 对无法启动的脚本同步抛出;返回的 `WorkflowRun` 的 `result` 永不 reject(失败解析为 `stopReason: 'error' | 'cancelled'`)。`workflow/*` 事件是仅观察的 emit,携带数据快照(id + meta;`workflow/end` 省略 result 值),按监听器隔离,与 `subagent/start`/`subagent/end` 对称——控制权留在 run 的持有者手中。词汇详情见 [core-data-structures/workflow.md](../../../../docs/core-data-structures/workflow.md)。 + +### 引擎(dsh-workflow-workerthread):每次运行一个 worker 线程 + +**信任前提**:工作流脚本与模型的 bash 访问具有相同的信任级别。引擎容纳有缺陷的脚本,并保证结果已 settled、值为 JSON 安全、取消后完全停稳;它不防御恶意代码。vm 上下文和 worker 线程不是安全边界:脚本可以逃逸到具有进程级权限的 Node API。沙箱化需要在此 seam 背后使用独立进程或 isolated-vm 引擎。 + +**为何选择 `node:worker_threads`**:每次运行获得一个非池化的 worker。vm 上下文限制了文档化的脚本表面,而消息端口 RPC 将 `agent()` 桥接到宿主侧的子循环。worker 防止脚本的同步工作阻塞宿主,提供序列化边界,并允许取消后强制终止。`isolated-vm` 因其维护状态和部署要求被否决。 + +宿主在发布前校验元数据并解析正文。私有枚举键 payload 映射定义协议格式;待启动记录、已发布子记录、单一取消信号、worker 死亡回收、结果优先级与 dispose 完全停稳,在此协议上保持 subagent run 契约。这些竞态算法归[agent 作用域运行时设计 Agent Note](../architecture/2026-07-12-agent-scope-runtime-design.md#workflow-children-are-pending-starts-or-published-records)所有。 + +引擎暴露一条进程内 `MessageChannel` 测试路径,因为主进程 V8 覆盖率无法观测 worker 执行。 + +**Meta 是数据**:经 schema 校验的 `meta` 字段以 JSON 形式到达 seam,仅做形状校验。宿主从不执行元数据字面量,否则脚本控制的访问器可以在 worker 隔离之外运行。 + +**值边界**:`materializeFromRealm` 复制出站值,并拒绝函数、symbol、嵌套 `undefined`、异域原型、循环引用、稀疏数组和非有限数字。数据属性复制使 `"__proto__"` 安全;getter 正常读取,抛出异常的 getter 会大声失败。`args` 通过 `workerData` 传入,暴露前再次克隆。realm 函数被调用而非复制,抛出的值使用全量渲染器,因此 `result` 不会 reject。钩子错误是宿主 realm 的 `WorkflowError`,脚本应基于 `name` 或 `code` 分支而非 `instanceof Error`,如引擎 README 所述。并发、total-agent、item、超时和宽限限制均为经校验的配置。 + +### 消费方(dsh-tool-workflow) + +一个 `workflow` 工具,镜像 `dsh-tool-subagent` 的同步形态:启动、await、`try/finally` dispose、abort 桥接 `exec.signal`、非 `completed` → `isError`。渲染意图:一张以调用的 `meta.name` 参数为标题的 `generic` 卡片(展示是参数的纯函数)。工具描述即面向模型的编写规范。使用策略以工具自身的 `tool:<toolName>` 提示词段落随工具发布(显式请求才使用的引导——工具引导存在于工具插件中,从不在部署 persona 中);harness 没有 ultracode 风格的 effort 门控。 + +### 基础:subagent seam 上的结构化输出 + +`SubagentStartRequest.outputSchema` 由 `dsh-subagent-inprocess` 为两个进程内后端实现。每个结构化子 agent 在 `child.ctx` 上获得自己的作用域捕获工具、指令和强制注册;并发子 agent 可以使用不同的 schema 而不共享可变策略,dispose 子 agent 时移除整个附件。 + +输出 schema 使一次 schema 有效的已提交捕获成为子 agent 成功完成的必要条件。作用域运行时呈现捕获工具和指令,仅提交成功的最终结果(包括 SDK 调用时外层 `run_code` 的结果),在捕获变为 pending 后拒绝后续副作用,并在提交后不再进行模型步骤即停止子 agent。校验失败仍是可重试的工具错误;没有已提交捕获的正常完成以错误结算。 + +`ObjectJsonSchema` 是 `dsh-tools` 统一且可强制执行的原始 JSON Schema 子集所提供的对象根消费方视图;不支持的关键字会大声失败,因为该协议数据会逐字成为捕获工具的 parameters。[统一 JSON 值 schema Agent Note](../architecture/2026-07-20-unified-json-value-schema-dsl.md)定义词汇与校验语义,[agent 作用域运行时设计 Agent Note](../architecture/2026-07-12-agent-scope-runtime-design.md#structured-output-commits-only-authoritative-outcomes)则定义组装、提交、守卫和终止停止算法。 + +## 测试 + +worker 侧逻辑通过进程内 `MessageChannel` 运行,使 V8 覆盖率能够度量它。单元测试覆盖脚本辅助函数、fatal 与 nullable 失败、JSON 边界、上限、取消、子 agent 所有权和通过真实循环的结构化输出。built-bin 冒烟测试在纯 Node 下运行单独打包的 `lib/worker.cjs`,带密钥的 e2e 驱动真实子 agent,面向模型的工作流行为通过其所属示例进行快照覆盖。 + +## 延迟(本轮明确的非目标) + +- **后台收集**(启动工具 → run id → 完成通知 → 收集),与 bash/subagent 后台统一一起设计。 +- **日志化 + 恢复**(`resumeFromRunId`、缓存的 agent() 前缀):实现它会以脚本契约收紧的形式重新引入 CC 的确定性禁令(脚本目前可以读取时钟)。 +- **保存/打包的工作流**(`.deepseek/workflows/` 注册表、斜杠命令界面)和**脚本持久化到运行目录**(工具调用事件已经持久记录了脚本)。 +- **嵌套 `workflow()`**、**token `budget`**,以及 `effort`/`isolation`/`agentType` agent 选项(每个都以命名延迟的消息大声拒绝)。 +- **整体运行的挂钟超时**:取消总能释放调用方(result 在宽限期内 settle),因此总运行时间上限是后台重设计的策略旋钮,不是此处的正确性需求。 +- **超越 worker 线程的引擎加固**:在同一 seam 背后使用 isolated-vm 或独立进程引擎(真正的沙箱化;内存限制)。 +- **面向人类界面的进度 UI**(基于 `workflow/*` 事件的 `/workflows` 风格视图);事件已为此而存在。 +- **ACP 后端结构化输出**和 **`toolFilter`**(两者仍以能力标志 `false` 门控)。 + +## 曾考虑的替代方案 + +- **宿主侧的恶意值防护**(无 trap 代理拒绝、从不调用访问器的描述符遍历、realm 侧预渲染抛出值、realm 构建的 promise/array/error 克隆加结构化 fatal 识别):否决。每项防御针对的都是信任前提所接受的作者,而线程的序列化边界已经从构造上使跨 realm 值全量化。 +- **进程内 `node:vm` 执行**:机械上最简——无 RPC、无线程——但 `start()` 会在脚本的初始同步切片期间阻塞调用方,第一个 await 之后的同步自旋无法在进程内终止(vm `timeout` 仅覆盖第一个切片),且 `dispose()` 只能在宿主循环上放弃一个未 settle 的脚本。worker 线程引擎保持相同的 vm 上下文脚本表面,同时解除宿主阻塞并使终止成为现实。 +- **后台执行作为默认**(CC 的形态):延迟。前台同步与 `dsh-tool-subagent` 的当前形态一致,后台语义应在 bash、subagent 和工作流之间统一设计一次,而非逐工具设计。 +- **工作流层为 `agent({schema})` 做 JSON 解析**:在一个消费方重复 seam 关注点,而 seam 的能力标志仍不诚实地为 `false`。 +- **Meta 嵌入脚本中作为 `export const meta = {...}`**(CC 的确切格式):保持脚本自包含且 CC 脚本可直接使用,但获取 meta 需要在宿主上执行模型编写的文本。即使一个空的限时 vm 上下文也无法约束脚本控制的 getter(当宿主读取结果对象时)。JSON 参数消除了扫描器、执行和宿主自旋漏洞;代价是 CC 脚本的 meta 头必须移入参数(正文保持可直接使用)。 +- **`ValueSchemaSpec` 作为 `outputSchema` 协议类型**:面向作者的形式如今具有等价词汇,但工作流提供的是来自其他 realm 的原始 JSON Schema 数据;将这类运行时数据假装成可信的作者声明,会跳过原始 schema 断言边界。 +- **schema 对象库(zod 或本仓库的 schemastery)用于结构化输出子集**:schema 是协议数据——纯 JSON,跨越 `agent({schema})` 中的 vm realm 边界并逐字落入强制工具的 parameters——正是活 schema 对象无法存在的位置;在运行时消费原始 JSON Schema 需要在其上加一个第三方转换器(zod core 只输出 JSON Schema,不能反向),且会在 schemastery 的配置角色旁边放置第二种 schema 语言。 +- **ajv 用于值校验**:它校验完整 JSON Schema,因此子集门控——模块的真正要点,因为每个被接受的关键字都必须是 harness 强制执行的——无论如何仍需手写;它通过 `new Function` 编译校验器;且它将成为 dsh-tools 的第一个运行时依赖,仅为替换约 70 行的值遍历器,而路径限定的、报告每一处违规的错误报告无论如何都是自定义的。 +- **提供方 JSON 模式代替捕获工具**:它保证有效 JSON,不保证 schema 一致性,且它与工具调用的交互不明确。捕获工具保留了轮次内的校验重试。提供方侧的严格工具 schema 后续可以在不改变本设计的情况下收窄接受的子集。 + +## 后果 + +扇出计划现在存在于可重运行的脚本中,`outputSchema` 提供权威的结构化子 agent 结果。每次运行付出 worker 启动和消息端口 RPC 成本,但宿主启动保持非阻塞,取消可以终止 worker,序列化强制执行值边界。worker 线程不是安全边界。无效选项快速失败而非退化为 Claude Code 的 `null`;消费方通过 run handle 保持控制权,观察者仅接收快照。 diff --git a/.agents/notes/implemented/feature/2026-07-05-skill-system.i18n.yaml b/.agents/notes/implemented/feature/2026-07-05-skill-system.i18n.yaml new file mode 100644 index 0000000000..9cd21cbb39 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-05-skill-system.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-05-skill-system.md: 95772067b3b224f15fd290876c297eccbe5ab97e +2026-07-05-skill-system.zh.md: 589410076b6da1b108b01f55bf217001b2a8404f diff --git a/.agents/notes/implemented/feature/2026-07-05-skill-system.md b/.agents/notes/implemented/feature/2026-07-05-skill-system.md index eccc58f7c2..95772067b3 100644 --- a/.agents/notes/implemented/feature/2026-07-05-skill-system.md +++ b/.agents/notes/implemented/feature/2026-07-05-skill-system.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-05-skill-system.zh.md) + ## Problem Agent products have converged on a skill pattern: keep the request prompt small by listing only available instruction bundles, then load the full body when the model decides a task matches. Codex, Claude Code, OpenCode, and Kimi Code differ in details, but all separate discovery metadata from complete instructions so a workspace can carry reusable behavior without paying the full prompt cost on every turn. @@ -10,7 +12,7 @@ DeepSeek Harness uses the same primitive so project-specific review, plugin-auth ## Decision -`@deepseek-ai/dsh-skill` is the pure provider registry (`ctx.skills`), `@deepseek-ai/dsh-skill-local` is the shipped local filesystem provider, and `@deepseek-ai/dsh-tool-skill` owns the session-prefix catalog and model-facing loader tool. `dsh-agent-spine-demo` loads the registry, local provider, and consumer by default so stdio and ACP apps get the same behavior while embedded or remote providers contribute skills without changing the registry or consumer. Its `skills` config forwards `registry`, `local`, and `tool` branches to those owners. +`@deepseek-ai/dsh-skill` is the pure provider registry (`ctx.skills`), `@deepseek-ai/dsh-skill-local` is the shipped local filesystem provider, and `@deepseek-ai/dsh-tool-skill` owns the session-prefix catalog and model-facing loader tool. `dsh-agent-spine-demo` loads the registry, local provider, and consumer by default so TUI, headless, and ACP apps get the same behavior while embedded or remote providers contribute skills without changing the registry or consumer. Its `skills` config forwards `registry`, `local`, and `tool` branches to those owners. Provider plugins register synchronously during `apply()`. Provider membership is direct effect-owned state: registration and disposal invalidate completed catalogs synchronously, and discovery reads the current provider map on demand rather than observing registry-change events. Provider catalogs return ranked candidates from awaited `list()` calls, where remote providers perform initialization, authentication, and discovery while honoring the lookup abort signal. The registry validates each candidate, resolves same-name skills first-wins by rank, provider registration order, and provider-local order, then sorts summaries by skill name for deterministic consumers. It caches only completed catalog snapshots and retries when a provider/runtime revision changes during discovery, so an unload cannot freeze a stale, unresolvable skill into a session prefix. Runtime `ctx.skills.register(...)` remains a convenience for embedded in-process skills and uses project-over-user priority; `runtime` is reserved as the registry-owned provider name. @@ -30,7 +32,7 @@ The data structures and catalog/tool contract are documented in [skills.md](../. **Inject full skill bodies into every system prompt.** Rejected because it destroys progressive disclosure and makes every request pay for instructions that may not apply. -**Expose skills only as slash commands.** Rejected because model-initiated loading is the core capability; slash/ACP command advertisement does not change discovery. +**Expose skills only as slash commands.** Rejected because model-initiated loading is the core capability; human command advertisement does not change discovery. **Put local filesystem scanning directly inside `ctx.skills`.** Rejected because coding agents, web agents, and future plugin ecosystems need different skill sources. A provider registry mirrors the subagent seam: the registry owns conflict resolution and consumers, while implementations own loading. diff --git a/.agents/notes/implemented/feature/2026-07-05-skill-system.zh.md b/.agents/notes/implemented/feature/2026-07-05-skill-system.zh.md new file mode 100644 index 0000000000..589410076b --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-05-skill-system.zh.md @@ -0,0 +1,55 @@ +# Agent Note: Skill 系统——面向 agent 的渐进式指令披露 + +Status: implemented + +[English](2026-07-05-skill-system.md) | 中文 + +## 问题 + +Agent(智能体)产品已趋同于一种 skill(技能)模式:保持请求提示词精简,仅列出可用的指令包,当模型判定某任务匹配时再加载完整正文。Codex、Claude Code、OpenCode 与 Kimi Code 在细节上各有不同,但都将发现元数据与完整指令分离,使工作区能承载可复用的行为而无需在每个轮次支付全量提示词开销。 + +DeepSeek Harness 使用同一原语,使项目特定的评审、插件编写和工具使用指南存放在工作区或用户的 agent 配置旁,而非硬编码到 agent loop(智能体循环)中。 + +## 决策 + +`@deepseek-ai/dsh-skill` 是纯提供方注册表(`ctx.skills`),`@deepseek-ai/dsh-skill-local` 是随附的本地文件系统提供方,`@deepseek-ai/dsh-tool-skill` 负责会话前缀目录与面向模型的 loader 工具。`dsh-agent-spine-demo` 默认加载注册表、本地提供方和消费方,使 TUI、headless 与 ACP(Agent Client Protocol)应用获得相同行为,同时嵌入式或远程提供方可在不修改注册表或消费方的前提下贡献 skill。其 `skills` 配置将 `registry`、`local` 和 `tool` 分支分别转发给对应的所有者。 + +提供方插件在 `apply()` 期间同步注册。提供方成员资格是由直接 effect 持有的状态:注册与 dispose(资源释放)同步地使已完成的目录失效,发现操作按需读取当前提供方映射而非监听注册表变更事件。提供方目录从等待的 `list()` 调用返回排序后的候选项,远程提供方在此过程中执行初始化、认证和发现,同时遵守查找的 abort 信号。注册表校验每个候选项,按排名、提供方注册顺序和提供方内部顺序以先到先得方式解决同名 skill 冲突,然后按 skill 名称排序摘要以保证消费方获得确定性结果。它仅缓存已完成的目录快照,并在发现过程中提供方/运行时修订版本发生变化时重试,因此卸载操作不会将一个陈旧且不可解析的 skill 冻结到会话前缀中。运行时 `ctx.skills.register(...)` 仍作为嵌入式进程内 skill 的便捷方式保留,使用 project 优先于 user 的优先级;`runtime` 保留为注册表拥有的提供方名称。 + +本地提供方按先到先得的排名顺序扫描 cwd 敏感的项目根目录、自定义根目录和用户根目录:项目 `.dsh`、项目 `.agents`、`customSkillDirs`、用户 `.dsh`,然后是用户 `.agents`。用户 `.dsh/skills` 扫描跳过 `.system`,以免系统拥有的目录被当作普通用户内容处理。DeepSeek Harness 不随附内置系统 skill;嵌入式或远程提供方在配置后提供额外 skill。 + +每个 skill 是 `<name>/SKILL.md` 或带 YAML frontmatter 的 `<name>.md`。`name` 和 `description` 为必填;`whenToUse`、`disableModelInvocation` 和 `metadata` 为可选。名称采用 kebab-case。YAML frontmatter 使用 `yaml` 包(package)解析,而非 `js-yaml` 或手写解析器:`yaml` 是本包有限 frontmatter 需求已声明的现代解析器,窄解析器要么拒绝用户预期可用的合法 YAML,要么膨胀为一个未经评审的 YAML 子集。 + +本地 skill 的文件系统 I/O 在加载了文件系统服务时通过 `ctx.fs` 进行:项目根目录查找使用 `resolve` 和 `stat` 探测 `.git`,根目录发现使用 `listDir`,skill 读取使用 `readText`。Node 文件系统作为后备,供在不挂载 fs seam 的最小上下文中加载 `dsh-skill-local` 时使用。缺失的根目录、不可读或格式错误的 skill 文件、以及提供方 `list()` 的瞬态失败均降级为警告并跳过,使一个坏源不会导致所有 agent 请求失败;格式错误的候选项仍然快速失败,因为它们违反了提供方契约。 + +`dsh-tool-skill` 通过 [`agent/session-prefix`](2026-07-07-session-prefix.md) 贡献一个 user-role `<system-reminder>` 目录。该目录仅包含排序后的 skill 名称与描述;不包含正文、路径、来源、提供方和路由提示。描述经过空白规范化、XML 转义,并受 `catalogDescriptionMaxLength` 上限约束,其默认值为 `500`,最小值为 `3`。session-prefix seam 将仅用于请求的目录按 loop 实例冻结,并记录在请求头中,在不将其加入持久化历史的前提下保持可重建性。完整的 skill 正文从不包含在目录中。 + +`skill({ name })` 工具为当前 agent cwd 加载一个完整 skill,返回包含 `<skill_content name="...">`、`<skill_resources>` 和 `<skill_instructions>` 的工具结果。`resourceBase` 提供一个目录、URL 或不透明的提供方管理的基路径,用于显式引用的脚本、参考资料和资产;资源仅按需加载,不进行目录枚举。无法解析的名称报告该 skill 未知或不再可用;无效名称和标记了 `disableModelInvocation` 的 skill 保留不同的工具错误。工具结果是面向模型的可见披露路径。 + +数据结构与目录/工具契约记录在 [skills.md](../../../../docs/core-data-structures/skills.md) 中,服务签名见生成的[服务目录](../../../../docs/cordis-catalog/services.md)。 + +## 曾考虑的替代方案 + +**将完整 skill 正文注入每条系统提示词。** 否决,因为这破坏了渐进式披露,使每个请求都为可能不适用的指令付出代价。 + +**仅以斜杠命令暴露 skill。** 否决,因为模型主动加载是核心能力;面向人类的命令广播不改变发现机制。 + +**将本地文件系统扫描直接放入 `ctx.skills`。** 否决,因为编码 agent、Web agent 和未来的插件生态需要不同的 skill 来源。提供方注册表与 subagent seam 镜像:注册表拥有冲突解决和消费方,实现拥有加载。 + +**使用系统提示词段落。** 否决,因为渲染后的系统提示词是单一字符串,而目录是一条具有仅请求生命周期要求的 user-role `<system-reminder>` 消息。[`agent/session-prefix`](2026-07-07-session-prefix.md) 是选定的机制:它将目录置于派生历史之前,并将组合后的消息记录在请求头中。 + +**在 `~/.dsh/skills/.system` 下物化内置 DSH 编写 skill。** 否决,因为打包的 skill 不应在启动时写入用户主目录,嵌入式或远程提供方在配置后提供 skill。 + +**递归发现嵌套的 `**/SKILL.md`。** 否决。扁平文件和一级目录包覆盖了配置的根目录,同时使重复处理和目录顺序易于推理。 + +**手写 frontmatter 解析器。** 否决,因为已接受的 schema 包含一个开放的 `metadata` 对象。窄解析器要么拒绝用户预期可用的合法 YAML,要么膨胀为一个未经评审的 YAML 子集。 + +## 后果 + +agent-core 主干包含一个 session-prefix 贡献者、一个本地提供方和一个面向模型的工具。Skill 发现是 cwd 敏感的,因此以不同会话 cwd 值创建 agent 的调用方可以按设计观察到不同的项目 skill 覆盖。 + +目录对于固定的根目录集合和运行时注册修订版本是确定性的,但不监视磁盘变化;发现结果被缓存,直到运行时注册使缓存失效或进程重启。 + +## 延后 + +Fork 的 skill 上下文(`context: fork`)、参数声明与提示(`arguments` 和 `argument-hint`)、以及逐 skill 的工具约束(`allowed-tools` 和 `disallowed-tools`)不在已交付的契约范围内。注册表、本地提供方和面向模型的工具不解析、不广播、也不执行这些字段,`user-invocable` frontmatter 字段同样不会被解析。直接用户调用本身则作为消费方层面的能力交付:TUI 前门基于注册表现有的 `list()` 与 `get()` 方法提供手动 `/skill:<name>` 命令,无需变更注册表、提供方或工具契约——见 [TUI skill 斜杠命令](2026-07-21-tui-skill-slash-command.md)。 diff --git a/.agents/notes/implemented/feature/2026-07-06-approval-seam.i18n.yaml b/.agents/notes/implemented/feature/2026-07-06-approval-seam.i18n.yaml new file mode 100644 index 0000000000..6ac2ad45f6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-06-approval-seam.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-approval-seam.md: 852108f22be22eeba4578032924adb546ee10985 +2026-07-06-approval-seam.zh.md: 9a08f333e0859e6d71f40b039f4b441028c38dc3 diff --git a/.agents/notes/implemented/feature/2026-07-06-approval-seam.md b/.agents/notes/implemented/feature/2026-07-06-approval-seam.md index af063895e2..852108f22b 100644 --- a/.agents/notes/implemented/feature/2026-07-06-approval-seam.md +++ b/.agents/notes/implemented/feature/2026-07-06-approval-seam.md @@ -2,15 +2,17 @@ Status: implemented +English | [中文](2026-07-06-approval-seam.zh.md) + ## Problem -Two callers need to put one question — "may this specific action proceed?" — to a human: `tools/pre-execute`'s `ask` decision (including the Claude-Code hook bridge's `permissionDecision: ask`) and the [sandbox Agent Note](2026-07-06-sandbox.md)'s post-denial one-shot escalation retry. A shared seam keeps them from inventing separate outcome vocabularies, UI routing, cancellation, and audit trails, while guaranteeing that a deployment with no UI can never grant an unanswerable request. +Two callers need one closed decision — "may this specific action proceed?": `tools/pre-execute`'s `ask` decision (including the Claude-Code hook bridge's `permissionDecision: ask`) and the [sandbox Agent Note](2026-07-06-sandbox.md)'s post-denial one-shot escalation retry. A shared seam keeps them from inventing separate outcome vocabularies, channel routing, cancellation, and audit trails, while guaranteeing that a deployment with no answerer can never grant an unanswerable request. The answerer may be an interactive host or an automated controller. -The routing problem is ownership: an approval prompt must reach the editor session that owns the asking agent (the ACP bridge multiplexes N sessions over one connection), fail closed for agents nobody owns (in-process subagents, tests), and stay out of deployments that compose no UI (headless, CI). +The routing problem is ownership: a permission request must reach the channel that owns the asking agent, fail closed for agents nobody owns, and stay out of deployments that compose no answerer. ## Decision -One package, `dsh-user-approval` (`packages/ui/user-approval`), owning the vocabulary and the `ctx.approval` service — the MECHANISM. The POLICY — who answers, and whether a session is asked at all — lives outside it: answerers are `approval/request` waterfall listeners registered by the plugins that own the channel (the ACP bridge; future terminal UIs; test scripts), and a per-session policy tier can decide before any human is involved. Consumers (`dsh-tools`' ask routing, the sandbox escalation gate) resolve a question to a closed outcome and derive their own tool results from it. Deliberately ONE package, not the capability-seam three (see Alternatives). +One package, `dsh-user-approval` (`packages/ui/user-approval`), owns the vocabulary and the `ctx.approval` service — the mechanism. The policy — who answers, and whether a session is asked at all — lives outside it: answerers are `approval/request` waterfall listeners registered by channel-owning plugins (the ACP bridge, host adapters, and test scripts), and a per-session policy tier can decide before a channel is involved. Consumers (`dsh-tools`' ask routing and the sandbox escalation gate) resolve a question to a closed outcome and derive their own tool results from it. This is deliberately one package, not the capability-seam three (see Alternatives). ### How a deployment uses it @@ -23,11 +25,11 @@ One `cordis.yml` entry mounts the seam. Not loading it is the fail-closed opt-ou # policy: never # deployment default for sessions without an override; 'ask' when omitted ``` -The entry alone provides mechanism, not a channel: with no answerer composed, every ask resolves `unavailable` and the asking tool call denies — fail-closed needs no configuration. Composing the ACP app (`@deepseek-ai/dsh-acp-demo`, as in [the acp-agent example's default tree](../../../../examples/acp-agent/README.md)) completes the loop: its bridge registers an answerer that prompts the owning editor session via `session/request_permission`, so a hook's `ask` or an escalation request surfaces as a one-shot Allow/Reject prompt attached to the already-streamed tool call. `policy: never` is the unattended stance — every ask auto-rejects deterministically, stated in the system prompt, no human in the loop. `policy` is validated against the closed list at plugin load; anything else throws. +The entry alone provides mechanism, not a channel: with no answerer composed, every ask resolves `unavailable` and the asking tool call denies — fail-closed needs no configuration. Composing the ACP app (`@deepseek-ai/dsh-acp-demo`, as in [the acp-agent example's default tree](../../../../examples/acp-agent/README.md)) completes the loop: its [automation-only bridge](../simplification/2026-07-23-acp-automation-only-protocol.md) registers an answerer that sends `session/request_permission` to the owning client with the exact tool-call id and one-shot allow/reject options. `policy: never` is the unattended stance — every ask auto-rejects deterministically and is stated in the system prompt. `policy` is validated against the closed list at plugin load; anything else throws. What a composed deployment observes: `allowed-once` lets exactly that call proceed; rejection, dismissal, and channel absence deny with three distinct reasons the model can tell apart; a successful in-turn request lands a durable `approval/asked`/`approval/decided` pair on the asking agent's session log; nothing about a grant persists past the call that asked. An idle request or audit append failure rejects instead of returning an unaudited decision. -One ask under this composition, verbatim from the sandbox example's recorded `escalation-approved` scenario — the model requests a sandbox escalation, the gate asks, the bridge prompts the owning editor, the user clicks Allow once: +One ask under this composition, from the sandbox example's recorded `escalation-approved` scenario — the model requests a sandbox escalation, the gate asks, and the automation client selects Allow once: ``` tool/call bash {"command": "printf 'escalated\n' > escalated.txt && cat escalated.txt", @@ -38,12 +40,12 @@ approval/asked {"toolName": "bash", "callId": "call_00_…", → session/request_permission {"toolCall": {"toolCallId": "call_00_…"}, "options": [{"optionId": "allow-once", "name": "Allow once", "kind": "allow_once"}, {"optionId": "reject-once", "name": "Reject", "kind": "reject_once"}]} - ← the user picks "Allow once" on the prompt the editor attaches to the streamed bash call + ← the client selects "Allow once" approval/decided {"outcome": "allowed-once"} tool/result "escalated" — this one call ran under the wider mode; the grant died with it ``` -The `escalation-rejected` twin ends in `{"outcome": "rejected"}` instead: nothing executes, and the model's result carries the asker's verbatim fail-closed text (`the user rejected escalating this command to "workspace-write"`). A hook's `permissionDecision: ask` rides the identical wire; only the asker and its deny texts differ (§ Ask routing in dsh-tools). Headless, the same request skips the prompt entirely and settles `unavailable`. +The `escalation-rejected` twin ends in `{"outcome": "rejected"}` instead: nothing executes, and the model's result carries the asker's verbatim fail-closed text (`the user rejected escalating this command to "workspace-write"`). A hook's `permissionDecision: ask` rides the identical wire; only the asker and its deny texts differ (§ Ask routing in dsh-tools). Without an answerer, the same request settles `unavailable`. ### Design detail @@ -53,11 +55,11 @@ After validation and a successful `approval/asked` append, the service resolves Answerers are `approval/request` waterfall listeners. Zero listeners fall through to `unavailable`; a recognizing listener occupies the first-wins decision slot, while an unrecognized agent must delegate with `next()`. Listeners dispose with their fibers, so an unloaded channel fails closed. Because sibling registration order is not deterministic, a deployment composes one terminal answerer and reserves `prepend` for decide-or-delegate gates. -`ApprovalRequest` carries the asking `agent`, `toolName`, optional exact `callId`, human-readable `reason`, and optional `signal`. It uses the `CallId` brand without importing `dsh-tools`, which depends on this seam. Tool arguments stay on the already-streamed call that a UI references by `callId`. +`ApprovalRequest` carries the asking `agent`, `toolName`, optional exact `callId`, human-readable `reason`, and optional `signal`. It uses the `CallId` brand without importing `dsh-tools`, which depends on this seam. Channel adapters correlate any richer call state by `callId`; the approval request does not duplicate tool arguments. #### Ask routing in dsh-tools -`ToolRegistry.execute()` resolves `ask` before dispatch: `allowed-once` proceeds, while rejection, cancellation, and channel absence produce distinct deny reasons. Opportunistic `ctx.get('approval')` consumption lets an absent or unmounted service fail closed without gating the registry fiber. Agent-less execution also fails closed because it has neither an audit session nor a UI owner. +`ToolRegistry.execute()` resolves `ask` before dispatch: `allowed-once` proceeds, while rejection, cancellation, and channel absence produce distinct deny reasons. Opportunistic `ctx.get('approval')` consumption lets an absent or unmounted service fail closed without gating the registry fiber. Agent-less execution also fails closed because it has neither an audit session nor a channel owner. #### The per-session policy tier @@ -65,9 +67,9 @@ The seam also owns the session-scoped `'ask' | 'never'` policy described by [the #### The ACP answerer -The ACP bridge answers only for an exact agent object owned by its forward session map. It attaches `session/request_permission` to the existing `callId`, advertises one-shot allow/reject options, maps cancellation separately, and never grants an unknown option. Foreign or call-less requests delegate; a failed client RPC becomes `unavailable`. Hooks and `tools/pre-execute` decide whether a call asks at all. +The ACP bridge answers only for an exact agent object owned by its session map. It sends `session/request_permission` with the existing `callId`, advertises one-shot allow/reject options, maps cancellation separately, and never grants an unknown option. Foreign or call-less requests delegate; a failed client RPC becomes `unavailable`. Hooks and `tools/pre-execute` decide whether a call asks at all. This channel is machine policy between an automated client and its agent, not ACP presentation. -The answerer routes through the bridge's exact-agent ownership check described by [the ACP support Agent Note](2026-06-14-acp-agent-client-protocol.md), implementing the per-session permission ownership required by [the multi-session Agent Note](2026-06-14-acp-multi-session.md). +The answerer routes through the bridge's exact-agent ownership check described by [the ACP support Agent Note](2026-06-14-acp-agent-client-protocol.md), preserving the per-session permission ownership required by [the multi-session Agent Note](2026-06-14-acp-multi-session.md). #### Audit, and what the model sees @@ -86,13 +88,13 @@ Snapshots record allowed and rejected sandbox escalation through `session/reques ## Deferred - **`allow_always` grant storage** — honoring a persistent grant means designing storage, scope identity (call? path? prefix? session? time window?), and revocation; until designed, only the one-shot options are advertised ([the sandbox Agent Note](2026-07-06-sandbox.md) § Escalation records the open scope question). -- **A recorded hook-driven `ask` through a composed answerer** — the human-prompt wire is recorded through the sandbox example's escalation branches. The hook matrix's `hook-cc-pretool-ask` pins the no-ApprovalService fallback denial, while the hook-producer-plus-answerer composition remains on the unit tier. -- **Routing a child agent's approvals to the parent session** — `subagent-acp`'s child auto-answers its own `permission` requests; surfacing them to the parent's editor is its own design. +- **A recorded hook-driven `ask` through a composed answerer** — the permission wire is recorded through the sandbox example's escalation branches. The hook matrix's `hook-cc-pretool-ask` pins the no-ApprovalService fallback denial, while the hook-producer-plus-answerer composition remains on the unit tier. +- **Routing a child agent's approvals to the parent session** — `subagent-acp`'s child auto-answers its own permission requests; delegating them to the parent controller is its own design. ## Alternatives considered - **A single registered provider instead of waterfall listeners** — rejected: a `registerProvider()` surface forces every composition question — allowlist pre-filters, external hook deciders, scripted test answers, a policy gate in front of a human — inside one provider implementation. The waterfall gets composition, fail-closed absence, and HMR disposal from machinery the runtime already has; the seam's JSDoc pins the single-decision-slot convention instead of inventing a provider registry. -- **An inline `tools/pre-execute` permission gate in the ACP bridge** — rejected: prompting for every bridge-owned call hardwires the asking POLICY into the UI plugin, cannot serve a second asker (sandbox escalation happens after execution starts, with no pre-execute moment), and leaves hook-produced `ask` decisions without a shared mechanism. +- **An inline `tools/pre-execute` permission gate in the ACP bridge** — rejected: prompting for every bridge-owned call hardwires the asking policy into the transport, cannot serve a second asker (sandbox escalation happens after execution starts, with no pre-execute moment), and leaves hook-produced `ask` decisions without a shared mechanism. - **The generic user-interaction seam (`ctx.userInteraction`)** — rejected as the approval mechanism: the two share a skeleton (route by agent, block for a human, handle absence), but approval's contract is narrower in every dimension that matters: a closed outcome vocabulary instead of free text, a protocol-native prompt attached to a tool call instead of a generic form, mandatory fail-closed absence, and audit events. Approval therefore does not ride the shipped `packages/ui/user-interaction` / `ask_user_question` elicitation path — an elicitation form is not a permission prompt, and a free-text answer is not a closed outcome; sharing provider plumbing stays open if the two ever converge. - **Static optional injection in `dsh-tools`** — rejected: the vendored cordis `Inject` type has no optional flag — the object form maps service names to intercept config, and a declared inject gates the fiber. `ctx.get('approval')` is the documented opportunistic-consumption pattern (the `tool-bash` owner-token lookup, the loop's persistence probe), reads presence per call, and degrades correctly across HMR without extra machinery. - **The capability-seam three-package split** — rejected: interface/implementation/consumer fits a seam whose implementation is swappable (bash-local vs bash-sandbox). Here the service body is fixed mechanism and the variable part is listeners that live with their owners — splitting would manufacture an implementation package with nothing in it ("don't split preemptively"). @@ -105,13 +107,13 @@ The implemented contract is pinned by the suites in Testing: - `allowed-once` dispatches one action; every other outcome denies with a distinct reason, and `'never'` rejects before prompting. - Missing, foreign, agent-less, throwing, invalid, and disconnected answer paths fail closed. - Successful requests route by exact agent ownership and append one replayable, model-invisible audit pair; idle and pre-commit failures reject. -- ACP ownership keeps prompts inside their session, while a deployment without the service emits no prompt or audit events. +- ACP ownership keeps decisions inside their session, while a deployment without the service emits no request or audit events. Costs and accepted limits: - **Two decide-eager answerers race for the slot.** Sibling-plugin listener order is not deterministic, so the seam cannot referee competing terminal answerers — mitigated by convention (one terminal answerer per deployment; `prepend` only for decide-or-delegate gates) rather than a priority mechanism the event bus does not have. - **Production exercise rests on one composition.** `ask` has two producer families — the hook bridges through `tools/pre-execute`, and sandbox escalation through its own gate — with the wire recorded in the sandbox example's snapshot suite, so the seam's real-world coverage is that one composition until more deployments compose it. -- **Ownership keys on `Agent` object identity.** The answerer resolves the forward session-map record at `agent.session.id`, then requires that record to own the exact agent object; every current path hands the same object through the loop and the seams, but a future boundary that clones or proxies agents would make the bridge delegate and fail closed — safe, but silently UI-less — and would need a different ownership contract. +- **Ownership keys on `Agent` object identity.** The answerer resolves the session-map record at `agent.session.id`, then requires that record to own the exact agent object; every current path hands the same object through the loop and the seams, but a future boundary that clones or proxies agents would make the bridge delegate and fail closed, and would need a different ownership contract. ## FAQ @@ -121,10 +123,10 @@ Costs and accepted limits: - **Who decides whether a call asks in the first place?** Policy producers: a hook returning `permissionDecision: ask`, any `tools/pre-execute` listener, or the sandbox escalation gate. The seam and the bridge only route and answer; neither injects its own judgment about what deserves a prompt. - **What happens when the user dismisses the prompt, or the turn aborts mid-ask?** Dismissal maps to `cancelled` with its own deny text. An already-aborted signal settles `cancelled` without dispatching; an abort during the ask discards the late answer. When both audit appends commit, either path records one pair, never two. - **What if the client answers with an option the harness never offered?** Any selection other than the offered `allow_once` maps to `rejected` — an unknown optionId from a non-conforming client can never grant. -- **How do subagents' approvals route?** An agent no answerer owns delegates through the whole waterfall and fails closed — in-process subagents are deliberately unanswerable. `subagent-acp`'s child-side auto-answer is separate; routing a child's asks to the parent's editor is deferred (§ Deferred). +- **How do subagents' approvals route?** An agent no answerer owns delegates through the whole waterfall and fails closed — in-process subagents are deliberately unanswerable. `subagent-acp`'s child-side auto-answer is separate; routing a child's asks to the parent controller is deferred (§ Deferred). - **What does `policy: 'never'` actually change at runtime?** The service resolves every ask for that session to `rejected` before dispatching any answerer (in-service, so no registration order can bypass it); the system prompt states the policy; switches are narrated at boundaries; each successful auto-rejection records the audit pair. -- **What happens across a hot reload, or when the UI plugin unloads mid-session?** Answerers dispose with their owning fiber, so the next ask degrades to `unavailable` instead of hanging on a dead channel; remounting re-registers the answerer with no catch-up state. -- **Where does the user see what they are approving?** On the tool call itself: the prompt attaches to the already-streamed call via `callId` — arguments included — and adds the asker's human-readable `reason`; the request carries no argument copy of its own. +- **What happens across a hot reload, or when an answerer unloads mid-session?** Answerers dispose with their owning fiber, so the next ask degrades to `unavailable` instead of hanging on a dead channel; remounting re-registers the answerer with no catch-up state. +- **Where does a client get approval context?** The request carries the exact `callId` and the asker's human-readable `reason`; channel adapters may correlate richer tool-call state without duplicating arguments in the approval seam. ## Prior art @@ -133,5 +135,5 @@ In-repo precedents this design copies or contrasts with: - The `fs/write-intent` gate (`packages/fs/fs/`) — the documented single-occupancy decision-slot waterfall semantics (first answer wins, delegate via `next()`) the answerer contract reuses. - `hook/invoked`/`hook/result` — the log-only audit-pair precedent `approval/asked`/`approval/decided` follows; [the hook-bridges Agent Note](2026-06-30-hook-bridges.md) ships `permissionDecision: ask`, the first producer. - [The interception-seams Agent Note](2026-06-30-interception-seams.md) — the `tools/pre-execute` `allow`/`deny`/`ask` vocabulary whose `ask` this seam services. -- [The ACP support Agent Note](2026-06-14-acp-agent-client-protocol.md) — the exact-agent ownership check against the forward session map that the answerer routes through; [the multi-session Agent Note](2026-06-14-acp-multi-session.md) — the per-session permission-ownership blocker this implements. +- [The ACP support Agent Note](2026-06-14-acp-agent-client-protocol.md) — the exact-agent ownership check against the session map that the answerer routes through; [the multi-session Agent Note](2026-06-14-acp-multi-session.md) — the per-session permission-ownership blocker this implements. - The opportunistic `ctx.get()` consumption pattern (`tool-bash`'s owner-token lookup, the loop's persistence probe) — how `dsh-tools` consumes the seam without gating its fiber on it. diff --git a/.agents/notes/implemented/feature/2026-07-06-approval-seam.zh.md b/.agents/notes/implemented/feature/2026-07-06-approval-seam.zh.md new file mode 100644 index 0000000000..9a08f333e0 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-06-approval-seam.zh.md @@ -0,0 +1,139 @@ +# Agent Note: 审批 seam——基于 waterfall(瀑布式事件)应答者的一次性权限决策 + +Status: implemented + +[English](2026-07-06-approval-seam.md) | 中文 + +## 问题 + +两个调用方需要同一个封闭决策——「这个具体操作可以继续吗?」:`tools/pre-execute` 的 `ask` 决策(包括 Claude-Code 钩子桥的 `permissionDecision: ask`)以及[沙箱 Agent Note](2026-07-06-sandbox.md) 中拒绝后的一次性升级重试。一个共享的 seam 使它们无需各自发明独立的结果词汇、通道路由、取消机制和审计轨迹,同时保证没有应答者的部署永远不会批准一个无法应答的请求。应答者可以是交互式宿主,也可以是自动化控制器。 + +路由问题的核心是归属:权限请求必须到达拥有发起请求的 agent(智能体)的通道,对无人拥有的 agent 失败关闭,并且不侵入没有组合应答者的部署。 + +## 决策 + +一个包 `dsh-user-approval`(`packages/ui/user-approval`),拥有词汇表和 `ctx.approval` 服务——即机制。策略——谁来应答、某个会话是否需要被询问——不在其中:应答者是 `approval/request` waterfall 监听器,由拥有通道的插件注册(ACP(Agent Client Protocol)桥、宿主适配器、测试脚本),而每会话的策略层可以在任何通道介入之前做出决定。消费方(`dsh-tools` 的 ask 路由和沙箱升级门禁)将问题解析为一个封闭结果,并从中派生各自的工具结果。刻意设计为一个包,而非能力 seam 的三包拆分(见「替代方案」)。 + +### 部署如何使用它 + +一条 `cordis.yml` 条目挂载该 seam。不加载它就是失败关闭的退出方式:消费方在没有注册任何审批代码的情况下拒绝无法应答的请求。 + +```yaml +- id: approval + name: '@deepseek-ai/dsh-user-approval' + # config: + # policy: never # deployment default for sessions without an override; 'ask' when omitted +``` + +仅有这条条目只提供机制,不提供通道:没有组合应答者时,每次 ask 都解析为 `unavailable`,发起请求的工具调用被拒绝——失败关闭无需配置。组合 ACP 应用(`@deepseek-ai/dsh-acp-demo`,如 [acp-agent 示例的默认树](../../../../examples/acp-agent/README.md))即可闭环:其[仅面向自动化的桥接层](../simplification/2026-07-23-acp-automation-only-protocol.md)注册一个应答者,向拥有该会话的客户端发送 `session/request_permission`,携带精确的工具调用 id 和一次性 allow/reject 选项。`policy: never` 是无人值守姿态:每次 ask 确定性地自动拒绝,并在系统提示词中声明。`policy` 在插件加载时对照封闭列表校验;非法值直接抛异常。 + +组合部署的可观测行为:`allowed-once` 仅允许该次调用继续;拒绝、关闭和通道缺失以三种不同原因拒绝,模型可以区分;轮次内成功的请求会在发起请求的 agent 的会话日志上落一对持久的 `approval/asked`/`approval/decided` 事件;授权不会在发起请求的调用结束后继续存在。空闲时的请求或审计追加失败会拒绝,而不会返回未经审计的决策。 + +以下是该组合下的一次 ask,取自沙箱示例录制的 `escalation-approved` 场景——模型请求沙箱升级,门禁发起 ask,自动化客户端选择 Allow once: + +``` +tool/call bash {"command": "printf 'escalated\n' > escalated.txt && cat escalated.txt", + "sandbox_permissions": "workspace-write", + "justification": "the user asked to write escalated.txt in the workspace"} +approval/asked {"toolName": "bash", "callId": "call_00_…", + "reason": "escalate sandbox to workspace-write: the user asked to write escalated.txt in the workspace"} + → session/request_permission {"toolCall": {"toolCallId": "call_00_…"}, + "options": [{"optionId": "allow-once", "name": "Allow once", "kind": "allow_once"}, + {"optionId": "reject-once", "name": "Reject", "kind": "reject_once"}]} + ← the client selects "Allow once" +approval/decided {"outcome": "allowed-once"} +tool/result "escalated" — this one call ran under the wider mode; the grant died with it +``` + +`escalation-rejected` 孪生场景以 `{"outcome": "rejected"}` 结束:不执行任何操作,模型的结果携带发起方的逐字失败关闭文本(`the user rejected escalating this command to "workspace-write"`)。钩子的 `permissionDecision: ask` 走完全相同的协议;只有发起方和拒绝文本不同(§ dsh-tools 中的 Ask 路由)。没有应答者时,同一请求直接结算为 `unavailable`。 + +### 设计细节 + +#### seam:机制与策略分离 + +经过校验并成功追加 `approval/asked` 后,服务将 `approval/request` waterfall 解析为 `allowed-once`、`rejected`、`cancelled` 或 `unavailable`。服务借用只读的请求标识和 signal,将中止视为 `cancelled`,把应答者失败和无效返回容纳为 `unavailable`,丢弃迟到的应答,并追加配对的 `approval/decided` 事件。提交前的审计失败会拒绝;追加后的观察者失败无法撤销权威事件。`allowed-once` 仅授权所询问的操作,而 `request()` 会拒绝打开轮次之外的调用,以保证审计对留在持久提交边界内。 + +应答者是 `approval/request` waterfall 监听器。零监听器会一路委派至 `unavailable`;识别该 agent 的监听器占用先到先得的决策槽,而不识别的监听器必须调用 `next()` 委派。监听器随其 fiber dispose,因此卸载通道会失败关闭。由于兄弟插件的注册顺序不确定,部署应组合一个终端应答者,并保留 `prepend` 给「决策或委派」门禁。 + +`ApprovalRequest` 携带发起请求的 `agent`、`toolName`、可选的精确 `callId`、人类可读的 `reason` 和可选的 `signal`。它使用 `CallId` brand 而不导入依赖本 seam 的 `dsh-tools`。通道适配器可按 `callId` 关联任何更丰富的调用状态;审批请求本身不重复携带工具参数。 + +#### dsh-tools 中的 Ask 路由 + +`ToolRegistry.execute()` 在派发前解析 `ask`:`allowed-once` 继续执行,而拒绝、取消和通道不可用产生三种不同的拒绝原因。机会性消费 `ctx.get('approval')`,让缺失或未挂载的服务失败关闭而不阻塞注册表 fiber。无 agent 的执行同样失败关闭,因为它既没有审计会话,也没有通道所有者。 + +#### 每会话策略层 + +seam 还拥有[沙箱 Agent Note](2026-07-06-sandbox.md) 所描述的会话级 `'ask' | 'never'` 策略。生效策略由日志中记录的切换在部署默认值之上折叠而成。`'never'` 会在任何应答者运行之前,于 `request()` 内部解析为 `rejected`;`'ask'` 则派发请求,否则一路委派至 `unavailable`。提示词仅声明确定性的 `'never'`,切换叙述会被合并,每个请求仍记录审计对。 + +#### ACP 应答者 + +ACP 桥只应答其会话映射所拥有的精确 agent 对象。它携带既有 `callId` 发送 `session/request_permission`,声明一次性的 allow/reject 选项,单独映射取消,并且绝不批准未知选项。外部或无调用标识的请求会委派;客户端 RPC 失败变为 `unavailable`。钩子和 `tools/pre-execute` 决定一次调用是否需要询问。该通道是自动化客户端与其 agent 之间的机器策略,不是 ACP 展示层。 + +应答者通过 [ACP 支持 Agent Note](2026-06-14-acp-agent-client-protocol.md) 描述的桥精确 agent 归属检查进行路由,保留了[多会话 Agent Note](2026-06-14-acp-multi-session.md) 要求的每会话权限归属。 + +#### 审计,以及模型看到什么 + +`approval/asked` 和 `approval/decided` 是持久的仅日志事件;模型只看到从结果派生出的普通工具结果。成功完成时,每个 `asked` 都提交一个 `decided`,包括取消和被容纳的应答者失败。空闲时的请求不追加任何事件;提交前失败会拒绝,而第二次追加失败可能留下一个已经提交但未匹配的 `asked`。 + +#### 实体与依赖 + +`dsh-user-approval` 依赖 Cordis,以及会话、agent 和带 brand 的调用契约;`dsh-tools` 与 `dsh-acp` 消费它。沙箱执行器保持独立,因为升级请求归 `dsh-tool-bash` 所有。固定的派发与审计服务仍是一个包;可替换的应答者留在各自的通道所有者中。静态能力授权和 `subagent-acp` 子侧权限应答仍是独立关注点。 + +### 测试 + +单元测试固定结果、先到先得的委派、错误容纳、取消、作用域路由、审计配对、不可绕过的 `'never'` 策略、工具拒绝原因,以及通过真实脚本化桥实现的 ACP 归属/结果映射。 + +快照记录通过 `session/request_permission` 批准和拒绝沙箱升级,以及 `'never'` 提示词与策略切换通知。没有脚本化应答的权限提示会取消并失败关闭。 + +## 延后 + +- **`allow_always` 授权存储**:兑现持久授权意味着设计存储、作用域标识(调用?路径?前缀?会话?时间窗口?)和撤销;在设计完成之前,只展示一次性选项([沙箱 Agent Note](2026-07-06-sandbox.md) § Escalation 记录了开放的作用域问题)。 +- **通过组合应答者录制由钩子驱动的 `ask`**:权限协议格式已通过沙箱示例的升级分支录制。钩子矩阵中的 `hook-cc-pretool-ask` 固定无 ApprovalService 时的后备拒绝,而钩子生产者与应答者的组合仍留在单元测试层。 +- **将子 agent 的审批路由到父会话**:`subagent-acp` 的子侧自动应答自己的权限请求;将其委派给父控制器是独立的设计。 + +## 曾考虑的替代方案 + +- **单一注册提供方而非 waterfall 监听器**:否决。`registerProvider()` 接口迫使所有组合问题——允许列表预过滤、外部钩子决策者、脚本化测试应答、人类前面的策略门禁——都塞进一个提供方实现。waterfall 从运行时已有的机制中获得组合能力、缺失时失败关闭和 HMR(热模块替换) dispose(资源释放);seam 的 JSDoc 以约定固定单决策槽语义,而非发明一个提供方注册表。 +- **在 ACP 桥中内联 `tools/pre-execute` 权限门禁**:否决。对桥拥有的每次调用都弹出提示,会将请求策略硬编码进传输层,无法服务第二个发起方(沙箱升级发生在执行开始之后,没有 pre-execute 时刻),且钩子产生的 `ask` 决策没有共享机制。 +- **通用用户交互 seam(`ctx.userInteraction`)**:否决作为审批机制。二者骨架相似(按 agent 路由、阻塞等待人类、处理缺失),但审批的契约在每个关键维度上都更窄:封闭的结果词汇而非自由文本、附着在工具调用上的协议原生提示而非通用表单、强制的缺失时失败关闭、以及审计事件。因此审批不走已交付的 `packages/ui/user-interaction` / `ask_user_question` 引出路径——引出表单不是权限提示,自由文本应答不是封闭结果;如果二者将来趋同,共享提供方管道仍然开放。 +- **`dsh-tools` 中的静态可选注入**:否决。vendor 的 Cordis `Inject` 类型没有 optional 标志——对象形式将服务名映射到拦截配置,声明的 inject 会阻塞 fiber。`ctx.get('approval')` 是文档化的机会性消费模式(`tool-bash` 的 owner-token 查找、loop 的持久化探测),按调用读取存在性,跨 HMR 正确降级,无需额外机制。 +- **能力 seam 的三包拆分**:否决。接口/实现/消费方适合实现可替换的 seam(bash-local vs bash-sandbox)。此处服务体是固定机制,可变部分是留在各自通道拥有者插件中的监听器——拆分只会制造一个空的实现包(「不要预防性拆分」)。 +- **现在就提供 `allow_always`**:否决。协议能表达它,但兑现它意味着设计授权存储、作用域标识和撤销(§ 延后)。展示 harness 无法兑现的选项只会制造注定失败的授权。 + +## 后果 + +实现后的契约由「测试」一节所列套件固定: + +- `allowed-once` 派发一次操作;其他所有结果都以不同原因拒绝,而 `'never'` 会在提示前拒绝。 +- 缺失、外部、无 agent、抛异常、无效或断开连接的应答路径都会失败关闭。 +- 成功的请求按精确 agent 归属路由,并追加一对可回放、对模型不可见的审计事件;空闲时和提交前失败的请求会拒绝。 +- ACP 归属把决策限制在其会话内,而没有该服务的部署不产生请求或审计事件。 + +代价与已接受的局限: + +- **两个急于决策的应答者竞争同一槽位。** 兄弟插件的监听器顺序不确定,seam 无法仲裁竞争的终端应答者。通过约定缓解(每个部署一个终端应答者;仅对「先决策或委派」门禁使用 `prepend`),而非事件总线不具备的优先级机制。 +- **生产环境验证依赖单一组合。** `ask` 有两个生产者家族——钩子桥通过 `tools/pre-execute`,沙箱升级通过自己的门禁——协议格式录制在沙箱示例的快照套件中;因此在更多部署组合它之前,seam 的真实覆盖面就是这一种组合。 +- **归属以 `Agent` 对象标识为键。** 应答者先在 `agent.session.id` 处解析会话映射记录,再要求该记录拥有精确的 agent 对象;当前所有路径在 loop 和各 seam 之间传递同一对象,但未来如果某个边界克隆或代理了 agent,桥会委派并失败关闭,届时需要另一种归属契约。 + +## FAQ + +- **在完全没有应答者的部署中(headless、CI)会发生什么?** 每次 ask 穿过空的 waterfall 降级为 `unavailable`,工具调用以「no approval channel is available」原因被拒绝。失败关闭是零监听器的默认行为,不是配置。 +- **授权能持久化吗——「始终允许」?** 不能。`allowed-once` 仅授权单次被询问的操作,服务在请求之间不存储任何内容;`allow_always` 在授权存储设计完成之前刻意不展示(§ 延后)。 +- **模型看到审批的什么?** 只看到发起方从结果派生的工具结果——审计对永远不进入 transcript(文本记录)。三种非授权原因各不相同,模型可以区分人类说「不」、提示被关闭、通道缺失。 +- **谁决定一次调用是否需要 ask?** 策略生产者:返回 `permissionDecision: ask` 的钩子、任何 `tools/pre-execute` 监听器、或沙箱升级门禁。seam 和桥只负责路由和应答;二者都不注入自己对「什么值得弹出提示」的判断。 +- **用户关闭提示或轮次在 ask 进行中中止时会发生什么?** 关闭映射为 `cancelled` 并携带自己的拒绝文本。已中止的 signal 直接结算为 `cancelled` 而不派发;ask 进行中的中止丢弃迟到的应答。当两个审计追加都提交时,任一路径都记录恰好一对事件,绝不会两对。 +- **如果客户端以 harness 从未提供的选项应答呢?** 除已提供的 `allow_once` 之外的任何选项都映射为 `rejected`——来自不合规客户端的未知 optionId 永远不能授权。 +- **subagent 的审批如何路由?** 没有应答者拥有的 agent 穿过整个 waterfall 委派并失败关闭——进程内 subagent 被刻意设计为不可应答。`subagent-acp` 的子侧自动应答是独立的;将子 agent 的 ask 路由到父控制器已延后(§ 延后)。 +- **`policy: 'never'` 在运行时实际改变了什么?** 服务在派发任何应答者之前,将该会话的每次 ask 解析为 `rejected`(在服务内部,因此没有注册顺序能绕过它);系统提示词声明该策略;切换在边界处被叙述;每次成功的自动拒绝都会记录审计对。 +- **热重载或应答者在会话中途卸载时会发生什么?** 应答者随其拥有的 fiber 一起 dispose,因此下一次 ask 降级为 `unavailable` 而非挂在死通道上;重新挂载会重新注册应答者,无需追赶状态。 +- **客户端从哪里获得审批上下文?** 请求携带精确的 `callId` 和发起方的人类可读 `reason`;通道适配器可自行关联更丰富的工具调用状态,而无需在审批 seam 中重复携带参数。 + +## 先例 + +本设计复用或对照的仓库内先例: + +- `fs/write-intent` 门禁(`packages/fs/fs/`)——文档化的单占用决策槽 waterfall 语义(先到先得,通过 `next()` 委派),应答者契约复用了它。 +- `hook/invoked`/`hook/result`——仅日志审计对先例,`approval/asked`/`approval/decided` 沿用了它;[钩子桥 Agent Note](2026-06-30-hook-bridges.md) 交付了 `permissionDecision: ask`,即第一个生产者。 +- [拦截 seam Agent Note](2026-06-30-interception-seams.md)——`tools/pre-execute` 的 `allow`/`deny`/`ask` 词汇,本 seam 服务其中的 `ask`。 +- [ACP 支持 Agent Note](2026-06-14-acp-agent-client-protocol.md)——应答者路由时对会话映射执行的精确 agent 归属检查;[多会话 Agent Note](2026-06-14-acp-multi-session.md)——本设计实现的每会话权限归属阻塞项。 +- 机会性 `ctx.get()` 消费模式(`tool-bash` 的 owner-token 查找、loop 的持久化探测)——`dsh-tools` 消费该 seam 而不阻塞其 fiber 的方式。 diff --git a/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.i18n.yaml b/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.i18n.yaml new file mode 100644 index 0000000000..1c1ae2daf2 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-explicit-tool-order.md: bd6d0a04aa470ca33e618957ae1f08c1ef15fcfe +2026-07-06-explicit-tool-order.zh.md: 5cdecc0e59ff00b6dce7134819f8230072d084cb diff --git a/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.md b/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.md index c78126e92a..bd6d0a04aa 100644 --- a/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.md +++ b/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-06-explicit-tool-order.zh.md) + ## Problem Model-facing tool order followed plugin registration order, which depends on concurrent module loading for otherwise independent plugins. That race produced different request headers in CI and snapshot recordings. Because order affects request bytes, caching, and the durable header, it needs an explicit deterministic policy. diff --git a/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.zh.md b/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.zh.md new file mode 100644 index 0000000000..5cdecc0e59 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.zh.md @@ -0,0 +1,51 @@ +# Agent Note: 显式的模型侧工具顺序 + +Status: implemented + +[English](2026-07-06-explicit-tool-order.md) | 中文 + +## 问题 + +模型侧的工具顺序此前跟随插件注册顺序,而注册顺序取决于相互独立的插件的并发模块加载。这种竞态在 CI 和快照录制中产生了不同的请求头。由于顺序影响请求字节、缓存和持久化的 header,因此需要一个显式的确定性策略。 + +## 决策 + +系统提示词的组装逻辑拥有模型侧工具顺序的权威定义,正如它已经拥有 section 顺序的权威定义一样。`dsh-system-prompt` 上的 `toolOrder?: string[]` 是可选的显式策略: + +- 列表中已注册的工具按列表位置排列。 +- 列表中的名称没有对应的已注册工具,属于配置错误。形状错误(缺少 rest 条目或名称重复)在服务构造器中快速失败;未注册的名称则在每次 `assemble()` 时拒绝——这是已注册工具集存在并可供检查的最早时刻(工具插件在服务构造之后才注册),也是唯一的通用时刻(注册随时可能变化;Cordis 没有「所有插件已加载」事件)。在已交付的 agent loop(智能体循环)下,第一个轮次在发出任何模型请求之前就会失败——确切的影响范围见下文「后果」。 +- 已注册但不在列表中的工具,插入到 `'<unlisted-tools>'` rest 条目(`TOOL_ORDER_REST`)的位置,与其他未列出的工具按名称字典序排列。 +- 任何已收集的工具不得使用 `TOOL_ORDER_REST` 作为其 `ToolSchema.name`;组装逻辑在排序之前就会拒绝这个保留名称。 +- 列表必须恰好包含一个 rest 条目,且不得有重复名称。 +- 当 `toolOrder` 未设置时,权威顺序为纯字典序(code-unit 比较,与 locale 无关),因此无需配置即可保证确定性。 + +`assemble()` 在 `system-prompt/assemble` waterfall(瀑布式事件)之前对提供方工具进行规范化排序,从源头消除注册顺序的差异。waterfall 从这个确定性列表开始;不变的顺序随后流入请求头、冻结的请求和重建检查,无需 loop 特有的排序逻辑。 + +范围刻意收窄:本 Agent Note 修复的是注册顺序竞态,而非插件行为。`system-prompt/assemble` 的监听器仍然可以添加、移除或重排工具——正如它可以在 section 排序之后编辑 section——并对自身输出的确定性负责;waterfall 契约已经要求监听器是确定性的(可重建性不变式会捕获在构建与回放之间行为不一致的监听器)。 + +配置传递沿用 `persona` 的先例,`toolOrder` 与之并列:TUI、Headless 和 ACP 应用配置接受该键,并通过 `dsh-agent-spine-demo`(其 schema 是各所有者 schema 的交集)转发给 `SystemPrompt` 子服务。有一个 schemastery 细节至关重要:schemastery 数组默认为 `[]`,但省略的 `toolOrder` 必须保持 ABSENT(= 字典序),而不是变成一个显式配置的空列表(无效——缺少 rest 条目),因此链路上每个 schema 都将默认值强制为 `undefined`。 + +## 曾考虑的替代方案 + +- **注册顺序(现状)**:并发导入竞态,依赖宿主环境(上述 CI 抖动),评审中不可见。 +- **插件依赖图的线性化**:该关系是偏序的,独立的工具插件不可比较;抖动发生时偏序已完全满足。 +- **每个插件在其工具贡献上标注 `weight`**:将顺序分散到各插件中,仍需一个无人拥有的全局编号约定(section 的 `order` 分段已经展示了这种协调成本需要手工承担)。 +- **在 `ToolRegistry.schemas()` 中排序(注册表层)**:同样确定,但注册表是一个成员存储,被组装之外的多方消费;排序是提示词组合的关注点,而组装逻辑已经拥有 section 的组合策略。 +- **在 `LlmService` 上加配置 + `orderTools()` 方法,由 loop 在记录 header 前调用**:可行,但仅为在远处应用一个策略就增加了一个公开服务方法和一处 loop 改动;每个未来的请求组合者都必须记得调用。在列表诞生处进行规范化使得无序列表不可表示,且零新增接口。 +- **在 `llm.stream()` 内部规范化**:在 header 事件已记录之后才运行(抖动仍然存在),且需要重建深度冻结的信封,静默地解除了重建不变式。 +- **穷举列表(无 rest 条目)**:每个新加载的工具插件都会导致启动失败;强制的 rest 条目使未列出的工具保持确定性,且其位置是显式的。 +- **启动时校验(由 `dsh-app-boot` 在 `loader.await()` 之后调用 `SystemPrompt.assertToolOrderSatisfied()`)**:能将错误配置变为启动时死亡而非首轮次失败,但代价是一个公开服务方法加上通用启动胶水对单个服务的结构耦合,且无法替代组装时检查(嵌入式调用者从不运行 app boot;注册在 boot 之后仍会变化)。也没有现成事件可以承载该检查:Cordis v4 没有 ready 类事件,`loader/entry-init`/`internal/status` 在加载中途触发(与工具注册存在竞态——正是本 Agent Note 要消除的熵源),而 agent 生命周期事件不会早于组装。在 `assemble()` 设置单一执行点被判定值得接受较晚的失败时刻。 + +## 后果 + +- 每个由注册表构建的组装在任何宿主上都以确定性工具顺序开始;在没有专家监听器刻意改变的情况下,每个 `request/header` 事件和模型请求都继承该顺序。CI 与本地之间的注册顺序翻转从结构上被消除,默认为字典序。 +- 初始 `PromptAssembly.tools` 是权威的,因此 waterfall 监听器从模型侧顺序开始;提供方注册顺序在该协作 seam 之前无处可观测。 +- 快照套件中唯一固定请求头的 fixture(`text-turn`)携带新的权威工具顺序;按照固定请求头设计,其他 ACP 快照仍将大块 header 清洗为 `{{system}}`/`{{tools}}`。 +- 步骤之间的纯工具重排与其他 header 变更一样记录:一份原因是 `'change'` 的完整 `request/header` 快照。稳定的权威顺序会防止注册时序在普通路径上制造这类变化。 +- `toolOrder` 键沿 app → `agent-core` → `SystemPrompt` 的转发链传递,因此部署时将其放在 app 配置中 `persona` 旁边即可;`dsh-llm` 和 agent loop 无需改动。 +- `toolOrder` 中拼错或未加载的工具名称在提示词组装时使轮次失败,而非启动时:loop 在轮次内部组装(`turn/start` 之后、`step/start` 之前),因此拒绝到达轮次的外层 catch——轮次以 `error` 原因平衡关闭并携带错误消息,`agent/error` 镜像该消息,不打开步骤,不记录 `request/header`,不向适配器发出请求,agent 回到空闲状态。每个轮次都以相同方式失败,直到配置被修正;进程本身保持运行(符合仓库规则:显式配置引用不得被静默忽略——执行点是组装,因为不存在更早的通用时刻)。 +- 工具提供方返回保留的 rest 条目名称时,其提示词组装失败形态与未知的已列名称相同。这防止哨兵值变成一个歧义的真实工具,并保持「从不丢弃工具」的排序契约。 + +## 测试 + +系统提示词测试覆盖:字典序默认顺序、列表/rest 位置、提供方顺序无关性、共享名称、无效列表、未知或保留名称、waterfall 前的权威列表,以及监听器添加的工具不被重新排序的规则。Loop 测试固定:跨注册排列的已记录与已分发顺序一致、通过 agent-core 和两个 app 的转发、深度冻结的请求,以及在配置了未知名称时的平衡轮次失败(无步骤、无 header、无适配器调用)。快照回放仅在固定的 `text-turn` header 中保留完整的权威列表;其他 fixture(测试前置数据)继续使用 `{{tools}}`。 diff --git a/.agents/notes/implemented/feature/2026-07-06-sandbox.i18n.yaml b/.agents/notes/implemented/feature/2026-07-06-sandbox.i18n.yaml new file mode 100644 index 0000000000..6437d7813d --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-06-sandbox.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-sandbox.md: 723ef170188dc11da24e049a1e2838fb240d0a17 +2026-07-06-sandbox.zh.md: a8c7743bb3d499fb58f507ea2c202b44efe2311d diff --git a/.agents/notes/implemented/feature/2026-07-06-sandbox.md b/.agents/notes/implemented/feature/2026-07-06-sandbox.md index 507142fac9..723ef17018 100644 --- a/.agents/notes/implemented/feature/2026-07-06-sandbox.md +++ b/.agents/notes/implemented/feature/2026-07-06-sandbox.md @@ -2,13 +2,15 @@ Status: implemented +English | [中文](2026-07-06-sandbox.zh.md) + ## Problem A coding agent needs this product path: bash subprocesses — and the hook commands that ride them — execute under a restricted file sandbox by default; if and only if the sandbox actually denies an operation, the model may request one user approval for that same operation and, once granted, retry it once with wider permissions. An every-tool boundary is deliberately NOT the claim: fs/web/todo execute in-process where an `execve` wrapper is meaningless (§ In-process tools), and the cross-family boundary is staged follow-up work (§ Deferred phases). Without a shared vocabulary, every tool reinvents approval fields, denial parsing, retry matching, and permission-state hints. The harness is an SDK, so confinement must be a capability developers COMPOSE: whether to sandbox, and which backend per platform, belongs in the leaf `cordis.yml` as a first-class entry — not inside one executor's private machinery. And the first-choice runner, `bwrap`, is unusable on exactly the hosts a sandbox matters most (minimal containers, disabled unprivileged userns, LSMs that deny `mount`), so a fallback runner has to ship with the SDK rather than be assumed on the host. -Confinement alone leaves two gaps. A denial with no escalation path is terminal — the model can only give up, which pressure-cooks operators into configuring `workspace-write` or `danger-full-access` globally and defeats the sandbox. And the model-visible knobs (the sandbox mode, the approval policy) change over an agent's lifetime — an ACP user flips a per-session setting, an operator edits `cordis.yml` while the process is down — while the model must never act on a stale belief about them: what IS the state on every request, what changed while the agent lives, and what changed while nobody was watching all need answers. +Confinement alone leaves two gaps. A denial with no escalation path is terminal — the model can only give up, which pressure-cooks operators into configuring `workspace-write` or `danger-full-access` globally and defeats the sandbox. The sandbox mode and approval policy can also change over an agent's lifetime through deployment config or an optional UI policy control; execution and model-visible policy must derive from the same logged state. ## Decision @@ -38,13 +40,13 @@ The swap is invisible to every consumer of `ctx.bash`: the bash tools, hook comm Misconfiguration fails loud: `mode` outside the closed vocabulary is rejected at plugin load, and a host with no usable backend throws the structured `SANDBOX_UNAVAILABLE` — at `confine()` before the command ever spawns — rather than degrading to unconfined execution. `runnerCommand` on `dsh-sandbox-local` is the operator's explicit assertion of a bwrap-compatible runner (chain and probes skipped); it doubles as the deterministic fake-runner seam for keyless tests. -Denied file effects return a `[sandbox: file access denied under <mode> mode]` marker and instructions not to work around the denial. A confining executor adds paired `sandbox_permissions` and `justification` fields for one approved retry that must be strictly wider than the session's effective mode. A grant widens only that retry; rejection executes nothing, returns `the user rejected escalating this command to "<mode>"`, and permits no re-ask. The prompt does not announce sandbox mode, avoiding preemptive refusal. When `dsh-permission` is composed, ACP exposes one `Permissions` select whose presets write both knob events; unmatched knobs appear as switch-away-only `custom`. Only a switch to the deterministic `'never'` approval policy is stated in the prompt and narrated. +Denied file effects return a `[sandbox: file access denied under <mode> mode]` marker and instructions not to work around the denial. A confining executor adds paired `sandbox_permissions` and `justification` fields for one approved retry that must be strictly wider than the session's effective mode. A grant widens only that retry; rejection executes nothing, returns `the user rejected escalating this command to "<mode>"`, and permits no re-ask. The prompt does not announce sandbox mode, avoiding preemptive refusal. When `dsh-permission` is composed with a UI adapter, one preset selects both knob values; unmatched values fold to `custom`. The [ACP automation composition](../../../../examples/acp-agent/README.md) does not mount that UI service and selects its deployment mode explicitly. ### Design detail #### Scope grounding -OS subprocess confinement applies to the bash executor, including hook commands, and later to ACP subagent children. Filesystem, web, and other tools execute in-process and require policy at their own seams; an argv wrapper cannot confine a function closing over `ctx`. The existing bash request/spec split carries per-call overrides, while `tools/pre-execute` and the approval seam own the human decision. +OS subprocess confinement applies to the bash executor, including hook commands, and later to ACP subagent children. Filesystem, web, and other tools execute in-process and require policy at their own seams; an argv wrapper cannot confine a function closing over `ctx`. The existing bash request/spec split carries per-call overrides, while `tools/pre-execute` and the approval seam own the one-shot policy decision. #### The seam: `ctx.sandbox` @@ -90,7 +92,7 @@ Left open: what a durable grant's scope identity is beyond the sandbox mode — effective(session) = findLast(the session's own knob events)?.value ?? the composition-config default ``` -The default is composition config (`cordis.yml`) — operator-owned, process-wide. A runtime switch is a SESSION-SCOPED override recorded as one log-only event in that session's own log. Restart immunity (resuming a session replays its log, so overrides come back with zero catch-up machinery) and multi-session isolation (one editor tab's `workspace-write` cannot disturb another's `read-only`) both fall out by construction, and no external config store exists anywhere. +The default is composition config (`cordis.yml`) — operator-owned, process-wide. A runtime switch is a session-scoped override recorded as one log-only event in that session's own log. Restart immunity (resuming a session replays its log, so overrides come back with zero catch-up machinery) and multi-session isolation both fall out by construction, and no external config store exists anywhere. **One event per knob, owned by its domain** — the merge-extensible `SessionEventMap` idiom every existing event family already follows (`approval/*` in `dsh-user-approval`, `hook/*` in the hooks packages): @@ -105,9 +107,9 @@ Each owner exports the same three-piece kit: the event declaration, a pure fold Sandbox mode is not narrated in the prompt; denial results report the mode when it matters, avoiding preemptive refusal based on a standing label. Approval policy is different: only `'never'` is stated because automatic rejection otherwise looks like a user decision. Policy-change notices are coalesced and delivered by the next pre-step, with log-derived fallback after restart. The notice source is inferred from event position: a knob event after the last request header is user-driven; unlogged drift is operator or config driven. -**The editor surface** is protocol-native [Session Config Options](https://agentclientprotocol.com/protocol/session-config-options) — the spec's replacement for session modes (slated for removal in ACP v2), already SDK-typed. When `ctx.permission` is composed, the bridge advertises one `permission` select (category `mode`) in `session/new` and `session/load`; its options are the deployment's preset table, and its `currentValue` is `PermissionService.current()` over the session log plus composition defaults. The shipped `workspace-write` and `danger-full-access` presets each bundle a sandbox mode with an approval policy and write through to both domain setters; a knob combination outside the table is reported as switch-away-only `custom`. `session/set_config_option` validates and switches through the permission service, then returns the complete refreshed state (the spec contract). +**The optional UI surface** is `PermissionService`: a deployment-defined preset table whose entries bundle one sandbox mode with one approval policy. The shipped `workspace-write` and `danger-full-access` presets write through to both domain setters; a knob combination outside the table is reported as `custom`. UI adapters may expose that table as a selector. The automation-only ACP transport advertises no configuration selector and mounts no permission-preset service. -**Turn enclosure is the commit boundary.** A switch during an open turn appends immediately. An idle switch remains pending on the bridge record and is appended at the next prompt submission, before assembly or execution; last write wins per knob. Openness comes from log boundaries rather than `agent.status`, and setters do not append from inside a `session/event` listener because that would reorder later observers. Until anchoring, responses overlay the pending value. A crash discards it, and reload returns the durable fold. +**The committed event is the commit boundary.** A runtime switch records its preset and changed knob events on the target session, and every later capability resolution folds the last values. Adapters own choosing a valid session append boundary; the ACP transport has no runtime switch path. (The former ACP idle-switch anchoring — holding a pending idle selection until the next prompt submission — left with that bridge.) #### In-process tools @@ -115,10 +117,10 @@ fs/web/todo execute in-process, so their sandbox semantics are policy at their s ### Testing -- **Unit:** pin platform selection and profiles, fail-closed runner classification, per-call mode/root resolution, per-process facts, escalation validation and outcomes, permission preset folding and write-through, narrator coalescing, ACP advertisement and validation, and turn-enclosed config writes. -- **Keyless real-runner:** exercise bwrap, Landlock, and Seatbelt against real filesystem effects at provider and bash-consumer layers; one real Cordis context concurrently drives two project sessions through shipped bash and fs tools, proving own-root success and sibling-root denial. Packed-install coverage proves the registry launcher remains executable. The real ACP composition pins permission switching and rejects unknown presets. CI rejects a silent all-skip. +- **Unit:** pin platform selection and profiles, fail-closed runner classification, per-call mode/root resolution, per-process facts, escalation validation and outcomes, permission preset folding and write-through, and narrator coalescing. +- **Keyless real-runner:** exercise bwrap, Landlock, and Seatbelt against real filesystem effects at provider and bash-consumer layers; one real Cordis context concurrently drives two project sessions through shipped bash and fs tools, proving own-root success and sibling-root denial. Packed-install coverage proves the registry launcher remains executable. CI rejects a silent all-skip. - **With-key:** start the real ACP composition in read-only mode, let a model-driven bash write hit the runner's denial marker, then drive the bridge answerer and disk effect through granted and rejected workspace-write retries; unavailable credentials or runners self-skip. -- **Snapshot:** pin the permission config-option wire, preset and knob events, prompt deltas and notices, and both scripted approval branches. A real ACP example scenario places its session under the user home while the deployment fallback points at `/tmp`, then pins a successful workspace-write mutation; this distinguishes session-root resolution from the process fallback without depending on runner-specific denial text. Other snapshots start unconfined so unrelated fixtures remain platform-independent, and policy scenarios switch explicitly. +- **Snapshot:** pin prompt deltas and notices plus both scripted approval branches. A real ACP example scenario places its session under the user home while the deployment fallback points at `/tmp`, then pins a successful deployment-selected workspace-write mutation; this distinguishes session-root resolution from the process fallback without depending on runner-specific denial text. Other snapshots start unconfined so unrelated fixtures remain platform-independent. ## Deferred phases @@ -150,7 +152,7 @@ Each phase gets its full design when picked up, validated against the code at th - **Narrate via `agent/user-message` + a bus event** — rejected: it presupposes a turn-entry seam that does not exist (the real seam is `agent/prompt-submit`), and pre-step's position serves both the coalesced turn-entry notice and the mid-turn immediacy bound with one listener. - **A standing prompt statement of the sandbox mode (+ a switch narrator)** — shipped first, then removed on live evidence: with `Bash commands run under the "read-only" file sandbox.` in every request, the model refused to ATTEMPT denied-then-escalatable work (five of twelve turns in the first manual session ended with zero tool calls), turning the sandbox into a soft lockout. The denial marker names the mode at the moment it matters and the escalation fields carry the recovery; the approval knob keeps its statement because an auto-rejection is behaviorally indistinguishable from a human "no". - **Track "last told" with its own bookkeeping events** — rejected: the `request/header` fold already records the exact prompt the model saw; parsing the closed candidate sentences back replaces a second bookkeeping stream — events are needed only where they ARE the store. -- **ACP session modes instead of config options** — rejected: the preset is already one deployment-defined config-option select, and modes are slated for removal in ACP v2. +- **Independent sandbox and approval selectors** — rejected: one deployment-defined permission preset keeps the two policy knobs coherent for UI clients that expose runtime switching. ## Consequences @@ -159,11 +161,11 @@ What shipped pins — the tiers in Testing hold each: - A denied command retried with `sandbox_permissions` + `justification` prompts the user through the composed answerer chain; a grant runs THAT call under the wider mode (result facts say so) while every other call keeps its own effective mode; every non-grant outcome produces its distinct error text and executes nothing. - The escalation fields exist exactly when the mounted executor confines; a request that is not strictly wider than the call's effective mode fails closed with its own text and prompts no one; a deployment with no ApprovalService fails escalating calls closed and leaves plain calls untouched. - The system prompt never states the sandbox mode (an approval `'never'` policy is the one stated knob), and the whole exchange — headers, knob events, notices, approvals, results — reconstructs from the session log alone, with no event types beyond the two knob events. -- N idle-time flips produce at most one anchored event per knob (a net-zero sequence anchors none — a no-op push from a client echoing current selections records nothing); an approval-policy switch is narrated in at most one coalesced notice; a mid-turn sandbox switch is honored by the next call's stamp. -- A resumed session's overrides apply and are reported to the editor with no special-casing; a default changed while the process was down is narrated before the session's first new request, attributed to the operator. -- Two concurrent sessions never see each other's state, notices, or config options. +- One preset selection records only changed knob values, while a no-op selection records nothing; an approval-policy switch is narrated in at most one coalesced notice, and a committed sandbox switch is honored by the next call's stamp. +- A resumed session's overrides apply with no catch-up state; a default changed while the process was down is narrated before the session's first new request, attributed to the operator. +- Two concurrent sessions never see each other's state or notices. - Two concurrent project sessions in one Cordis context resolve independent workspace roots; bash and fs writes succeed inside the calling session's cwd and fail against its neighbor's cwd. -- `agent-loop` is untouched — everything rides `systemPrompt.section`, `SessionEventMap` merging, `agent.inject()`, `agent/pre-step`, `agent/prompt-submit`, and the ACP handler surface. +- `agent-loop` is untouched — everything rides `systemPrompt.section`, `SessionEventMap` merging, `agent.inject()`, `agent/pre-step`, `agent/prompt-submit`, and capability-owned policy resolution. Costs and accepted limits: @@ -176,7 +178,6 @@ Costs and accepted limits: - **The model may over-ask.** Escalating without denial grounding, or picking `danger-full-access` where `workspace-write` suffices: the description steers and the enum forces the ladder, but the human prompt is the actual gate; the `approval/asked` reasons make over-asking auditable, and a `prepend` policy answerer can auto-reject patterns a deployment never wants. - **The advertised target set is static while the effective mode is per-session** (schemas are registry-global) — a session already at the widest mode is still offered the fields. Harmless by construction: the strict-wider check at execution, not the enum, is the safety boundary — a non-widening request fails with its own text and never prompts anyone. - **A granted escalation is not a working sandbox.** An unavailable backend still fails closed even for a granted escalation to a confining mode — at `confine()` when the platform has no chain or every probe fails, at execution when an unprobed sole runner refuses (classified as a sandbox failure, not a command failure) — while a granted `danger-full-access` run never touches the provider at all: there the grant, not the probe, is the authority. -- **An idle switch lives in bridge memory until the next prompt submission anchors it.** A crash in that window reverts it (reported on `session/load`), and a session that never submits another prompt never persists it — accepted, with a loop-owned idle commit turn left as future work if durability becomes required. - **The approval narrator's restart baseline parses prompt prose.** The closed candidate sentence is owned by the writing module itself, so a wording change is a coordinated writer+parser edit in one file; a session whose headers predate the section silently adopts the current policy without a notice. - **The approval section is still a dynamic prompt surface** (a `'never'` switch breaks provider prompt-prefix caching for that session). Accepted: policy switches are rare, and a model acting on a stale `'never'` is worse. The sandbox knob no longer touches the prompt at all. - **The model may hold a stale belief about the sandbox mode** (nothing announces a switch). Accepted deliberately: the next attempt's marker or success corrects it, and the observed failure mode of announcing — preemptive refusal — is worse than one wasted retry. @@ -190,7 +191,7 @@ Costs and accepted limits: - **Does the sandbox restrict network or process visibility?** No — `SandboxMode` claims FILE effects only; the bwrap profile deliberately does not unshare pid, and no backend claims network. Whether network restriction becomes its own knob is left open in § The seam. - **Which tools actually run confined?** OS subprocesses through `ctx.bash` — the bash tools, and hook commands transitively — plus the filesystem tools (`read`/`write`/`edit`) through the sandboxed `ctx.fs` provider (the [cross-family fs sandbox RFC](2026-07-14-cross-family-fs-sandbox.md)): bash confines via the OS runner, fs via an in-process path fence, both keying off the same `ctx.sandboxPolicy` mode. web/todo stay in-process and unfenced (web's only effect is network, outside the file-effect mode vocabulary). - **Does a granted escalation persist?** No. The grant is consumed by the exact foreground or background call that asked; every neighboring call keeps its own effective mode. A later background denial surfaces through `task_output` and may ground a new exact-command retry. -- **When does an editor's mode switch take effect?** Mid-turn: appended immediately, honored by the very next call's stamp. Idle: held on the bridge's session record, anchored at the next `agent/prompt-submit` inside its open turn, with N flips coalescing to at most one event (none if net-zero); a crash before anchoring reverts it and `session/load` reports the truth. The model is not told — its next command simply behaves under the new mode. +- **When does a runtime mode switch take effect?** Once its session event commits, the very next capability resolution folds and stamps the new mode. The model is not told a standing mode; its next command simply behaves under the new policy, and any denial names that policy at the point of use. - **What survives a restart — and what if the operator changed the config default while the process was down?** Overrides replay from the session log (`effective = fold ?? config`), so a resumed session keeps its modes with zero catch-up machinery; a default that drifted offline changes behavior the same way a switch does (the approval policy, being stated, is additionally narrated with operator/config attribution). - **What does `enforcement: 'partial'` on a result mean?** The selected backend enforces the subset its kernel ABI governs — e.g. Landlock before ABI v3 does not govern path truncate — and says so structurally instead of refusing the host; the probe's report line distinguishes the cases. The bwrap and Seatbelt profiles govern every promised file effect by construction, so they always report `full`. diff --git a/.agents/notes/implemented/feature/2026-07-06-sandbox.zh.md b/.agents/notes/implemented/feature/2026-07-06-sandbox.zh.md new file mode 100644 index 0000000000..a8c7743bb3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-06-sandbox.zh.md @@ -0,0 +1,206 @@ +# Agent Note: 子进程沙箱——约束 seam、原生 runner、升级机制与按会话模式 + +Status: implemented + +[English](2026-07-06-sandbox.md) | 中文 + +## 问题 + +一个编码 agent 需要如下产品路径:bash 子进程(以及依附其上的钩子命令)默认在受限的文件沙箱下执行;当且仅当沙箱实际拒绝了某个操作时,模型可以为同一操作请求一次用户批准,获批后以更宽的权限重试一次。本设计刻意不声称覆盖所有工具:fs/web/todo 在进程内执行,`execve` 包装对它们毫无意义(§ 进程内工具);跨工具族的统一边界属于分阶段后续工作(§ 延迟阶段)。如果没有共享词汇,每个工具都会各自重新发明批准字段、拒绝解析、重试匹配和权限状态提示。 + +harness 是一个 SDK,因此约束必须是开发者可组合的能力:是否启用沙箱、每个平台使用哪个后端,都应作为一等条目写在叶子 `cordis.yml` 中,而非藏在某个执行器的私有机制里。而首选 runner `bwrap` 恰恰在沙箱最重要的主机上不可用(精简容器、禁用了非特权 userns、LSM 拒绝 `mount`),因此备选 runner 必须随 SDK 一起交付,而不能假设主机已有。 + +仅有约束还留下两个缺口。拒绝后没有升级路径就是死路:模型只能放弃,这会迫使运维人员全局配置 `workspace-write` 或 `danger-full-access`,从而使沙箱形同虚设。而沙箱模式和批准策略也会通过部署配置或可选的 UI 策略控件在 agent 生命周期内变化;执行与模型可见的策略必须派生自同一份已记录的状态。 + +## 决策 + +一个 seam、一条按平台的本地后端链、一个消费方,加上两个上层杠杆:按调用的升级路径与按会话的运行时模式。以下所有内容均从叶子 `cordis.yml` 组合而来;不触及 `agent-loop`。跨工具族 fs 强制与按会话工作区根目录已经作为后续设计落到同一策略载体上;剩余阶段——`subagent-acp` 消费方、更多环境与 Windows 链——仍列在 § 延迟阶段。 + +### 部署方式 + +四条 `cordis.yml` 条目即可将一个无约束的编码 agent 转变为沙箱产品路径;[`examples/acp-agent`](../../../../examples/acp-agent/README.md) 默认使用此组合: + +```yaml +- id: sandbox + name: '@deepseek-ai/dsh-sandbox-local' # the per-platform runner provider (ctx.sandbox) +- id: bash + name: '@deepseek-ai/dsh-bash-sandbox' # the confined executor, replacing dsh-bash-local behind ctx.bash + config: + mode: workspace-write # the deployment default every session starts from + workspaceRoot: !!js process.cwd() # the boundary workspace-write may write under +- id: approval + name: '@deepseek-ai/dsh-user-approval' # the escalation gate's channel (the approval Agent Note) + config: + policy: ask +- id: permission + name: '@deepseek-ai/dsh-permission' # one product-facing select over both mechanism knobs +``` + +这一替换对 `ctx.bash` 的所有消费方透明:bash 工具、钩子命令和后台任务照常运行,通过提供方返回的包装 argv spawn。删除 `sandbox` 和 `permission` 条目、将 `bash` 替换为 `@deepseek-ai/dsh-bash-local` 即为退出——执行恢复为无约束,升级字段从工具 schema 中消失,因为它们是基于已挂载执行器的能力门控,而非基于配置。仅省略 `approval` 则保留约束但以自身错误文本关闭每次升级;`permission` 还要求 approval seam 和约束执行器同时存在,因此部分组合的 preset 层在加载时即大声失败。 + +配置错误大声失败:`mode` 不在封闭词汇中时在插件加载时被拒绝;主机上没有可用后端时在 `confine()` 阶段(命令 spawn 之前)抛出结构化的 `SANDBOX_UNAVAILABLE`,而非降级为无约束执行。`dsh-sandbox-local` 上的 `runnerCommand` 是运维人员对一个 bwrap 兼容 runner 的显式断言(跳过链和探测);它同时充当 keyless 测试的确定性 fake-runner seam。 + +被拒绝的文件操作返回 `[sandbox: file access denied under <mode> mode]` 标记,并附带不要绕过拒绝的指令。约束执行器添加配对的 `sandbox_permissions` 和 `justification` 字段,用于一次经批准的重试,该重试必须严格宽于会话的有效模式。授权仅放宽该次重试;拒绝则不执行任何内容,返回 `the user rejected escalating this command to "<mode>"`,且不允许再次请求。提示词不声明沙箱模式,以避免基于常驻标签的预防性拒绝。当 `dsh-permission` 与某个 UI 适配器一起组合时,一个 preset 同时选定两个旋钮值;不匹配的组合折叠为 `custom`。[ACP 自动化组合](../../../../examples/acp-agent/README.md)不挂载该 UI 服务,而是显式选定其部署模式。 + +### 设计细节 + +#### 范围界定 + +OS 子进程约束适用于 bash 执行器(包括钩子命令),后续还将适用于 ACP subagent 子进程。文件系统、web 和其他工具在进程内执行,需要在各自的 seam 层面实施策略;argv 包装无法约束一个闭包了 `ctx` 的函数。既有的 bash request/spec 拆分承载按调用的覆盖,而 `tools/pre-execute` 和 approval seam 负责一次性策略决策。 + +#### seam:`ctx.sandbox` + +`dsh-sandbox` 拥有词汇和 `SandboxProvider` 契约:`confine(argv, policy)` 返回调用方应当 spawn 的替代 argv(经过包装,使进程及其所有子进程在约束下运行),加上所选后端达到的 `enforcement` 完整度、其拒绝方言(`denialSignatures`,该后端内核在拒绝文件操作时打印到 stderr 的子串)、以及其 runner 失败方言(`runnerFailureSignatures`,runner 本身失败——因而命令从未运行——时的自我标识方式);没有可用后端时抛出失败关闭的 `SANDBOX_UNAVAILABLE` 错误,绝不静默放行。词汇:`SandboxMode`(`read-only` / `workspace-write` / `danger-full-access`,仅限文件操作——不声称覆盖网络和进程可见性)、`SandboxEnforcement`(`full` / `partial`)、`SandboxExecutionPolicy`(每次能力调用的完整 mode + workspace root)以及 `SandboxPolicy`(提供给约束后端的子集)。 + +策略随每次调用而非提供方携带:两个消费方可以在同一时刻以不同策略约束(bash 在 `read-only` 下运行,而一个受约束的子 agent 保持其状态目录可写),且经批准的升级重试是一次带有更宽策略的新调用——在配置固定的提供方模式下无法表达。 + +该 seam 仅约束与宿主机共享文件系统和内核的子进程。容器、microVM 和远程执行器不是此 seam 的后端——它们以环境一致的组替换整个能力实现(`ctx.bash`、`ctx.fs`),因为一个 bash 在容器中运行而 fs 工具写主机的 agent 生活在两个割裂的世界中。 + +留待需要时再决定:网络限制是作为独立的 `network_mode` 到来,还是在某个 runner 同时强制两者后合并进 `sandbox_mode`;以及 `SandboxPolicy` 是现在就增加额外的可写根授权(launcher 已支持 `--rw <path>`),还是等到升级机制需要时再加。 + +#### 本地后端与随附 launcher + +`dsh-sandbox-local` 在提供方生命周期内选择一个平台 runner 并缓存结论。Linux 功能性探测 `bwrap` 然后 Landlock;macOS 使用 Seatbelt。不支持的平台和不可用的 runner 失败关闭。每次包装携带后端特定的拒绝签名和 runner 失败签名,以便 `dsh-bash-sandbox` 区分被拒绝的文件操作与损坏的沙箱。`runnerCommand` 作为运维人员对 bwrap 形状 runner 的断言跳过选择,但缺失或不可执行的命令仍被归类为沙箱失败,绝不无约束地运行负载。 + +launcher 是一个约 300 行的 C 程序(纯 C11,直接使用 Landlock UAPI——除静态链接的 musl 外无其他库,因此审计面仅为该文件加内核的稳定 syscall 契约):`--ro <path>` / `--rw <path>` 授权,`--`,被包装的 argv;它在自身上安装规则集并 `exec`(规则集跨 `execve` 继承,且它在限制前设置 `no_new_privs`);`--probe` 在一个短生命周期子进程中强制最大规则集,仅当内核确实强制时才以 0 退出;launcher 失败以 125 退出且不 exec。 + +Landlock launcher 源码和包工作区位于 `native/landlock-run`,与 harness 消费方同仓。独立的 [`node-addon-landlock-run`](https://github.com/deepseek-harness/node-addon-landlock-run) 仓库是用于打包并发布 npm 包族的发布镜像;导出流程归 `native/README.md` 所有。平台二进制由 npm 选择,入口包拥有路径解析、探测和 CLI flag,而 harness 将沙箱模式映射为授权。将入口点与其二进制一起版本化,使探测解析和启动语法保持对齐。 + +后端 profile 共享模式契约但在必要的主机授权上有所不同。Landlock 和 Seatbelt 在 read-only 模式下仅允许 `/dev/null`;workspace-write 还允许各自所需的主机临时目录根。每次包装携带后端特定的拒绝签名。Landlock 在较旧的 ABI 无法管控所有操作时报告 partial enforcement,而成功的 bwrap 和 Seatbelt profile 报告 full enforcement。 + +#### bash 消费方 + +`dsh-bash-sandbox` 扩展 `LocalBashExecutor`,并把即将 spawn 的确切 `['bash', '-c', command]` argv 交给 `ctx.sandbox`。拒绝是与其他结果正交的事实,依据当前 runner 的 stderr 方言保守分类。Runner 失败优先于拒绝:前台执行抛出 `SANDBOX_UNAVAILABLE`;结算后的 `BashProcess` 会盖章 `sandbox.runnerFailed`,bash 生产者再通过通用 `task_output` 渲染它。 + +模型看到的仅是结果事实:静态工具描述解释拒绝标记(`[sandbox: file access denied under <mode> mode]`),鼓励尝试可能被拒绝的命令,并禁止绕过拒绝重试;当升级字段被公布时,被拒绝的结果还额外携带升级提示本身,使被认可的同轮次重试在决策点被提示,而非依赖模型回忆描述(§ 升级机制)。没有提示词段落声明沙箱模式(§ 按会话模式)。 + +#### 升级机制:拒绝后一次经批准的更宽重试 + +`BashExecRequest.sandboxPolicy` 是可选的完整按调用输入;解析后的 spec 使该字段显式。`BashExecutor.sandboxMode` 仍是公布已挂载执行器能否兑现该策略的能力事实,因此只有约束组合才暴露升级。seam 接受任何显式策略;工具拥有会话解析和「仅更宽」的升级规则。非沙箱执行器诚实地保持无约束。 + +`ctx.sandboxPolicy.resolve()` 在执行器运行前盖章完整执行策略——显式升级模式 > 会话覆盖 > 配置默认值,且 `SessionHeader.cwd` > 配置的后备根目录。`SandboxBashExecutor.resolve()` 在 spec 上保留该策略,或为直接的无 agent 调用方提供部署后备值,使 `run()`/`start()` 永不读取可变会话状态。每进程包装事实以返回的 `BashProcess` 为键;`onProcessDone()` 在 `done` 结算前分类 stderr 并给该句柄盖章,因此重叠进程各自保留自己的模式和 runner 方言。 + +当约束执行器被挂载时,`bash` 公布配对的 `sandbox_permissions` 和 `justification` 字段。schema 暴露完整的封闭升级词汇,因为有效模式是按会话的;执行拒绝任何不严格宽于该调用有效模式的目标。批准在执行之前解析。`allowed-once` 仅将授权模式盖章到该请求上,而 `rejected`、`cancelled`、`unavailable`、缺失的 approval 服务或缺失的 agent 都以各自不同的结果文本失败关闭。授权不持久化。 + +升级是对被拒绝命令的同轮次重试,使用最窄的足够 `sandbox_permissions` 和一个 `justification`;批准提示是同意步骤。它必须基于实际的拒绝,除非会话已观察到相同的被拒绝访问;禁用或被拒绝的批准终结该命令。重试、批准决策和结果使用既有的工具和批准事件。`dsh-tool-bash` 拥有请求动作,因为执行器 seam 既没有 agent 也没有用户交互所需的 call id。 + +仍未决定:持久授权超出沙箱模式之外的作用域标识是什么——确切调用、路径、命令前缀、会话或时间窗口——这是公布 `allow_always` 选项之前必须回答的问题。 + +#### 按会话模式:会话日志即存储 + +``` +effective(session) = findLast(the session's own knob events)?.value ?? the composition-config default +``` + +默认值是组合配置(`cordis.yml`)——运维人员拥有,进程范围。运行时切换是会话范围的覆盖,记录为该会话自身日志中的一条仅日志事件。重启免疫(恢复会话时回放其日志,覆盖自然恢复,无需追赶机制)和多会话隔离都是构造性的自然结果,且不存在任何外部配置存储。 + +**每个旋钮一种事件,由其领域拥有**——这是每个既有事件族已遵循的可合并扩展 `SessionEventMap` 惯用法(`dsh-user-approval` 中的 `approval/*`、hooks 包中的 `hook/*`): + +```ts +interface SessionEventMap { + 'sandbox/mode': { mode: 'read-only' | 'workspace-write' | 'danger-full-access' } + 'approval/policy': { policy: 'ask' | 'never' } +} +``` + +每个拥有者导出相同的三件套:事件声明、纯 fold(`effectiveSandboxMode(events)` / `effectiveApprovalPolicy(events)`——一个 `findLast`,类型化到领域的封闭联合),以及唯一的写入路径(`setSandboxMode(session, mode)` / `setApprovalPolicy(session, policy)`——切换即其事件;没有任何东西在带外修改状态)。无共享拥有者服务、无通用 facts map、无注册表:第三个旋钮只需将约 40 行模式复制到自己的包中。执行在两侧都遵循 fold——bash 工具的按调用盖章将其作为 § 升级机制优先级链的中间层读取,approval seam 的 `'never'` 门控是[批准 Agent Note](2026-07-06-approval-seam.md) 同一模式的另一侧。 + +沙箱模式不在提示词中叙述;拒绝结果在需要时报告模式,避免基于常驻标签的预防性拒绝。批准策略不同:只有 `'never'` 被声明,因为自动拒绝在行为上与用户的「不」无法区分。策略变更通知被合并,由下一个步骤前检查点递送,重启后有基于日志的回退。通知来源从事件位置推断:最后一个 request header 之后的旋钮事件是用户驱动的;未记录的漂移是运维人员或配置驱动的。 + +**可选的 UI 界面**是 `PermissionService`:一张部署定义的 preset 表,每个条目捆绑一个沙箱模式与一个批准策略。随附的 `workspace-write` 和 `danger-full-access` preset 写入两个领域 setter;preset 表之外的旋钮组合报告为 `custom`。UI 适配器可以把该表暴露为选择器。仅面向自动化的 ACP 传输层不公布任何配置选择器,也不挂载权限 preset 服务。 + +**已提交的事件是提交边界。** 运行时切换在目标会话上记录其 preset 和发生变化的旋钮事件,之后每次能力解析都折叠最后的值。选择有效的会话追加边界由适配器负责;ACP 传输层没有运行时切换路径。(原先 ACP 的空闲切换锚定——将待定的空闲选择保留到下一次提示词提交——已随该桥一并移除。) + +#### 进程内工具 + +fs/web/todo 在进程内执行,因此它们的沙箱语义是各自 seam 层面的策略。fs seam 现在通过沙箱提供方强制共享模式词汇(`dsh-fs-sandbox` 按模式限制 write/edit;见[跨工具族 fs 沙箱 Agent Note](2026-07-14-cross-family-fs-sandbox.md)),因此 `read-only`/`workspace-write` 对文件系统工具也是真实边界,而非仅限 bash 的近似。web/todo 仍不受限制(web 的唯一效果是网络,不在文件效果模式词汇内)。没有通用的按工具沙箱运行时:主机中介的工具仅通过返回主机验证的声明式效果来离开进程,那是一次重写而非包装——后续设计选择了一个共享策略归属 `ctx.sandboxPolicy`,由各 seam 强制,而不是统一包装器。 + +### 测试 + +- **单元测试:** 固定平台选择和 profile、失败关闭的 runner 分类、按调用的模式/根目录解析、按进程事实、升级验证和结果、权限 preset fold 和写入透传、以及叙述器合并。 +- **Keyless 真实 runner:** 在提供方和 bash 消费方层面对 bwrap、Landlock 和 Seatbelt 执行真实文件系统效果测试;一个真实 Cordis 上下文通过已交付的 bash 和 fs 工具并发驱动两个项目会话,证明在自身根目录写入成功、在兄弟根目录写入被拒绝。Packed-install 覆盖率证明注册表 launcher 保持可执行。CI 拒绝静默全跳过。 +- **With-key:** 以只读模式启动真实 ACP 组合,让模型驱动的 bash 写入命中 runner 的拒绝标记,再通过已授权与被拒绝的 workspace-write 重试驱动 bridge 应答器和磁盘效果;不可用的凭证或 runner 自动跳过。 +- **快照:** 固定提示词 delta 和通知,以及两个脚本化的 approval 分支。一个真实 ACP 示例场景把会话放在用户主目录下,同时让部署后备根目录指向 `/tmp`,然后固定一次成功的、由部署选定的 workspace-write 变更;这能区分会话根目录解析与进程后备值,而不依赖 runner 特定的拒绝文本。其他快照以无约束启动,使无关 fixture(测试前置数据)保持平台无关。 + +## 延迟阶段 + +每个阶段在被拾起时获得完整设计,对照当时的代码验证,并在其涉及的层级带上单元测试、真实 API e2e 和快照覆盖率落地。 + +- **第二个消费方**——`subagent-acp` 可选地约束子 agent(按调用策略;默认无约束——子 agent 必须写入自己的持久化)。 +- **更多环境**——环境一致的能力组示例(如 bash+fs 对一个容器)。 +- **Windows 链**——`PLATFORM_CHAINS.win32` 保留为空(失败关闭);填充它意味着来自 AppContainer/restricted-token 家族的约束 runner,从其自己的仓库按 `node-addon-landlock-run` 模板交付,加上其 profile 方言和拒绝/runner 失败签名。 + +## 曾考虑的替代方案 + +- **命令字符串启发式预检**:否决。无法理解展开/子进程/符号链接;严格尝试(运行它,让内核决定)是唯一可信的拒绝信号。 +- **即使平台仅有一个后端也功能性探测**:否决。探测用于在候选者之间仲裁;只有一个时无需决策,且探测开销对每个会话的首次约束命令征税(对未来重量级后端而言代价过高)。runner 自身执行时的失败关闭拒绝加 `runnerFailureSignatures` 分类承载了安全属性。 +- **提交构建好的 launcher 二进制**:否决。diff 中的二进制不可审查且膨胀历史;经审查的源码 + 原生 CI 构建 + launcher 仓库的字节固定发布演练使二进制远离所有代码树。 +- **安装时编译 launcher**:否决。将 C 工具链强加给每个消费方;仅在碰巧有编译器时才存在的备选不是备选。 +- **从一个构建器交叉编译两种架构**:否决。仅为重建两个约 70 KB 的二进制就需要携带一个固定的交叉工具链(rustup targets、zig 或容器镜像);每架构的原生 runner 已存在,各自构建自己的平台包(`node-addon-require-builtin` 模式,launcher 仓库自己的流水线)。 +- **无备选(bwrap 或失败关闭)**:否决。将失败集中在沙箱最重要的主机上,最终因放弃而降级到 `danger-full-access`。 +- **将机制保留在 `dsh-bash-sandbox` 内部**:否决。阻塞既有的第二个消费方,使未来阶段从一个 bash 插件的配置中读取模式,且无法表达升级。 +- **提供方上的配置固定模式**:否决。每进程一个模式;无法服务具有不同策略的并发消费方,也无法表达一次性放宽重试。 +- **一个接口同时覆盖容器/VM**:否决。`confine(argv)` 预设共享文件系统;环境隔离是作为一致组部署的能力兄弟后端。 +- **通用 ToolRuntime 包装任何工具**:否决。对进程内工具(闭包了 `ctx`)机械上不成立;声明式效果重写对 fs/web/todo 而言不合理。 +- **在执行器内部(`dsh-bash-sandbox`)请求批准**:否决。没有可路由的 `agent`,没有可附加提示词的 `callId`;添加它们会让传输 seam 了解会话和 UI——工具层持有两者并拥有面向模型的词汇。 +- **同一工具调用内自动重试**:否决。日志无法重建的隐藏重入:一个 `tool/call` 会产生两次具有不同策略的执行——重试是一次新的带有自身参数和结果事实的已记录调用。 +- **无条件公布升级字段**:否决。在 `dsh-bash-local` 下它们是死杠杆——公布 harness 无法兑现的选项会制造注定失败的授权;能力门控仅需注册时一次读取。 +- **默认值相对的升级阶梯(仅公布比执行器注册时默认值更宽的模式)**:否决。按会话覆盖使默认值成为错误的基线——切换到比默认值更窄的会话恰恰失去它需要的杠杆,而在 `danger-full-access` 默认值下字段完全消失,同时一个被覆盖为 `read-only` 的会话仍处于约束中却没有升级路径。枚举固定封闭的目标词汇;严格放宽是针对会话有效模式的按调用执行检查。 +- **按会话动态工具 schema**:否决。schema 设计上是注册表全局的(一套 assembly 词汇、固定 header 快照契约),按会话重新注册只能买到执行时严格放宽检查已保证的东西,代价是按会话的 schema 表面和每次切换的 header 变动。 +- **将重试硬匹配到先前的拒绝**:否决。命令字符串同一性脆弱(引号、`workdir`、env 前缀、作为失败阶段重试的管道)——要么误拒诚实的重试,要么被轻易满足;真正的边界是人看到命令 + 理由。仅在 `allow_always` 授权存储需要机器可检查的范围时才重新考虑。 +- **通用 `env/state` facts map 加拥有者服务**:否决。approval 和沙箱独立组合,因此任何一方的状态都不应拖入第三个包;单键 fold 各自是一个 `findLast`,拥有者服务自然消解;没有跨旋钮的不变式,因此原子多键补丁无收益。 +- **通过 `agent/user-message` + 总线事件叙述**:否决。它预设了一个不存在的轮次入口 seam(真正的 seam 是 `agent/prompt-submit`),而步骤前检查点的位置使一个监听器能够同时服务合并的轮次入口通知和轮中即时性约束。 +- **提示词中常驻声明沙箱模式(+ 切换叙述器)**:先交付后移除,基于实际证据:当每个请求中都有 `Bash commands run under the "read-only" file sandbox.` 时,模型拒绝尝试被拒绝后可升级的工作(首次手动会话中十二个轮次有五个以零工具调用结束),将沙箱变成了软锁定。拒绝标记在需要时命名模式,升级字段承载恢复路径;批准旋钮保留其声明,因为自动拒绝在行为上与人的「不」无法区分。 +- **用专门的簿记事件追踪「上次告知」**:否决。`request/header` fold 已记录模型看到的确切提示词;将封闭的候选句子解析回来替代了第二条簿记流——事件仅在它们本身即为存储时才需要。 +- **相互独立的沙箱与批准选择器**:否决。一个部署定义的权限 preset 让两个策略旋钮对暴露运行时切换的 UI 客户端保持一致。 + +## 后果 + +已交付并固定的内容——测试中的各层级分别保障: + +- 被拒绝的命令以 `sandbox_permissions` + `justification` 重试时,通过组合的应答器链提示用户;授权使该次调用在更宽模式下运行(结果事实如此报告),而其他所有调用保持各自的有效模式;每种非授权结果产生各自不同的错误文本且不执行任何内容。 +- 升级字段恰好在已挂载的执行器约束时存在;不严格宽于调用有效模式的请求以自身文本失败关闭且不提示任何人;没有 ApprovalService 的部署对升级调用失败关闭,对普通调用不影响。 +- 系统提示词从不声明沙箱模式(批准 `'never'` 策略是唯一被声明的旋钮),且整个交互——header、旋钮事件、通知、批准、结果——仅从会话日志即可重建,除两个旋钮事件外无额外事件类型。 +- 一次 preset 选择只记录发生变化的旋钮值,而无操作的选择不记录任何内容;批准策略切换最多以一条合并通知叙述,已提交的沙箱切换由下一次调用的盖章兑现。 +- 恢复的会话的覆盖直接生效,无需追赶状态;进程停止期间变更的默认值在会话的首个新请求前被叙述,归因于运维人员。 +- 两个并发会话永远看不到彼此的状态或通知。 +- 同一个 Cordis 上下文中的两个并发项目会话解析各自独立的工作区根目录;bash 和 fs 写入在调用方会话的 cwd 内成功,对其相邻会话的 cwd 则失败。 +- `agent-loop` 未被触及——一切搭载 `systemPrompt.section`、`SessionEventMap` 合并、`agent.inject()`、`agent/pre-step`、`agent/prompt-submit` 和由能力拥有的策略解析。 + +代价与已接受的限制: + +- **单一包装的幻觉被有意放弃。**`tools/pre-execute` 包装加提示词约定无法解决沙箱批准——正确的设计需要结构化拒绝、原生 runner 探测、按调用策略承载和一致的跨工具族强制,本设计为此付出了代价。 +- **`read-only` 通过后续设计成为跨工具族边界。** 本 Agent Note 最初只交付 bash 强制;[跨工具族 fs 沙箱 Agent Note](2026-07-14-cross-family-fs-sandbox.md) 通过沙箱化的 `ctx.fs` 提供方把同一模式词汇扩展到文件系统工具,并将 mode/root 配置和 `sandbox/mode` 覆盖迁移到 `ctx.sandboxPolicy`(§ 进程内工具)。 +- **Windows 没有后端。** 其链槽保留为空——失败关闭,绝不穿透;填充它是延迟阶段。 +- **Seatbelt 层级依赖 Apple 已弃用但仍交付的 `sandbox-exec` CLI。** 作为 darwin 的唯一候选,它无需探测即被选中,因此未来移除会在执行时作为 runner 失败分类浮现——重新抛出 `SANDBOX_UNAVAILABLE`,命令从未运行;失败关闭,绝不开放。 +- **Landlock 约束的完整度取决于运行内核的 ABI。** 报告为 `enforcement: 'partial'` 而非拒绝——这是有意的权衡,使备选在旧内核主机上仍可用。 +- **launcher 作为注册表依赖到达。** 通过其自身仓库的发布流水线(经审查的 C 源码、原生 CI 构建器、字节固定的发布演练)加上本仓库的版本固定获得信任——真实内核 e2e 测试腿是通过安装字节为行为背书的。 +- **模型可能过度请求。** 在没有拒绝依据的情况下升级,或在 `workspace-write` 足够时选择 `danger-full-access`:描述引导且枚举强制阶梯,但人的提示词是实际门控;`approval/asked` 原因使过度请求可审计,且 `prepend` 策略应答器可以自动拒绝部署永远不想要的模式。 +- **公布的目标集是静态的,而有效模式是按会话的**(schema 是注册表全局的)——已处于最宽模式的会话仍被提供这些字段。构造上无害:执行时的严格放宽检查(而非枚举)是安全边界——非放宽请求以自身文本失败且不提示任何人。 +- **授权的升级不等于可工作的沙箱。** 不可用的后端即使对授权升级到约束模式也仍然失败关闭——在平台没有链或所有探测失败时于 `confine()` 阶段,在未探测的唯一 runner 拒绝时于执行阶段(归类为沙箱失败而非命令失败)——而授权的 `danger-full-access` 运行根本不触及提供方:此时授权(而非探测)是权威。 +- **批准叙述器的重启基线解析提示词文本。** 封闭的候选句子由写入模块本身拥有,因此措辞变更是同一文件中写入器+解析器的协调编辑;header 早于该段落的会话静默采用当前策略而不发通知。 +- **批准段落仍是动态提示词表面**(`'never'` 切换会破坏该会话的提供方提示词前缀缓存)。已接受:策略切换罕见,且模型基于过时的 `'never'` 行动更糟。沙箱旋钮不再触及提示词。 +- **模型可能持有关于沙箱模式的过时信念**(没有任何东西宣布切换)。有意接受:下一次尝试的标记或成功会纠正它,而宣布的观察到的失败模式——预防性拒绝——比一次浪费的重试更糟。 + +## FAQ + +- **一个命令返回了 `[sandbox: file access denied under read-only mode]`——它失败了吗?** 它运行了,内核拒绝了一个文件操作:拒绝是与退出码正交的结果事实。教学禁止绕过它重试;唯一被认可的动作是以升级请求重试同一命令一次。 +- **如何区分损坏的沙箱与失败的命令?** Runner 失败在分类中优先于拒绝:匹配包装的 `runnerFailureSignatures` 的失败运行意味着命令从未运行——前台重新抛出结构化的 `SANDBOX_UNAVAILABLE` 并附带 runner 的 stderr 行,后台任务盖章 `sandbox.runnerFailed` 并渲染自己的标记。损坏的沙箱永远不会被读作失败的命令,且命令永远不会无约束运行。 +- **在没有后端的平台上会发生什么——今天的 Windows?** `confine()` 抛出失败关闭的 `SANDBOX_UNAVAILABLE`,命令永不 spawn;`win32` 是保留的空链,由测试固定为同样失败关闭,直到 Windows runner 填充它(§ 延迟阶段)。 +- **`bwrap` 已安装在我的主机上但不可用(禁用了非特权 userns、LSM 拒绝 `mount`)——会发生什么?** 链探测是功能性的——它构建并强制一个真实 profile 而非检查 `--version`——因此存在但不可用的 `bwrap` 探测失败,选择落到注册表安装的 Landlock launcher,结论在提供方生命周期内缓存。 +- **沙箱限制网络或进程可见性吗?** 不——`SandboxMode` 仅声称文件操作;bwrap profile 刻意不 unshare pid,没有后端声称网络。网络限制是否成为自己的旋钮留在 § seam 中开放。 +- **哪些工具实际在约束下运行?** 通过 `ctx.bash` 的 OS 子进程——bash 工具及传递性的钩子命令——再加上通过沙箱化 `ctx.fs` 提供方运行的文件系统工具(`read`/`write`/`edit`,见[跨工具族 fs 沙箱 Agent Note](2026-07-14-cross-family-fs-sandbox.md)):bash 通过 OS runner 约束,fs 通过进程内路径围栏约束,二者都以同一个 `ctx.sandboxPolicy` 模式为键。web/todo 仍在进程内且不受限制(web 的唯一效果是网络,不在文件效果模式词汇内)。 +- **授权的升级会持久化吗?** 不会。授权由发起请求的确切前台或后台调用消费;每个相邻调用保留自己的有效模式。后续的后台拒绝通过 `task_output` 呈现,并且可以作为一次新的精确命令重试的依据。 +- **运行时模式切换何时生效?** 一旦其会话事件提交,紧接着的下一次能力解析就会折叠并盖章新模式。模型不被告知常驻模式;其下一个命令直接在新策略下运行,任何拒绝都会在使用点命名该策略。 +- **重启后什么存活——如果运维人员在进程停止期间改了配置默认值呢?** 覆盖从会话日志回放(`effective = fold ?? config`),因此恢复的会话以零追赶机制保持其模式;离线漂移的默认值以与切换相同的方式改变行为(批准策略因被声明,还额外以运维人员/配置归因叙述)。 +- **结果上的 `enforcement: 'partial'` 是什么意思?** 所选后端强制其内核 ABI 管控的子集——例如 ABI v3 之前的 Landlock 不管控路径 truncate——并以结构化方式如此声明而非拒绝主机;探测的报告行区分各种情况。bwrap 和 Seatbelt profile 构造上管控所有承诺的文件操作,因此始终报告 `full`。 + +## 先例 + +本设计复制或对比的仓库内先例: + +- [能力 seam Agent Note](../architecture/2026-06-13-capability-seams.md)——接口/实现/消费方拆分与「不要过早拆分」的时机规则(第二个消费方满足了该规则)。 +- `dsh-bash` 的 request/spec 拆分([bash 词汇目录](../../../../docs/core-data-structures/bash.md))——完整的 `sandboxPolicy` 搭载其按调用载体,以及显式 `resolve()` 默认约定。 +- [批准 seam Agent Note](2026-07-06-approval-seam.md)——升级请求通过的通道;其应答器 waterfall(瀑布式事件)、审计对和单包理由记录在那里。 +- [事件溯源会话](../architecture/2026-06-11-event-sourced-sessions.md)与[轮次封闭不变式](../architecture/2026-06-15-turn-enclosure-invariant.md)——按会话模式 fold 所依赖的日志即存储基础,以及锚定设计遵守的提交边界。 +- [拦截 seam Agent Note](2026-06-30-interception-seams.md)——`tools/pre-execute` 词汇,升级门控刻意不复用它(升级调用没有自己的 pre-execute 时刻)。 diff --git a/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.i18n.yaml b/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.i18n.yaml new file mode 100644 index 0000000000..940908457f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-07-mcp-client-plugin.md: 2a8ad62e3bad1f2ae47100294f5dba25ceb47d12 +2026-07-07-mcp-client-plugin.zh.md: 9860d5ec805b394eb0c5f59f54349264593a5599 diff --git a/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.md b/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.md index 95cad58b46..2a8ad62e3b 100644 --- a/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.md +++ b/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-07-mcp-client-plugin.zh.md) + ## Problem The harness had no way to consume tools from the MCP (Model Context Protocol) ecosystem. MCP is the emerging standard for tool servers — GitHub, filesystem, databases, code search, and hundreds of community servers expose tools via MCP. Users want to point the harness at one or more MCP servers and have their tools appear as native model-facing tools, without writing per-server glue code. @@ -97,7 +99,7 @@ This server-qualified shape is the de-facto standard among multi-server agent cl 1. On connect: drain `client.listTools()` pagination, derive every tool's `publicName`, then register each as a raw `ToolDefinition` via `ctx.tools.register()`. The MCP JSON Schema and description pass through unchanged (no `defineTool` DSL conversion); only the model-facing `name` is replaced. 2. Listen for `notifications/tools/list_changed` → re-run the same sync (dispose previous generation, register new). Deterministic names mean unchanged tools keep their names across re-syncs. 3. The executor closes over `rawName`; the public name is never sent to the server and never parsed to recover the raw name. -4. No `presentCall`/`presentResult` — the ACP bridge's generic-card fallback handles rendering. +4. No `presentCall`/`presentResult` — UI consumers use the provider-neutral generic-card fallback. 5. Tools are transparent in the system prompt — no "[via MCP]" annotation beyond the name itself. ### Public name normalization @@ -199,7 +201,7 @@ Coverage is named per tier; each behavior lives at the cheapest tier that can ex - **Unit** (`tests/mcp-client.spec.ts`, `tests/apply.spec.ts`, mocked MCP SDK): the `publicToolName` algorithm (clean, normalize, truncate-and-hash, determinism, distinct-identity separation), raw-vs-public wire discipline, cross-server and native-tool coexistence, duplicate-`serverName` load failure and reservation release, invalid-tool-list rejection, generation swap/rollback, failed-re-sync retention, result mapping, cancellation, config schema validation. 100% per-file coverage gates the package. - **E2E** (`tests/mcp-client.e2e.ts`, keyless): the real MCP protocol against the in-repo fixture server, `@modelcontextprotocol/server-everything`, and `@modelcontextprotocol/server-filesystem` over stdio, and against an in-process `StreamableHTTPServerTransport` server over Streamable HTTP — discovery under the namespace, dotted-name normalization end to end, execution round-trips, duplicate-`serverName` rejection, disposal. -- **Snapshot**: deliberately none. MCP tools introduce no new transcript surface — they register as raw `ToolDefinition`s and render through the ACP bridge's generic-card fallback, which the bridge's unit suite already pins (`packages/ui/acp/tests/stream-update.spec.ts`). Adding an MCP server to the snapshot example's `cordis.yml` would mutate the pinned `text-turn` system-prompt fixture (forcing a with-key re-record of every recorded expected output) and make every replay depend on spawning an external MCP server process — for zero new rendering behavior. If a later change gives MCP tools their own render intent, that change names its snapshot coverage then. +- **Snapshot**: deliberately none. MCP tools introduce no new presentation shape — they register as raw `ToolDefinition`s and UI consumers use the generic-card fallback already pinned by their presentation suites. Adding an MCP server to a runnable snapshot composition would mutate its pinned system-prompt fixture and make every replay depend on spawning an external MCP server process for no new behavior. If a later change gives MCP tools their own render intent, that change names its snapshot coverage then. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.zh.md b/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.zh.md new file mode 100644 index 0000000000..9860d5ec80 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.zh.md @@ -0,0 +1,214 @@ +# Agent Note: MCP 客户端插件——连接外部 MCP 服务器并桥接其工具 + +Status: implemented + +[English](2026-07-07-mcp-client-plugin.md) | 中文 + +## 问题 + +harness 此前无法消费 MCP(Model Context Protocol)生态中的工具。MCP 是工具服务器的新兴标准——GitHub、文件系统、数据库、代码搜索以及数百个社区服务器都通过 MCP 暴露工具。用户希望将 harness 指向一个或多个 MCP 服务器,让其工具以原生的模型可见工具形式出现,而无需为每个服务器编写胶水代码。 + +`ToolRegistry` 已经接受原始 JSON Schema 工具定义(`dsh-tools` README 中有记录:「Raw JSON-Schema tool definitions (from MCP servers) are still accepted by `ToolRegistry.register()` directly」),扩展实操手册(cookbook)也勾勒了预期模式(「MCP | one plugin per server: discover tools → `ctx.tools.register()`」)。基础设施已就绪,缺的是桥接插件。 + +## 决策 + +### 包 + +单个包(package) `@deepseek-ai/dsh-mcp-client`,位于 `packages/mcp/mcp-client/`。不做能力 seam 的三包拆分——可预见范围内不会有第二种 MCP 客户端实现,且约定是「不要预防性拆分」([能力 seam Agent Note](../architecture/2026-06-13-capability-seams.md))。 + +### SDK + +使用官方 [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk)(`Client`、`StdioClientTransport`、`StreamableHTTPClientTransport`)。harness 不自行实现 JSON-RPC,与 ACP 委托给 `@agentclientprotocol/sdk` 的做法一致。 + +### 范围 + +仅 MCP Client(不含 server 端——ACP 已承担「将 harness 暴露为 agent」的角色)。仅桥接 **Tools**——Resources 和 Prompts 延后处理(它们需要 harness 侧尚不存在的消费机制,且设计空间较大)。 + +### 插件形态 + +命名空间插件(具名导出 `name`/`inject`/`Config`/`apply`,无 `export default`)。`inject: ['tools']`。每个 MCP 服务器对应 `cordis.yml` 中的一个插件实例——同一个包以不同配置加载 N 次,与 `dsh-tool-subagent` 相同。 + +### 配置 + +以 `transport` 字段为判别的扁平联合类型: + +```typescript +interface StdioConfig { + transport: 'stdio' + serverName: string // required namespace, ^[A-Za-z0-9_-]{1,32}$ + command: string + args?: string[] + env?: Record<string, string> + cwd?: string + toolCallTimeoutMs?: number // default 60_000 +} + +interface StreamableHttpConfig { + transport: 'streamable-http' + serverName: string // required namespace, ^[A-Za-z0-9_-]{1,32}$ + url: string + headers?: Record<string, string> + toolCallTimeoutMs?: number // default 60_000 +} + +type Config = StdioConfig | StreamableHttpConfig +``` + +`serverName` 是稳定的本地标识,用于在模型可见名称(见下文)中为该服务器的工具提供命名空间。它有意设计为用户配置,而非远端的 `serverInfo.name`:远端名称是不可信输入、跨部署不唯一(同一服务器的生产和预发布实例报告相同名称)、且可能在服务器升级时变化——这些都不得静默重命名模型可见工具。多个活跃实例使用重复的 `serverName` 属于配置错误:后加载的实例在启动时以可操作的错误消息失败,绝不静默覆盖或跳过。短 `serverName`(如 `gh`)也是缩短公开名称的调节手段。 + +`cordis.yml` 用法示例: + +```yaml +- id: mcp-github + name: '@deepseek-ai/dsh-mcp-client' + config: + serverName: github + transport: stdio + command: npx + args: ['-y', '@modelcontextprotocol/server-github'] + env: + GITHUB_TOKEN: !!js process.env.GITHUB_TOKEN + +- id: mcp-web + name: '@deepseek-ai/dsh-mcp-client' + config: + serverName: web + transport: streamable-http + url: http://localhost:3000/mcp + headers: + Authorization: !!js `Bearer ${process.env.MCP_TOKEN}` +``` + +模型看到的是 `mcp__github__create_issue`、`mcp__github__search_code`、`mcp__web__search`。 + +### 生命周期 + +启动时从 `cordis.yml` 加载。HMR(热模块替换)(`@cordisjs/plugin-hmr`)提供热替换:编辑 yml 条目触发旧实例的 dispose(资源释放)(断开连接、注销工具),并创建新实例(连接、发现、注册)。目前不提供运行时动态 API。公开名称是 `(serverName, rawName)` 的纯函数,因此保持 `serverName` 不变的 HMR 替换会重建完全相同的模型可见名称——会话历史和权限规则保持有效——而添加或移除不相关的服务器永远不会重命名已有工具。 + +### 工具发现与注册 + +每个 MCP 工具有两个名称: + +- `rawName`——MCP `Tool.name` 的原始值,仅用于协议通信(`tools/call`)。 +- `publicName`——在 `ToolRegistry` 中注册的全局唯一模型可见名称: + + mcp__<serverName>__<rawName> + +这种按服务器限定的形式是多服务器 agent 客户端的事实标准——所有被调研的终端用户产品都按服务器限定 MCP 工具名([Claude Code](https://code.claude.com/docs/en/agent-sdk/mcp#tool-naming-convention) `mcp__github__list_issues`、[Codex](https://openai.com/index/unrolling-the-codex-agent-loop/) `mcp__weather__get-forecast`、[Gemini CLI](https://geminicli.com/docs/tools/mcp-server/#3-tool-naming-and-namespaces)、[VS Code](https://github.com/microsoft/vscode/blob/ab9ec62c6a61e429a9abd612ff220c3f4834c9ea/src/vs/workbench/contrib/mcp/common/mcpServer.ts#L217-L260)、[Cline](https://github.com/cline/cline/blob/52fdbb1d72f7324a28142a7ba7678d4b53c902f4/sdk/packages/core/src/extensions/mcp/name-transform.ts#L20-L35)、[Roo Code](https://github.com/RooCodeInc/Roo-Code/blob/b867ec9145750d0ae1ff7f02d35406e9bf2a0b16/src/utils/mcp-name.ts#L117-L140)、[Goose](https://github.com/block/goose/blob/b3a012cbdde854b0fe14f95b1c48543bf6517c0a/crates/goose/src/agents/extension_manager.rs#L1391-L1441)、[OpenCode](https://github.com/anomalyco/opencode/blob/d199b1bff90282a4f9cd6251b5fc7b16875a52f6/packages/opencode/src/mcp/catalog.ts#L117-L120));`mcp__<server>__<tool>` 的拼写方式与 Claude Code 和 Codex 一致。`mcp__` 前缀将 MCP 注册与原生工具的命名空间隔离,并为权限/遥测规则提供稳定的匹配模式(`mcp__*`、`mcp__github__*`)。 + +1. 连接时:遍历 `client.listTools()` 的分页结果,推导每个工具的 `publicName`,然后通过 `ctx.tools.register()` 将其注册为原始 `ToolDefinition`。MCP 的 JSON Schema 和描述原样透传(不做 `defineTool` DSL 转换);仅替换模型可见的 `name`。 +2. 监听 `notifications/tools/list_changed` → 重新执行同步(dispose 上一代、注册新一代)。确定性命名意味着未变化的工具在重新同步后保持原名。 +3. 执行器闭包持有 `rawName`;公开名称永远不发送给服务器,也永远不被解析以还原原始名称。 +4. 无 `presentCall`/`presentResult`——UI 消费方使用提供方无关的通用卡片兜底。 +5. 工具在系统提示词中是透明的——除名称本身外不附加「[via MCP]」标注。 + +### 公开名称规范化 + +MCP 允许工具名最长 128 字符且可包含 `.`;DeepSeek 的函数名契约允许 `[A-Za-z0-9_-]` 且最多 64 字符。公开名称按确定性规则规范化:非法字符替换为 `_`,当替换或截断改变了名称时,追加 `(serverName, rawName)` 标识的 12 位十六进制 SHA-256 hash,确保不同的 MCP 标识永远不会坍缩为同一个公开名称: + +```typescript +function publicToolName(serverName: string, rawName: string): string { + const joined = `mcp__${serverName}__${rawName}` + const normalized = joined.replace(/[^A-Za-z0-9_-]/g, '_') + if (normalized === joined && normalized.length <= 64) return normalized + const hash = sha256(`${serverName}\0${rawName}`).slice(0, 12) + return `${normalized.slice(0, 64 - 13)}_${hash}` +} +``` + +### 名称冲突处理 + +MCP 仅保证工具名在[单个服务器内](https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool-names)唯一;跨服务器冲突是常态而非例外(一项[微软研究院调查](https://www.microsoft.com/en-us/research/blog/tool-space-interference-in-the-mcp-era-designing-for-agent-compatibility-at-scale/#namespacing-issues-and-naming-ambiguity)覆盖 1,470 个服务器,发现 775 个冲突的工具名;仅 `search` 就出现在 32 个服务器中,官方 GitHub 服务器发布的是裸名 `create_issue`)。始终启用的命名空间从结构上杜绝冲突,而非在冲突发生时再处理: + +- 两个服务器都发布 `search` → 共存为 `mcp__github__search` 和 `mcp__web__search`。 +- 名为 `search` 的原生 harness 工具不受影响。 +- 重复的 `serverName` 配置使后加载的实例在启动时失败(见配置一节)。 +- 服务器列出重复的工具名属于无效工具列表:同步抛出异常,上一代注册保持不变。 +- 替换期间的注册表冲突只可能意味着外部工具占据了该服务器的 `mcp__<serverName>__` 命名空间:部分代注册被回滚(该服务器零工具),并以醒目日志记录错误。 + +工具永远不会被静默跳过;哪些工具可用永远不取决于插件加载顺序。 + +### 命名不变式 + +1. 每个 MCP 工具拥有稳定标识 `(serverName, rawName)`;每个活跃标识恰好对应一个公开名称。 +2. 公开名称是确定性的、全局唯一的,且满足 DeepSeek 64 字符 `[A-Za-z0-9_-]` 契约。 +3. MCP `tools/call` 始终接收原始的 raw name。 +4. 连接、断开或重新同步不相关的服务器永远不会重命名已有工具。 +5. 注册顺序永远不决定哪个工具可用。 + +### 工具执行 + +为来自同一个 MCP 服务器的所有工具提供统一的 `execute` 处理器: + +1. 解析 `rawName`(执行器闭包持有它),以配置的超时时间调用 `client.callTool({ name: rawName, arguments }, { signal: exec.signal })`——公开名称永远不发送给服务器。 +2. 映射结果: + - 多个 `text` 内容块 → 以 `'\n'` 连接为单个 `TextBlock`(必要原因:`flattenText` 使用 `join('')` 无分隔符,多块会丢失块间边界)。 + - `image` 内容块 → 丢弃并 `ctx.logger.warn`(harness 没有图片内容块类型;[删除图片 Agent Note](../simplification/2026-07-04-drop-image-content-block.md))。 + - `isError: true` → 映射到 harness 的 `isError` 结果路径(`{ content: [...], isError: true }`)。 +3. 取消:`exec.signal`(来自 agent loop(智能体循环)的取消)透传给 MCP SDK 的 `callTool`,后者向服务器发送 `$/cancelRequest`。 + +### 子进程环境(stdio 传输) + +复用 `dsh-subagent-acp` 的 `buildChildEnv` + `SENSITIVE_ENV_PATTERN` 清洗逻辑:过滤环境变量(剥离匹配 `/KEY|SECRET|TOKEN/i` 的凭证形变量),然后将 `config.env` 覆盖合并到顶层。显式配置的 env 不受清洗影响。 + +### 断连 / 崩溃 + +不自动重连。如果 MCP 服务器进程退出或传输层关闭: + +1. effect dispose → 所有已注册工具被注销(fiber 作用域的 disposer)。 +2. 后续模型对这些工具的调用 → `ToolNotFoundError` → `isError: true`。 +3. 恢复:用户编辑 `cordis.yml`(触发 HMR 重载)或重启 harness。 + +这与 ACP subagent 模式一致:「崩溃即终态,报告错误,清理资源,不重试。」 + +## 曾考虑的替代方案 + +### MCP Server 端(将 harness 工具暴露给外部 MCP 客户端) + +延后。ACP 桥接已将 harness 暴露为 agent 服务器。再加一层 MCP server 会以不同协议重复这一功能,而用户的首要需求是消费外部工具,而非暴露自身工具。 + +### 能力 seam 三包拆分(接口 / 实现 / 消费方) + +否决。可预见范围内不会有替代的 MCP 客户端实现——MCP 只有一个协议、一个 SDK。约定是「不要预防性拆分」,直到出现第二种实现。 + +### 指数退避自动重连 + +v1 否决。引入复杂性(工具已注册但暂时不可用的部分可用状态),且 stdio 进程崩溃通常表明配置问题,重试无法修复。HMR 已提供手动恢复路径。如有需要,可在未来作为 `reconnect: boolean` 配置项添加。 + +### 桥接 Resources 和 Prompts + +延后。Resources 需要 harness 侧的机制来决定何时注入内容(系统提示词?按需?模型触发?)。Prompts 需要 harness 尚不具备的「提示词模板」概念。两者都需要独立设计;Tools 是高价值、低风险的起点。 + +### 原始模型可见工具名加可选 `toolPrefix` + +否决。这是最初的提案,基于「大多数 MCP 服务器已在工具名中使用语义前缀(如 `github_create_issue`)」这一前提。该前提不成立:官方 GitHub 服务器发布的是 `create_issue`,参考文件系统服务器发布 `read_file`,Sentry 发布 `search_issues`——且上述微软调查表明冲突在生态规模下很常见。冲突时再加前缀(或 warn-and-skip)还会使可用工具集取决于插件加载顺序,且添加不相关服务器时工具可能被静默重命名——在对话中途使会话历史和权限规则失效。所有被调研的多服务器 agent 产品都不使用裸名。 + +### 仅服务器命名空间(`github__create_issue`,无 `mcp__` 前缀) + +v1 否决。它能防止跨服务器冲突,但无法将 MCP 注册与原生 harness 工具分离,也丧失了 MCP 全局策略匹配模式(`mcp__*`)。前缀仅多花 5 个字符;`mcp__<server>__<tool>` 拼写与 Claude Code 和 Codex 一致,最大化模型的熟悉度。如果 ToolRegistry 未来引入源感知命名空间,届时可作为命名策略变更重新考虑去掉字面前缀。 + +### 从服务器公告的 `serverInfo.name` 派生命名空间 + +否决。远端名称不可信、跨部署不唯一、升级时可变;工具标识和权限规则不得静默跟随它。命名空间是本地配置。 + +### 在工具结果中保留多个 TextBlock + +否决。DeepSeek 序列化器中的 `flattenText()` 在将 `ContentBlock[]` 扁平化为协议格式(wire format)时使用 `join('')`(无分隔符)。多个 text 块会静默丢失块间边界——这是正确性缺陷。所有现有工具返回单个 TextBlock;MCP 桥接遵循同一做法。 + +## 测试 + +覆盖率按层级命名;每个行为放在能表达它的最低成本层级。 + +- **单元测试**(`tests/mcp-client.spec.ts`、`tests/apply.spec.ts`,mock MCP SDK):`publicToolName` 算法(干净名称、规范化、截断加 hash、确定性、不同标识的分离)、raw 与 public 的协议纪律、跨服务器与原生工具共存、重复 `serverName` 加载失败与预留释放、无效工具列表拒绝、代切换/回滚、重新同步失败时的保留、结果映射、取消、配置 schema 校验。100% 逐文件覆盖率门禁约束该包。 +- **E2E**(`tests/mcp-client.e2e.ts`,无需密钥):使用真实 MCP 协议对接仓库内的 fixture(测试前置数据)服务器、`@modelcontextprotocol/server-everything` 和 `@modelcontextprotocol/server-filesystem`(stdio 传输),以及进程内 `StreamableHTTPServerTransport` 服务器(Streamable HTTP 传输)——命名空间下的发现、带点号名称的端到端规范化、执行往返、重复 `serverName` 拒绝、dispose。 +- **快照**:刻意不做。MCP 工具不引入新的展示形态——它们以原始 `ToolDefinition` 注册,UI 消费方使用各自展示测试套件已固定的通用卡片兜底。将 MCP 服务器添加到某个可运行的快照组合会改变其已固定的系统提示词 fixture,且使每次回放依赖于 spawn 外部 MCP 服务器进程,而新增行为为零。如果后续变更为 MCP 工具引入专属渲染意图,该变更届时自行声明快照覆盖。 + +## 后果 + +- 每个 MCP 服务器只需 `cordis.yml` 中的一条配置即完成集成:`serverName: filesystem` 加一条 stdio 命令(或一个 Streamable HTTP URL),就能将 `mcp__filesystem__read_file` 放入模型的工具列表,可调用,协议上使用原始的 `read_file`。 +- 公开名称是会话历史和权限/配置表面的一部分;命名算法是由测试固定的 v1 契约,发布后变更即为破坏性变更。 +- `mcp__<serverName>__` 限定符在每个名称上消耗 token。已接受:描述和 JSON Schema 在工具定义 token 中占主导,而限定符换来了稳定标识、冲突隔离和 MCP 全局策略匹配模式(`mcp__*`、`mcp__github__*`)。 +- **MCP SDK 稳定性**:`@modelcontextprotocol/sdk` 仍在演进中;破坏性变更需要更新桥接。版本已固定,且该 SDK 被广泛采用(Claude Desktop、Cursor、VS Code),因此破坏性变更不太可能悄然发生。 +- **工具 schema 质量**:MCP 服务器可能暴露描述不佳的工具(模糊的描述、不完整的 JSON Schema)。harness 原样透传——垃圾进垃圾出;这是服务器作者的责任,不是桥接的。 +- **Stdio 进程管理**:行为异常的 MCP 服务器如果忽略信号,可能卡住 dispose。Cordis fiber 的 dispose 有有界的完全停稳过程;卡住的传输层最终在框架层面超时。 +- 崩溃恢复是手动的(HMR 编辑或重启)——v1 已接受;`reconnect` 配置作为未来工作保持开放。 diff --git a/.agents/notes/implemented/feature/2026-07-07-plan-mode.md b/.agents/notes/implemented/feature/2026-07-07-plan-mode.md index 06fd50e1f0..f5b76fae5b 100644 --- a/.agents/notes/implemented/feature/2026-07-07-plan-mode.md +++ b/.agents/notes/implemented/feature/2026-07-07-plan-mode.md @@ -4,6 +4,8 @@ Status: implemented > **Superseded vocabulary (2026-07-22):** [Collapse named session modes into plan mode](../simplification/2026-07-22-plan-specific-collaboration-state.md) replaces this note's generic `dsh-mode`, `mode/set`, definition map, and `ctx.modes` design with the current plan-specific `dsh-plan-mode`, `plan/mode`, `{ section }`, and `ctx.planMode` contract. The review, boundary, reconstructability, and sandbox-orthogonality decisions below remain in force; generic API examples are retained as the historical design this simplification removed. +> **Superseded ACP mapping:** [ACP as an automation-only protocol](../simplification/2026-07-23-acp-automation-only-protocol.md) removes the picker, config-option, and elicitation mappings described below. Plan mode remains available to human-facing interfaces. + ## Problem Before this change, the harness had no durable way to put one agent into a distinct working stance. Plan mode needs the agent to explore and design under planning guidance, produce a reviewable artifact, cross an explicit approval boundary, and restore that state across resume and fork without making the model-visible request diverge from the session log. @@ -118,7 +120,7 @@ No new cordis event is declared (`mode/set` rides `session/event`; the listeners Each behind its own decision: subagent mode inheritance via a forwarded creation-time mode option (removed as unconsumed; it returns with its first consumer), preset modes beyond `plan` (read-only, accept-edits), the idle-record primitive if pending-intent loss proves real, and — the big one — **effects self-declaration on tool definitions**: a per-tool read-only/mutating classification (the MCP `ToolAnnotations` vocabulary — `readOnlyHint`/`destructiveHint` — is the natural template, with its untrusted-hint caveat implying trust tiers). That item is what a general per-mode tool policy waits on: this Agent Note first shipped an interim per-mode name allowlist and removed it before release — a hand-maintained list mislabels the effects question, must track every tool a deployment composes, and rots silently as tools arrive — so mode-scoped tool availability (and per-tool `ask` policies) returns as a CONSUMER of declared effects, which is its restart trigger. -The canonical [`examples/acp-agent`](../../../../examples/acp-agent/) composition mounts the mode and question-tool plugins on the full ACP coding server; plan mode is an additive session feature, not a second server profile. Its snapshot suite pins the plan-shaped initial header, a real read, scripted approval, stable tool schemas across the pure-removal header delta, a subsequent edit, rejection feedback, and the keyless mode wire. A self-skipping real-API smoke boots that same leaf, verifies the file before approving the review, and verifies the approved implementation afterward. +The ACP automation composition does not mount plan mode or the question tool. Human-facing compositions own plan selection and review; focused plan-mode tests and interactive-interface snapshots pin its logged state, guidance, review, and stable tool schemas. ## FAQ @@ -138,13 +140,13 @@ Behavioral clarifications of the chosen design; rejected designs live in [Altern **How does plan mode relate to the sandbox's read-only mode?** They are separate axes that never touch: the mode is the collaboration stance (a `mode/set` fold), the sandbox mode is an enforcement knob (a `bash/sandbox-mode` fold, [the sandbox Agent Note](2026-07-06-sandbox.md)) — plan mode neither reads nor caps it, exactly as Codex keeps its Plan/Default presets separate from its sandbox and approval settings. A user who wants kernel-enforced read-only while planning sets both: flip the mode picker AND the sandbox-mode option, in either order; each switch changes only its own fold, so there is no interference and no restore step to crash out of. The log attributes each axis to its own event — the stance to `mode/set`, the confinement to `bash/sandbox-mode`. -**Why aren't sandbox mode, approval policy, or the model themselves modes?** They are individual environment knobs and belong to ACP's `session/set_config_option`; the division this proposal pins is picker-to-modes / knobs-to-config-options, recorded in [the feature matrix](../../../../packages/ui/acp/acp-feature-support.md) now that both this stack's picker and the sandbox stack's config options are landed. A mode definition may later bundle env facts (applied through `ctx.envState` where mounted) so a Codex-style preset stays a single mode; fusing approval policy into the mode CONCEPT itself is rejected in [Alternatives considered](#alternatives-considered). +**Why aren't sandbox mode, approval policy, or the model themselves modes?** They are individual environment knobs independent of collaboration state. The retired ACP mapping is recorded by the [automation-only protocol decision](../simplification/2026-07-23-acp-automation-only-protocol.md). A mode definition may later bundle env facts (applied through `ctx.envState` where mounted) so a Codex-style preset stays a single mode; fusing approval policy into the mode CONCEPT itself is rejected in [Alternatives considered](#alternatives-considered). ## Prior art A survey of shipped plan modes (Claude Code, Cursor, Copilot, OpenCode, Gemini CLI, Cline, Windsurf, Codex) shows the same five parts everywhere — the low-authority tool policy, plan artifact, approval moment, execution-state switch, and durable state that [Problem](#problem) builds on. -The mode surface is a LIST everywhere it is advertised, never a boolean: Claude Code's picker offers `plan` beside `acceptEdits` (plus an auto-mode entry into plan), and Codex exposes `Plan` beside `Default` as collaboration-mode presets while keeping approval and sandbox settings separate. This is the surface [the ACP feature matrix](../../../../packages/ui/acp/acp-feature-support.md) records as the gap, and what sizes the vocabulary as named modes rather than a flag. +The mode surface is a LIST everywhere it is advertised, never a boolean: Claude Code's picker offers `plan` beside `acceptEdits` (plus an auto-mode entry into plan), and Codex exposes `Plan` beside `Default` as collaboration-mode presets while keeping approval and sandbox settings separate. The ACP transport does not advertise this human-facing control. The deployment-owned example prompt borrows the instrumental behavior, not product-specific mechanics. From Codex: remain in plan mode despite imperative implementation language, explore before asking, distinguish repository facts from user-owned choices, and make the plan decision-complete across APIs, data flow, failures, tests, and assumptions. From Claude Code: prohibit mutations and commits, prefer existing patterns, use questions only for requirements or approach choices, and finish through the exit tool rather than a prose approval request. It deliberately omits Codex protocol tags and Claude's plan-file or phased-subagent machinery because those belong to their runtimes, not this plugin contract. @@ -186,7 +188,7 @@ What holds now, pinned by the unit, protocol, snapshot, and real-API tiers: - Native tool schemas and Code Mode's SDK stay byte-identical across default, plan, and custom-mode transitions; only the configured guidance section changes. - Plan mode changes nothing on the enforcement axes: the toolset, the sandbox mode, escalation, and the approval policy behave identically in plan and default — pairing the mode with the independent sandbox/approval knobs is how a deployment hardens planning. - Mode definitions are changeable from `cordis.yml` with no code edit; the complete plan instructions are required there, while missing plan config, malformed definitions, and unknown keys fail at load and unknown mode names fail at `set()`. -- `exit_plan_mode` is always advertised, rejects outside plan, drops only plan guidance after approval, and carries keep-planning feedback in a corrective `isError`; ACP mode updates and each surface's user-interaction provider carry the human side. +- `exit_plan_mode` is always advertised, rejects outside plan, drops only plan guidance after approval, and carries keep-planning feedback in a corrective `isError`; each human-facing surface's user-interaction provider carries the review. - The docs tail shipped with the landing: READMEs, regenerated catalogs (persistence log, config, cordis services, tools), the packages map and architecture rows, and the cookbook row. -The accepted costs: a pending user flip set while idle is lost if the process dies before the next turn (the UI re-applies; the idle-record primitive is the escape hatch if this bites in practice). A mode transition changes the system prompt at order 50, so the cache path from that point onward changes, but the tool schemas and Code Mode SDK no longer churn. **A mode restrains by guidance alone**: a model that ignores the section CAN mutate during plan — the review moment, the session log, and independent sandbox, approval, and filesystem policies are the containment surface. Hardening planning means setting those knobs, not widening the mode; the removed enforcement shapes and their effects-declaration restart trigger remain in [Alternatives considered](#alternatives-considered) and [Deferred](#deferred). The ACP mode surface carries the picker while sandbox, approval, and model selectors remain config options under the division pinned in the [FAQ](#faq) and [feature matrix](../../../../packages/ui/acp/acp-feature-support.md). If ACP removes session modes in favor of config options, the picker mapping can migrate without changing the logged mode state or model surface. +The accepted costs: a pending user flip set while idle is lost if the process dies before the next turn (the UI re-applies; the idle-record primitive is the escape hatch if this bites in practice). A mode transition changes the system prompt at order 50, so the cache path from that point onward changes, but the tool schemas and Code Mode SDK no longer churn. **A mode restrains by guidance alone**: a model that ignores the section CAN mutate during plan — the review moment, the session log, and independent sandbox, approval, and filesystem policies are the containment surface. Hardening planning means setting those knobs, not widening the mode; the removed enforcement shapes and their effects-declaration restart trigger remain in [Alternatives considered](#alternatives-considered) and [Deferred](#deferred). Human-facing interfaces own the plan picker and review interaction; the ACP automation transport carries neither. diff --git a/.agents/notes/implemented/feature/2026-07-07-session-prefix.i18n.yaml b/.agents/notes/implemented/feature/2026-07-07-session-prefix.i18n.yaml new file mode 100644 index 0000000000..63ac02b35e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-07-session-prefix.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-07-session-prefix.md: 322413f541706244a8a9a9113c0b79693fe54ccd +2026-07-07-session-prefix.zh.md: 710cfbd2656d132640d39b1d62374ef2d16be612 diff --git a/.agents/notes/implemented/feature/2026-07-07-session-prefix.md b/.agents/notes/implemented/feature/2026-07-07-session-prefix.md index 7faf80cf80..322413f541 100644 --- a/.agents/notes/implemented/feature/2026-07-07-session-prefix.md +++ b/.agents/notes/implemented/feature/2026-07-07-session-prefix.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-07-session-prefix.zh.md) + ## Problem A plugin often owns a session-stable opener the model must always see — a skills catalog, an AGENTS.md digest, a workspace baseline. Before this seam the harness offered two homes, and both are wrong for that content. The system prompt is one rendered string: message-shaped content (a user-role `<system-reminder>` envelope, a multi-message primer) does not fit it, and providers weight conversation messages differently from system text. Durable history (`agent.inject()`, a `context/message` at session start) makes the opener permanent: every `deriveMessages()` consumer replays it, the compaction retention walk owns it, forks bake it in stale, and a resume cannot refresh it — a catalog captured at session birth outlives the world it described. diff --git a/.agents/notes/implemented/feature/2026-07-07-session-prefix.zh.md b/.agents/notes/implemented/feature/2026-07-07-session-prefix.zh.md new file mode 100644 index 0000000000..710cfbd265 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-07-session-prefix.zh.md @@ -0,0 +1,43 @@ +# Agent Note: 会话前缀——派生历史之前的仅请求消息 + +Status: implemented + +[English](2026-07-07-session-prefix.md) | 中文 + +## 问题 + +插件经常拥有一段会话级别稳定的开场内容,模型必须始终看到它:技能目录、AGENTS.md 摘要、工作区基线。在引入本 seam 之前,harness 为这类内容提供了两个归属位置,但两者都不合适。系统提示词是一个渲染后的单一字符串:消息形态的内容(user 角色的 `<system-reminder>` 信封、多消息引导序列)放不进去,而且提供方对会话消息和系统文本的权重处理不同。持久化历史(`agent.inject()`、会话启动时的 `context/message`)使开场内容变为永久:每个 `deriveMessages()` 消费方都会回放它,压缩(compaction)的保留遍历拥有它,fork 会将其以陈旧状态固化,恢复也无法刷新它——会话诞生时捕获的目录会比它所描述的世界活得更久。 + +显而易见的第三种选项——让插件在请求发出途中编辑 `messages`——被[可重建请求 Agent Note](../architecture/2026-07-05-reconstructable-requests.md)禁止:每个由循环构建的请求都是会话日志的纯函数,因此无论哪个通道承载开场内容,都必须精确记录它所发送的内容。缺失的是一个带有持久记录的仅请求消息通道。 + +## 决策 + +`agent/session-prefix` 是 agent 事件映射上的一个 waterfall(瀑布式事件)([`packages/core/agent/src/types.ts`](../../../../packages/core/agent/src/types.ts)):监听器接收一个冻结的空种子并返回扩展(规范的贡献方式是前置插入 `[mine, ...await next()]`,在协议格式上产生注册顺序)。agent loop(智能体循环)([`packages/core/agent-loop/src/loop.ts`](../../../../packages/core/agent-loop/src/loop.ts))在每个循环实例中触发一次,惰性地在实例首次 `agent/pre-step` 之前执行;组合后的列表被深拷贝、深冻结、缓存在实例上,并在该实例发出的每个请求中置于整个派生历史之前——紧接在提供方的 system 槽位之后([协议格式顺序](../../../../docs/core-data-structures/core.md#the-request-envelope-llmcallconfig-and-the-logged-header))。 + +三个属性承载了这一设计: + +- **仅请求,记录在 header 中。** `deriveMessages()` 从不返回前缀;它唯一的持久记录是实例锚定的 `request/header` 快照上的 `EpochHeader.messagePrefix`——可重建请求 Agent Note 已为请求的非历史部分拥有的通道,因此不引入新的会话事件。配套的 [`dsh-agent-loop/invariant`](../../../../packages/core/agent-loop/src/invariant.ts)对每个循环构建的请求重新计算 `messagePrefix + boundary derivation`;启用该贡献时,未记录的前缀无法到达协议格式。 +- **按实例冻结。** 复用是结构性的,而非靠纪律保证:缓存的产物在会话中途不可变,因此提供方的提示词缓存从构造上成立,前缀以每步零边际成本扩展了可缓存区域。进程重启或 `ctx.agents.resume()` 产生新实例:它重新组合,任何漂移都可追溯地落在 `'resume'` header 快照上。这就是本 seam 创建的路由规则:会话冻结的开场内容走前缀;会话中途变化的内容走仅追加历史通道(`agent.inject()` 或工具/prompt-submit 的 `additionalContexts`——[拦截 seam Agent Note](2026-06-30-interception-seams.md)),每条都是一次性支付的持久 `context/message`,之后被前缀缓存覆盖。 +- **在持久请求信封中保持精确。** 组合先于实例的首次 `agent/pre-step` 和请求边界。第一个已路由请求会把当前前缀记录在其 header 上,因此步骤后的 token 压力会将精确前缀与实际提示词、工具和已路由模型一起读取;通用的步骤前检查点 seam 不携带压缩专属参数。被取消/dispose 中断的组合会被丢弃,永不缓存:感知中止的监听器的降级回退不会泄漏到后续请求中,下一轮次在活信号下重新组合。 + +由于组合在边界快照之前运行,组合监听器的会话追加会加入当前请求的派生历史。压缩在结构上不可能触及前缀(或系统提示词):它重写的是表面节点,而 header 状态从不进入表面。 + +## 测试 + +[拦截测试](../../../../packages/core/agent-loop/tests/interception.spec.ts)固定了以下行为:没有变更 header 时的组合一次复用、前置插入顺序、空前缀省略、不可变性、组合在步骤前检查点之前完成,以及已路由 header 上的前缀;[取消测试](../../../../packages/core/agent-loop/tests/cancel.spec.ts)固定了丢弃与重新组合。Session、不变式、token-meter 和压缩测试覆盖 header 往返、请求重建与持久前缀感知的压力核算。快照归一化保留前缀计数,[固定 header 场景](../testing/2026-07-06-pin-request-header-content-in-one-scenario.md)拥有内容,默认示例保持无前缀。与提供方无关的 seam 无需专门 e2e;带密钥的 [request-cache e2e](../../../../packages/core/agent-loop/tests/request-cache.e2e.ts) 覆盖了其缓存经济性。 + +## 曾考虑的替代方案 + +- **每请求 `before`/`after` 槽位,每步重新计算**(最初提出的形态:一个每请求触发的 waterfall,贡献冻结的 `before` 消息置于历史之前、新鲜的 `after` 消息置于历史之后):否决。每步重新组合 `before` 会引入漂移,必须记录为完整的变更 header;`after` 槽位位于不断增长的历史之后,其 token 在每个请求中重复支付,且其后的所有内容不可缓存。对照各替代方案衡量,当前所有更新模式都能通过持久追加更廉价地满足(支付一次,此后缓存读取),而唯一没有归属的内容是会话稳定的开场——它需要的是冻结,而非重新计算。 +- **系统提示词分段**(`system-prompt/assemble`):对此类内容否决。assembly 渲染为单一 `system` 字符串,消息形态的开场放不进去;且系统提示词被设计为每步重新组装(变化时带完整的变更 header),而开场内容需要按实例冻结的语义。 +- **持久化历史开场**(会话启动时 `inject()`):否决。永久历史正是问题陈述中的失败模式——到处被回放、可被压缩、在恢复后仍保持陈旧状态。 +- **按轮次组合而非按实例组合**:否决。轮次边界的重新组合要么与日志静默失同步,要么强制产生变更 header;且它每次触发都会破坏提供方缓存。合理的刷新点是实例边界,`'resume'` 快照已在那里可追溯地记录漂移。 +- **通过 `agent/pre-step` 携带提示词/前缀,用于临时压力估算**:否决,因为它把通用生命周期 seam 耦合到一个消费方,而且仍会遗漏更晚的请求路由和工具;步骤后的回放会从持久的已路由 header 读取请求信封的每个字段。 +- **专用会话事件承载前缀**:否决。header 事件按设计就是请求的非历史记录;第二个事件会为同一事实提供第二个归属,并多出一个需要保持完整的编解码器。 + +## 后果 + +- `agent/pre-step` 保持通用的 `(agent, turn, step, signal)` 检查点。压缩不接收 prefix 参数;`ctx.tokenMeter` 在步骤后从规范的已路由 header 折叠前缀。 +- 贡献者的内容在会话中途变化时,直到下一个实例才会被重新读取——这是设计意图。需要会话中途目录更新的部署,应将变更通知路由到仅追加历史通道,支付一条持久 `context/message`。 +- 被放弃的 `after` 槽位意味着请求尾部附近没有仅请求通道;仓库中没有任何功能需要它,且恢复它会重新引入本设计旨在避免的每步重复支付成本。 +- 空组合即为规范缺失:无贡献者的部署不记录额外的 header 字节,其请求就是裸派生。 diff --git a/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.i18n.yaml b/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.i18n.yaml new file mode 100644 index 0000000000..95661f953c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-08-repeat-tool-guard.md: 67ec29c6c9fa38bf1d5935c469f3f71b1119dc3a +2026-07-08-repeat-tool-guard.zh.md: 01037f29810c781c33beee414e50412a0c9b0f89 diff --git a/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.md b/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.md index 08f5bb01cf..67ec29c6c9 100644 --- a/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.md +++ b/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-08-repeat-tool-guard.zh.md) + ## Problem A model stuck in a loop re-issues the same tool call with byte-identical arguments — re-running a failing grep, re-reading an unchanged file, polling a command that already gave its answer — and each round trip burns tokens, wall-clock, and (for paid APIs) money without adding information. The harness has nothing that notices: the loop has no step budget, no plugin tracks call repetition, and the model only escapes when it happens to vary its own behavior. The failure mode is real and cheap to detect — [pi-repeat-tool-guard](https://github.com/Kingwl/pi-repeat-tool-guard) ships exactly this as a pi coding-agent extension: count consecutive identical calls and, past a threshold, append a `<system-reminder>` telling the model to stop repeating itself and change course. diff --git a/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.zh.md b/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.zh.md new file mode 100644 index 0000000000..01037f2981 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.zh.md @@ -0,0 +1,76 @@ +# Agent Note: 重复工具调用守卫插件 + +Status: implemented + +[English](2026-07-08-repeat-tool-guard.md) | 中文 + +## 问题 + +模型陷入循环时,会以字节级相同的参数反复发起同一个工具调用——重新运行一条失败的 grep、重新读取一个未变化的文件、轮询一条已经给出答案的命令——每一轮往返都消耗 token、挂钟时间以及(对付费 API 而言)金钱,却不带来新信息。harness 目前没有任何机制能察觉这一点:循环没有步骤预算,没有插件追踪调用重复,模型只有在碰巧改变自身行为时才能跳出。这种失败模式真实存在且检测成本极低——[pi-repeat-tool-guard](https://github.com/Kingwl/pi-repeat-tool-guard) 正是以 pi coding-agent 扩展的形式提供了这一功能:统计连续相同调用次数,超过阈值后追加一条 `<system-reminder>` 告诉模型停止重复并换个方向。 + +harness 已经具备 pi 扩展所使用的全部 seam,而且更好:[拦截 seam Agent Note](2026-06-30-interception-seams.md)赋予 `tools/post-execute` 一种经过认可的方式,将面向模型的上下文附加到已完成的调用上;循环缓冲并注入该上下文,同时保持调用/结果的邻接关系;注入的上下文是一条已记录的 `context/message`——因此原生守卫无需新增会话事件即可满足「模型可见 ⟺ 已记录」规则。缺少的只是插件本身。 + +## 决策 + +该守卫是一个循环卫生插件,而非面向模型的工具。它统计对同一工具以相同规范化参数发起的连续调用次数,并在配置的阈值处注入建议性提醒。它从不延迟、阻止或改写调用;模型自行决定是换种方式重试还是结束。 + +插件为 `@deepseek-ai/dsh-repeat-tool-guard`,位于 `packages/guard/repeat-tool-guard/`,开辟 `guard/` 分组用于循环卫生插件(单包(package)分组有先例:[todo-write Agent Note](2026-06-29-todo-write-tool.md)发布了 `todo/tool-todo`)。它注册两个监听器,将状态保存在以存活 `Agent` 对象为键的 `WeakMap` 中——工具注册表是上下文级别的单例,其 waterfall(瀑布式事件)交错所有 agent(智能体)的调用(subagent 运行在同一个上下文上),因此按 agent 分键是正确性要求,而非锦上添花;弱对象键还使得纯清理用途的 disposal 监听器不再必要。 + +- **`tools/post-execute`(waterfall)**——唯一的检测点。监听器同时接收 `(exec, result)`,因此计数和提醒投递无需跨事件的 pending map(pi 扩展需要它,仅因为其 `tool_call`/`tool_result` 钩子是分开的事件)。它始终通过 `next()` 委托,当命中阈值时,将提醒前置到下游决策的 `additionalContexts`——这正是[钩子桥接](2026-06-30-hook-bridges.md)已采用的「观察并丰富」姿态,遵守 waterfall 契约。计数放在此处而非 `tools/pre-execute`,因为 post-execute 也会为被拒绝的调用触发(`ToolRegistry.execute` 将 deny 路由到同一条流水线),而模型反复敲击一个被拒绝的调用恰恰是值得打破的循环。 +- **`agent/prompt-submit`(waterfall)**——纯重置钩子:通过 `next()` 委托,清除提交 agent 的链。用户介入改变了上下文;跨越介入的重复不是循环。 + +### 检测语义 + +链的键是 `(tool name, canonical arguments)`;与前一个被追踪调用相同的调用递增该 agent 的连续计数器,不同的被追踪调用将其重置为 1。规范化方式为深度键排序加 `JSON.stringify`:`ToolExecution.arguments` 按构造就是循环中 `JSON.parse` 的输出(或格式错误的参数 JSON 的原始字符串回退,其本身也是可比较的值),因此 pi 原版对 bigint/循环引用/`undefined` 的处理在此没有输入,被有意去除。 + +两条刻意的规则,均记录在[包 README](../../../../packages/guard/repeat-tool-guard/README.md) 中,因为它们是读者否则只能猜测的行为: + +- **未追踪的调用对链透明。** 被 `include`/`exclude` 排除的调用既不递增也不重置计数器,因此 `grep X → todo_write → grep X` 在 `todo_write` 被排除时仍计为两次连续的 `grep X`。这正是排除功能有用的原因——穿插在循环中的簿记工具不得为循环洗白——也是 pi 扩展的(未文档化的)语义,有意保留并明确写下。 +- **没有 agent 的调用被忽略。** 直接调用 `ctx.tools.execute()` 的调用方(测试、非循环消费方)没有可提醒的模型,也没有可作键的存活 agent 对象。 + +### 提醒投递 + +提醒作为独立条目搭载在 `additionalContexts` 上(source 为 `{kind: 'plugin', plugin: 'repeat-tool-guard'}`——依照 `HookContext`,该标签承载语义),绝不替换 `content`:`tool/result` 事件仍是工具自身的审计输出,循环则在步骤结果之后把缓冲的上下文追加为 `context/message`,会话将其渲染为带标签的合成 user 信封,并由派生历史回放。阈值逐级升级:第一个配置阈值获得简短的「你正在重复自己,请分析先前结果」提示;后续各阈值获得详细形式,包含工具、重复计数和规范参数(在头部截断到 `argumentsPreviewChars`,默认 500——循环中的 `write` 级 payload 不得无界地进入下一次请求;链键始终比较完整规范字符串),并说明这些调用没有取得进展。pi 原版把温和文本硬编码为字面计数 3;本守卫以 `thresholds[0]` 为键,修复了移植中的这一 bug。下游钩子桥贡献仍是独立数组条目,因此两个插件都保留各自的 source、信封与元数据。 + +### 配置 + +```yaml +- id: repeat-tool-guard + name: '@deepseek-ai/dsh-repeat-tool-guard' + config: + thresholds: [3, 5, 8] # default; consecutive counts that trigger a reminder + include: [] # tool-name patterns to track; empty ⇒ all tools + exclude: [todo_write] # tool-name patterns transparent to the chain + argumentsPreviewChars: 500 # default; cap on arguments quoted in the detailed reminder +``` + +`thresholds` 在加载时校验,遇到空列表、非整数、小于 2 的值或重复项时抛出异常——配置错误快速失败,取代 pi 原版的静默回退到默认值。`include`/`exclude` 条目支持 `*` 通配符。模式是对调用时实际存在的工具的谓词,而非对注册表条目的引用,因此匹配不到当前已注册工具的条目不是错误——与 `toolOrder` 的引用检查不同,`exclude: [mcp_*]` 在未加载 MCP 工具的部署中也必须保持有效。 + +## 测试 + +- **单元测试:** 使用脚本化适配器的真实循环,覆盖计数与重置规则、未追踪透明性、dispose(资源释放)清理、按 agent 隔离、规范化参数键序、升级、被拒绝的调用、无 agent 执行、通配符转义、无效配置,以及下游阻止或 replacement 决策,达到逐文件 100% 覆盖率。 +- **快照测试:** keyless 的 `repeat-tool-guard` 场景发起五次相同的 `todo_write` 调用,在 ACP 输出和会话日志中固定第三次调用的温和提醒与第五次调用的详细提醒。该插件在实时示例中加载,但在其他场景中保持静默。 +- **E2e 测试:** 无。该插件是确定性的且与提供方无关,其 seam 契约由各自的所有者覆盖。 + +## 曾考虑的替代方案 + +- **将提醒追加到工具结果中**(以替换 `content` 的方式 `accept`——pi 扩展的机制,它修补结果内容是因为那是其 API 提供的唯一通道):否决。这会让已记录的 `tool/result` 对工具实际返回的内容撒谎,而 `additionalContexts` 是 post-execute 评注的独立认可通道,循环级缓冲保持了调用/结果的邻接关系。 +- **在 `tools/pre-execute` 中计数并使用 pending-reminder map**(pi 的两阶段形态):否决。post-execute 单独就能同时看到 `(exec, result)` 且也为被拒绝的调用触发,因此一个监听器、无跨事件状态即可以更少的机制覆盖严格更多的尝试。 +- **在最高阈值升级为 `block`**:在初始范围内否决。阻止调用会惩罚合法的相同重复(轮询长时间运行的终端、重新检查 agent 预期会变化的文件),而建议性提醒让模型保持控制权。待有证据后重新审视;决策形状(`PostToolDecision`)已支持此选项。 +- **通过 CC/Codex 桥接的逐部署外部钩子**(一个 `PostToolUse` 脚本):否决作为最终答案。它对单个部署有效,但一个已发布、有单元测试、可通过 `cordis.yml` 配置的插件才是 harness 原生的形式,且没有逐调用的子进程开销。 +- **在 `agent-loop` 中设置循环级步骤或重复预算**:否决。「用插件,不改循环」;硬性步骤预算是一种更粗粒度的正交控制,需要自己的提案。 +- **模糊/近似相同检测**(路径归一化、相似但不完全相同的参数):否决。规范化后的精确匹配成本低、确定性强、且可向模型解释;相似度阈值引入误报风险,需要证据才能换取复杂度。 +- **将包放在 `core/`**:否决。core 是产品主干;行为守卫是可选的叶子插件,`todo/` 的先例是每个插件族一个小型专属分组。 + +## 后果 + +- 提醒在设计上是建议性的:有意重复相同调用的幂等轮询模式仍会在超过阈值后收到提示,减压阀是配置(`thresholds`、`exclude`)加上明确允许「在已收集足够证据时结束」的提醒文本。每次触发在下一次请求中增加提醒 token 的开销;阈值限制了触发频率。 +- 链状态仅存于内存:从持久化恢复的会话以全新的链开始,因此跨越恢复的循环比实时循环更晚收到提醒——可以接受,守卫是启发式提示而非已记录的不变式,持久化计数器状态带来的收益不值得其复杂度。 +- 当多个 post-execute 生产者在同一次调用上附加上下文时,每项贡献保持为独立的 `HookContext`;顺序遵循 waterfall 嵌套关系,每个条目保留自己的溯源信息。 +- 实现快照层时暴露了 suite kit 的一项隐藏假设:fixture guard 把「撰写的模型场景」等同于「由 override 驱动」。`Scenario` 表现在携带显式的 `overridden` 标志,并且 sidecar 是否存在会以双向方式与其核对(未注册的游离 sidecar 会静默替换派生脚本)——suite kit 比本插件出现前更严格。 + +## 延后事项 + +- 压缩(compaction)不重置链:压缩后的历史改变了模型所见的内容,但重复风险通常在压缩后仍然存在。 +- 在高阈值升级为 `block` 未实现;`PostToolDecision` 已支持此选项,待证据到来时启用。 +- subagent 的链按 agent 隔离;在出现具体用例之前不提供共享机制。 diff --git a/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.i18n.yaml b/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.i18n.yaml new file mode 100644 index 0000000000..f91e3b5d42 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-08-self-referential-cordis-toolset.md: 80bffa3a2a959939f18fd1d3422607cf61895fc7 +2026-07-08-self-referential-cordis-toolset.zh.md: 2ec79037045fdb040cccf31699789abdd3a12db2 diff --git a/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md b/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md index 429102aeee..80bffa3a2a 100644 --- a/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md +++ b/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-08-self-referential-cordis-toolset.zh.md) + ## Problem Everything in this harness is a cordis plugin, but the agent running inside that plugin runtime cannot see or touch it: it cannot enumerate the services and events around it, cannot extend itself with a new tool mid-session, and cannot compose capabilities it invents. Handing the model that power is worth exploring — a self-referential agent that inspects and modifies its own runtime — but it raises three correctness problems at once, and the design is about answering them rather than the raw "let the model run code" mechanic. diff --git a/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.zh.md b/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.zh.md new file mode 100644 index 0000000000..2ec7903704 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.zh.md @@ -0,0 +1,82 @@ +# Agent Note: 自引用 cordis 工具集 + +Status: implemented + +[English](2026-07-08-self-referential-cordis-toolset.md) | 中文 + +## 问题 + +本 harness 中的一切都是 cordis 插件,但运行在该插件运行时内部的 agent(智能体)既看不到也碰不到它:它无法枚举周围的服务和事件,无法在会话中途为自己添加新工具,也无法组合自己发明的能力。赋予模型这种能力值得探索——一个能审视并修改自身运行时的自引用 agent——但这同时引发三个正确性问题,本设计的核心正是回答这些问题,而非单纯的「让模型执行代码」机制。 + +第一,模型编写的注册必须在注册发生时就完成校验:格式错误的工具 schema 必须在注册时失败,而不是等到后续请求尝试将其组装进提示词时才报错。第二,模型编写的代码需要调用它从未见过源码的服务 API——靠猜测方法签名、更糟糕的是猜测返回值结构,会消耗大量盲目试探的步骤。第三,模型挂载的一切都必须完全可释放:模型可以按需释放,普通的插件生命周期在宿主插件重载时也会释放,否则长会话会积累遗留的监听器和工具。 + +## 决策 + +该工具集以 [`@deepseek-ai/dsh-tool-cordis`](../../../../packages/cordis/tool-cordis/README.md) 发布——一个新的顶层 `packages/cordis/` 分组——并由 [`examples/cordis-agent`](../../../../examples/cordis-agent/README.md) 演示。它为模型提供三个工具,操作模型自身运行其中的活跃 cordis 运行时:审视它、将模型编写的插件挂载进去、再将其释放。 + +vm 隔离了意外的全局污染,上下文门面隐藏了框架内部细节。但二者都不限制已暴露服务的权限:一个挂载可以调用 `ctx.bash` 以宿主执行器的权限运行命令,也能访问真实的文件系统和网络服务。这是一个需要显式启用的开发工具,信任等级与 bash 相当,不是安全边界,也不是产品默认配置。 + +### 三个工具 + +| 工具 | 契约 | +|---|---| +| `cordis_inspect` | 对活跃运行时的只读报告,每个 `what` 值对应一个 Markdown 段落(省略 `what` 则输出全部段落)。精确的 `name` 搭配 `what: "api"` 或 `what: "events"` 可收窄到一个带源码文档的目标。从不产生变更。 | +| `cordis_mount` | 在 `node:vm` 沙箱中执行 `code`(一个异步 JavaScript 函数的函数体);代码必须 `return` 一个 cordis 插件,该插件作为 `cordis-dynamic` 分组 fiber 的子节点挂载,并以一个新 id(`dyn-1`、`dyn-2`……)跟踪。 | +| `cordis_unmount` | 按 id 释放一个动态挂载,并等到释放达到完全停稳后才返回——该插件所做的每一项注册都被撤销,而不仅仅是请求停止。 | + +`cordis_inspect` 的段落:`services`(每个已提供的 ctx 服务及其所属 fiber,非活跃的所有者会被标记)、`plugins`(来自 `ctx.registry` 的所有已加载插件的扁平列表及其生命周期状态——展示加载了哪些能力,刻意不展示树形结构)、`tools`(模型可调用的工具)、`dynamic`(挂载表:id、名称、状态、提供的服务、等待的服务)、`api`(来自生成目录的活跃服务签名及其引用的类型形状)和 `events`(harness 事件及其分发模式和签名)。宽泛的 `api` 和 `events` 报告省略完整 JSDoc 以保持紧凑;精确 `name` 会返回一个服务或事件,以及其原始方法/声明 JSDoc。其他段落不能搭配 name,未知目标会失败,而 API 目标必须处于活跃状态。面向模型的工具描述携带了模型在调用时所需的操作规则;[生成的工具目录](../../../../docs/tool-catalog.md)是其完整呈现。 + +### 沙箱语义 + +挂载代码以异步函数体的形式在一个新的 vm realm 中运行。其文档化的接口面将文件、网络、进程和定时器访问引导至 Cordis 服务,使挂载保持可审视和可释放。宿主 realm 的辅助手段仍然使 Node 逃逸成为可能,这与信任姿态一致。`vmTimeoutMs` 仅约束同步执行部分。 + +沙箱全局变量刻意精简:一个带标签的直写 `console`(在宿主 stdout/stderr 上输出 `[cordis:<id>] …`,这样在挂载调用之后很久才触发的监听器输出仍能落到用户可见的地方)、`harness.defineTool` / `harness.registerTool` 注册对、新 vm 上下文缺少的编码原语(`btoa`/`atob` 作为基于 `Buffer` 的宿主闭包——这是一个经过审批的例外,`Buffer` 本身从不暴露——加上 `TextEncoder`/`TextDecoder`),以及对被扣留的 Node API 的可调用陷阱(`require`、`setTimeout`/`setInterval`/`setImmediate`/`clearTimeout`/`clearInterval`、`fetch`),这些陷阱会抛出一条重定向消息指明 cordis 替代方案。只有函数形态的全局变量才设陷阱;`process` 和 `Buffer` 保持 `undefined`,这样 `typeof` 特性探测保持惰性而不会引爆一个抛异常的访问器。 + +挂载代码通过三道控制跨越 vm 边界。双 realm `instanceof` 同时识别宿主和 vm 对象。`harness.defineTool` 在宿主 realm 中重建输出 schema/投影器,将工具体返回值快照为宿主自有的 JSON,并让注册表在观测前强制执行[规范工具输出契约](../architecture/2026-07-20-canonical-tool-output-contract.md)。挂载的插件接收的是一个白名单上下文门面,而非原始或透传的 `Context`;框架管道和以 context 为值的返回会被拒绝。服务读取需要声明 `inject`,保留 Cordis 的激活与卸载语义。`ctx.tools.get` 仅暴露 schema 视图,因此挂载代码无法绕过 `ToolRegistry.execute` 直接调用定义。 + +边界将无歧义的 JSON-Schema 形式规范化为 `ParameterSchemaSpec`,同时保留 `integer`、原始对象开放性和 required 数组。直接使用 DSL 的对象节点必须声明 `additionalProperties`;无效词汇会报错并给出可接受的替代方案。解析错误、TypeScript 错误、缺少 return、Node API 误用和重复工具名等错误信息包含相关源码行或纠正性契约,不叙述实现内部细节。 + +### 动态分组与挂载生命周期 + +所有动态挂载都是工具插件下方 `cordis-dynamic` 分组的子节点,因此普通的 fiber 释放即可处理重载和卸载。挂载会等待 settlement;启动失败时在返回错误前释放 fiber。已 settle 但处于 pending 状态的挂载仍然可见,并列出其缺失的注入。`cordis_unmount` 等待挂载 fiber 的释放完成。 + +### 通过 provide/inject 实现跨挂载组合 + +挂载之间通过普通的 cordis 服务语义相互关联,以各自的 id 作为生命周期句柄:挂载 A 调用 `ctx.provide('foo', value)`,挂载 B 声明 `inject: ['foo']` 并在 `foo` 存在的瞬间激活;如果 B 先挂载,它保持 pending 状态并列出缺失的服务;卸载 A 使 B 回到 pending(其注册被撤销),之后重新 provide 会通过一个新的沙箱门面重新运行 B 的 `apply`;重复 provide 会明确报错并指出拥有该服务的 fiber。一个 realm 注意事项:由挂载 provide 的服务值是 vm realm 对象——从任何地方调用其方法都能工作,但消费方不得假设它具有宿主原型。 + +### 生成的 API 目录 + +`cordis_inspect` 从生成的目录提供 API 和事件数据,而非维护一份重复的表格。生成器复用 Cordis 目录的 AST 扫描,输出服务摘要、签名、原始服务方法与事件 JSDoc、事件模式、引用的类型声明以及继承的上下文接口面。有歧义的类型名被省略,过大的声明被标记为截断。 + +新鲜度像所有生成产物一样受门禁约束:`pnpm run verify-cordis-api`(在 `doc-sync` 中)在内存中重新生成并在有任何 diff 时失败,因此 JSDoc 或公开签名变更如果不重新生成模型读取的目录就无法合入。运行时 inspect 工具将目录与活跃运行时取交集而非直接转储:宽泛报告把有目录条目的活跃服务渲染为摘要 + 签名,把没有目录条目的活跃服务(挂载提供的)渲染为名称 + 所属 fiber,简要列出有目录条目但无活跃提供方的服务,再附上引用的类型形状。精确名称报告渲染一个活跃服务或事件,并把原始 JSDoc 紧靠在每个签名之前;让该细节按需出现,避免探索性列表承担其 token 成本。 + +### 配置、渲染与可观测性 + +该插件暴露一个配置字段,由 schemastery 校验并记录在[配置目录](../../../../docs/config-catalog.md)中:`vmTimeoutMs`(默认 5000),挂载代码同步执行部分的毫秒上限。工具名、`cordis-dynamic` 分组名和 `dyn-` id 前缀是结构性词汇,保持固定。三个工具均按[工具实操手册](../../../../docs/cookbook/adding-a-tool.md)渲染为 `generic` 卡片(`cordis_inspect` 为 `read`,`cordis_mount` 为 `execute` 并将代码作为 `rawInput` 携带,`cordis_unmount` 为 `delete`),不覆盖 `presentResult`。 + +「模型可见 ⟺ 已记录」成立,且无需新的会话事件类型:挂载或卸载仅通过其自身的 `tool/call` / `tool/result` 对可见(循环会记录它们),而挂载引起的工具集变化由循环在 schema 在步骤间发生变化时发出的完整变更 request header 记录。刻意不设 `cordis/mount` 溯源事件——它只会重复工具调用对已记录的内容。动态挂载是进程生命周期的,不是会话状态:恢复一个持久化的会话会重建对话,但不会重新挂载插件。 + +## 曾考虑的替代方案 + +**用结构化的逐能力注册工具替代 `cordis_mount`。** 最具吸引力的替代方案是一个带有显式 `name` / `description` / `parameters` / `code` 字段的 `cordis_register_tool`(以及兄弟工具 `cordis_register_listener`、`cordis_register_service`……),而非单一的「挂载一个插件」原语。否决原因:它唯一的真正优势——对最常见的单一场景免去插件样板代码——不足以抵偿其代价,而单一的 mount 原语能一次性覆盖所有能力。 + +| 维度 | 结构化逐能力工具 | 单一 `cordis_mount` | +|---|---|---| +| Schema 正确性 | `parameters` 仍然是模型编写的 JSON,需要统一 schema 校验,只是提前了一步 | 同样的校验在沙箱边界运行,同样的指导性错误信息 | +| 代码字段 | `execute` 函数体仍然是 vm 中模型编写的 JS;realm 和服务调用的正确性问题不变 | 一个沙箱、一条规范化路径、一处受保护的注册 | +| 能力覆盖面 | 仅限工具;监听器、服务、`inject` 关系各需另一个结构化工具——接口面无限增长 | 一套词汇(cordis 插件)覆盖当前和未来的所有效果 | +| 跨挂载组合 | 在工具注册载荷中无法表达 | 原生 `provide`/`inject`,普通的 cordis 语义 | +| 可审视性 | 注册的东西无法在插件列表中显示为插件 | 模型挂载的正是 `cordis_inspect` 渲染的 | +| 模型易用性 | 对最常见的单一场景有优势(无插件样板) | 通过 mount 描述中的规范示例加边界错误信息教会正确调用来缓解 | + +因此正确性投入放在能一次性为所有能力带来回报的地方:通过 `cordis_inspect` 呈现的生成 API 目录,以及沙箱边界校验(其错误信息教会正确的调用方式)。结构化注册工具日后仍可作为语法糖添加,由它合成 mount 代码;本设计不排斥这一可能。 + +**在工具中手工维护服务/事件参考。** inspect 工具的第一版携带了一份手写的服务方法签名表。它被生成的 `api-catalog.ts` 取代,因为手写表在签名变化的瞬间就会与 JSDoc 脱节且没有门禁约束这种漂移,而生成产物的新鲜度由文档使用的同一套 AST 检查。 + +**新增 `cordis/mount` 会话事件。** 一个持久的溯源事件记录每次挂载(源码、名称)有明确先例(`hook/invoked`、`compact/start`)。v1 中予以否决:挂载和卸载已经作为 `tool/call` / `tool/result` 对可见,工具集变化已经作为完整的变更 request header 被记录,因此专用事件只会重复记录。如果审计用例需要将挂载溯源从工具调用中分离出来,日后仍可添加。 + +**加固的/能力受限的沙箱。** 对 Node 内置模块设陷阱并向挂载代码提供白名单门面而非原始上下文,可能暗示意图是为安全而沙箱化。这里明确不是:陷阱和门面收窄的是挂载代码所见的*接口面*——将其引导至 cordis 服务、远离易泄漏的 Node 内置模块和框架内部——目的是正确性和封堵未受保护的上下文逃逸,但门面暴露的能力(`ctx.bash`、`ctx.fs`、`ctx.web`)触及真实运行时,因此它不是安全边界。真正的安全边界(独立进程、权限提示)超出了一个开发/显式启用工具集的范围,且会与其核心目的——将活跃运行时交给模型——相冲突。 + +## 后果 + +该工具集是刻意的显式启用设计,具有完全特权的 `ctx`,因此部署方采用它的意识程度应与 bash 工具相当。以下几个事实由工具描述直接告知模型:一个 waterfall(瀑布式事件)监听器(如 `tools/pre-execute`)如果不调用 `next()` 就返回,会否决整条链,因此一个挂载的监听器可以瘫痪 agent 自身的工具分发([waterfall 语义](../../../../docs/cordis-primer.md#cordis-waterfall-semantics));挂载代码在当前轮次的工具调用内运行,因此 await 任何只在该轮次结束后才 resolve 的东西会导致死锁;`vmTimeoutMs` 仅约束同步执行;挂载不会在会话恢复后存活。 diff --git a/.agents/notes/implemented/feature/2026-07-10-session-query-service.i18n.yaml b/.agents/notes/implemented/feature/2026-07-10-session-query-service.i18n.yaml new file mode 100644 index 0000000000..f19f20eb9e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-10-session-query-service.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-10-session-query-service.md: 722f6bf6163278719c3bbb598ed2a2a9d042fb8e +2026-07-10-session-query-service.zh.md: ae6fcb78e18afe83784560c493ea93b7ee0bd68c diff --git a/.agents/notes/implemented/feature/2026-07-10-session-query-service.md b/.agents/notes/implemented/feature/2026-07-10-session-query-service.md index 8cc529377b..722f6bf616 100644 --- a/.agents/notes/implemented/feature/2026-07-10-session-query-service.md +++ b/.agents/notes/implemented/feature/2026-07-10-session-query-service.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-10-session-query-service.zh.md) + ## Problem Session history exists in two places: current `SessionStore` objects and an optional persistence backend. Consumers that need exact inspection would otherwise duplicate live-versus-persisted precedence, persistence lifecycle handling, raw-event surface classification, relationship tracing, and defensive cloning. Durable state can lag the live log between checkpoints, so persistence alone is not a truthful current source. diff --git a/.agents/notes/implemented/feature/2026-07-10-session-query-service.zh.md b/.agents/notes/implemented/feature/2026-07-10-session-query-service.zh.md new file mode 100644 index 0000000000..ae6fcb78e1 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-10-session-query-service.zh.md @@ -0,0 +1,42 @@ +# Agent Note: 精确会话查询服务 + +Status: implemented + +[English](2026-07-10-session-query-service.md) | 中文 + +## 问题 + +会话历史存在于两处:当前的 `SessionStore` 对象与可选的持久化后端。需要精确检查的消费方若无统一服务,就不得不各自重复实现活跃/持久化优先级判定、持久化生命周期处理、原始事件的 surface 分类、关系追踪以及防御性克隆。在检查点之间,持久化状态可能落后于活跃日志,因此仅靠持久化并非当前状态的可靠来源。 + +全文搜索与此相关,但规模大得多。将提供方协调、同步、失效、排序和游标状态放入精确读取服务,会在具体数据库拥有方旁边再创建一个状态机。 + +## 决策 + +`@deepseek-ai/dsh-session-query` 拥有面向单一逻辑语料库的唯一抽象 `ctx.sessionQuery` 服务。它具体实现 `listSessions()`、提供方无关的 `filterSessions(filters)`、`listEvents(sessionId)`、`filterEvents(sessionId, filters)`、有界的 `readEvent(request)`、`traceSession(sessionId)` 和 `traceEvent(request)`,而具体后端实现其两个全文搜索方法。[统一服务决策](../architecture/2026-07-23-unified-session-query-service.md)拥有这一拓扑,[SQLite 搜索决策](2026-07-10-sqlite-session-query-provider.md)拥有搜索行为,[追踪决策](2026-07-13-session-query-tracing.md)拥有血缘与事件关系语义。 + +该服务动态观察可选的 `ctx.sessionPersistence` 绑定,但不保留持久化缓存或失效监听器。每次跨语料库列表操作向活跃后端请求权威元数据,然后叠加一份新鲜的活跃 store 列表。id 匹配的条目合并为一条 `SessionRecord`:活跃 header 优先,`live`/`persisted` 各自独立报告来源可用性。不可变 header 不一致时产生 `SESSION_QUERY_SOURCE_CONFLICT`。 + +精确目标读取首先检查活跃 store,快照活跃 header 与事件日志。此路径从不查询持久化,因此持久化后端故障不会导致已知的活跃历史不可读。若活跃 store 中无目标,服务列出当前持久化元数据、证明该 id 存在、加载它,并在列表/加载 header 不一致时拒绝。所有返回的 header 与事件都经过一次 structured-clone 边界。 + +## Surface 语义 + +`dsh-session` 导出 `foldSurface(events)`,`SurfaceManager` 使用相同的转换函数维护其增量缓存。fold 返回分离的当前事件 seq 以及每次替换实际移除的 seq。`listEvents()` 和 `traceEvent()` 利用该结果为每个原始事件分类,使检查结果不会在位置替换语义上与 model-history 推导产生分歧。 + +`readEvent()` 返回完整的目标加上按连续 seq 排列的原始相邻事件。`before` 和 `after` 默认为零,各自受 `readWindowMax`(默认 50)约束。结果携带克隆的 `SessionHeader` 而非来源可用性记录,因为判断活跃目标的 persisted 标志会违反「活跃精确读取不依赖持久化健康状态」这一保证。 + +## 安全边界 + +该服务是上下文级别的受信任基础设施,而非授权层。未来面向模型的历史工具或人类 UI 将施加显式的调用方/会话范围。该服务不添加面向模型的工具,也不改变 transcript(文本记录)或快照的 surface。 + +## 曾考虑的替代方案 + +- **将逻辑语料库解析直接放在每个消费方中**:否决。来源优先级、冲突处理、可选服务生命周期、克隆与 surface 分类是共享的正确性规则。 +- **仅查询持久化**:否决。检查点可能落后于当前活跃日志。 +- **缓存持久化元数据并监听写入/删除**:否决。精确读取可以直接询问权威来源,而缓存失效在规模尚未要求时就引入了生命周期与并发状态。 +- **将提供方注册放入精确读取服务**:否决。SQLite 包拥有一套对账/事务生命周期;若没有第二个提供方证明其必要性,注册表只会拆分该状态。 + +## 后果 + +继承的精确读取实现只有一个来源解析状态变量:当前挂载的持久化服务。它没有提供方队列、指纹、提取器注册表、观察代次或派生索引更新;具体后端单独拥有其全文搜索状态。精确读取、语义扫描和事件追踪在纯活跃部署中仍然可用,在持久化存在时具有确定性。 + +跨语料库列表、血缘追踪和持久化事件操作在每次调用时执行后端 I/O。这是有意为之:正确性来自当前权威状态,而面向规模的全文搜索方法使用具体后端的 SQLite 派生索引。 diff --git a/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.i18n.yaml b/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.i18n.yaml new file mode 100644 index 0000000000..d4b48d4f41 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-10-sqlite-session-query-provider.md: 98618a7eb572ce59c5fa5984675c9dc57b3f4289 +2026-07-10-sqlite-session-query-provider.zh.md: bb3650da907cf86a853f748fa0ee40d5c2168709 diff --git a/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.md b/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.md index 7306ee6bd9..98618a7eb5 100644 --- a/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.md +++ b/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-10-sqlite-session-query-provider.zh.md) + ## Problem The exact-read `ctx.sessionQuery` service deliberately has no derived index. Large persisted histories need full-text search without scanning every event on every query, while current live sessions need an overlay newer than the last durability checkpoint. Search also needs concrete ranking, snippets, filters, pagination, cancellation, and rebuild behavior. @@ -36,7 +38,7 @@ One serialized operation reads the provider-neutral `SessionPersistence` snapsho Persisted documents survive restarts. Live sessions use connection-local TEMP tables, shadow the persisted base for the same id, and reveal that base on detach. Closing the database drops live rows. Unmounting persistence hides durable rows without treating absence as authoritative deletion; remounting observes and reconciles the backend again. Conflicting immutable live and durable headers fail rather than combining sources. -The derived schema has its own application id and monotonic schema version. A recognized incompatible version resets only this derived database. A database with a foreign application id or unrecognized user tables is refused before journal-mode mutation, which prevents an accidentally configured canonical session database from being changed. On POSIX filesystems, missing directories and database files are created owner-only so new SQLite sidecars inherit that mode; existing modes are preserved. One service in one process exclusively owns a derived-index path; cross-process writers are unsupported because generations and live TEMP shadow state are connection-owned. +The derived schema has its own application id and monotonic schema version. Persistent and TEMP session metadata store the integer `SessionHeader.createdAt` contract in strict `INTEGER` columns. A recognized incompatible version resets only this derived database. A database with a foreign application id or unrecognized user tables is refused before journal-mode mutation, which prevents an accidentally configured canonical session database from being changed. On POSIX filesystems, missing directories and database files are created owner-only so new SQLite sidecars inherit that mode; existing modes are preserved. One service in one process exclusively owns a derived-index path; cross-process writers are unsupported because generations and live TEMP shadow state are connection-owned. Cancellation rejects queued operations promptly. Once asynchronous source observation starts, the caller waits for that backend promise to settle before rejection, without committing an aborted observation or starting more source/index work. Node's synchronous `DatabaseSync` metadata and MATCH calls cannot be interrupted once executing on the JavaScript thread, so the service checks the signal around those calls but does not promise mid-statement preemption. diff --git a/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.zh.md b/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.zh.md new file mode 100644 index 0000000000..bb3650da90 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.zh.md @@ -0,0 +1,59 @@ +# Agent Note: SQLite FTS5 会话搜索 + +Status: implemented + +[English](2026-07-10-sqlite-session-query-provider.md) | 中文 + +## 问题 + +精确读取的 `ctx.sessionQuery` 服务有意不维护派生索引。大规模持久化的历史记录需要全文搜索,而不是每次查询都扫描全部事件;当前的活跃会话则需要一个比上一次持久性检查点更新的覆盖层。搜索还需要具体的排序、摘要片段、过滤器、分页、取消以及重建行为。 + +如果把这些关注点拆分到提供方协调器和数据库实现之间,就会产生两个耦合的对齐状态机。第一个实现既要暴露精简的提供方无关调用契约,也要在同一个生命周期内管理源观察、提取、SQLite 事务、代际与查询执行。 + +## 决策 + +`@deepseek-ai/dsh-session-query` 声明一个抽象的 `ctx.sessionQuery` 服务,其精确读取、过滤与追踪均有具体实现,仅有两项全文方法为抽象方法。`searchSessions(request, exec?)` 返回按游标分页的 `SessionSearchHit`,并按每个会话中匹配度最强的事件分组;`searchEvents(request, exec?)` 返回一个逻辑会话内的 `SessionEventSearchHit`。两种请求都必须提供 `query`,可以接受 `limit` 和由服务拥有的品牌化 `SessionSearchCursor`,并支持可选的中止信号。会话搜索接受 `sessionFilters` 与事件元数据过滤器,事件搜索接受事件元数据过滤器。结果会公开有界的纯文本摘要片段,但不公开提供方标识符或数值相关性分数。单一键拓扑由[统一服务决策](../architecture/2026-07-23-unified-session-query-service.md)定义。 + +`@deepseek-ai/dsh-session-query-sqlite` 扩展接口服务,并且是 `ctx.sessionQuery` 唯一的具体所有者。它依赖实时的 `ctx.sessions`,动态观察可选的 `ctx.sessionPersistence`,并拥有一个专用的派生 SQLite 数据库。系统没有搜索提供方注册表、协调器、持久化事件或 agent loop(智能体循环)集成。 + +接口包还拥有共享的第一方语义提取与提供方无关的过滤。`SessionResultFilter` 涵盖 id、可空的 cwd、创建时间范围、可空的父会话与可用性;`ctx.sessionQuery.filterSessions()` 无需 FTS 提供方即可应用这些过滤器。`SessionEventResultFilter` 涵盖 seq/时间范围、事件类型、surface 与字面语义文本。过滤器数组内各项按逻辑与(AND)组合,列表值按逻辑或(OR)组合。文本子句会将调用方输入转义为不区分大小写的 Unicode 正则表达式,其中每段连续空白都匹配一个或多个空白字符;该子句通过 `ctx.sessionQuery.filterEvents()` 提供,不会委托给 FTS 提供方。 + +## 搜索语义 + +每个语义事件对应一份 FTS 文档,其中携带会话元数据、事件元数据、surface 分类与提取文本。除非 surface 过滤器缩小范围,否则所有 `current`、`shadowed` 与 `log-only` 文档都会参与搜索。元数据过滤器在排序前编译为参数化 SQL。会话结果按会话划分匹配文档,并保留匹配度最强的文档。 + +排序在持久化 FTS 表与 TEMP FTS 表之间具有确定性和可比性:先按实际 FTS5 高亮匹配区段数量降序,再按已索引文档的码点长度升序、事件时间降序、跨会话范围内的会话 id 升序,最后按 seq 降序排列。摘要片段使用这些实际高亮位置,移除保留标记、规范化空白,并按 Unicode 码点限制长度。不透明游标会绑定到服务实例、范围、规范化后的标准请求、偏移量与相关代际。语料库发生任何变更都会使跨会话游标失效;会话内游标仅在其目标源或代际发生变化时失效,因此不相关的会话不会使其失效。重新打开服务会创建新的服务实例,并使旧游标失效。 + +查询会先去除首尾空白并规范化内部空白,再作为一个字面 FTS5 短语整体加引号。嵌入的引号在绑定前写成两个,因此 `OR`、`NEAR`、引号、括号与 `*` 等 MATCH 运算符会作为数据,而不是可执行的查询语法。系统会在 SQLite 执行前拒绝 NUL。文档中的保留高亮非字符与 NUL 会在索引前规范化,因此插入的呈现标记不会与源文本冲突。短语匹配遵循分词器 token,而不是任意子串。 + +## 分词器选择 + +持久化 FTS5 表与实时 FTS5 表都使用 `unicode61`。实现实验表明,该分词器支持由两个字符组成的 token `AI`,生成的索引体积约为 trigram 方案的 1/2.1。系统接受的限制是 token/短语召回:`AI` 不会匹配较长的 token `BRAID`,任意子串搜索改用提供方无关的文本扫描。 + +## 提取与对齐 + +共享提取器会提取消息文本、推理(reasoning)、嵌套的工具调用/结果内容、工具名称与参数、被阻止提示词的原因、待办事项状态与内容,以及错误或结束状态详情。结构性边界、流式分片、请求头、成功完成标记,以及通过声明合并扩展的未知事件/内容变体都不会产生文档。surface 分类复用 `foldSurface()`,使搜索与模型历史派生保持一致。 + +一个串行化操作会读取提供方无关的 `SessionPersistence` 快照清单,将每个包含源身份的不透明修订号与同已索引会话一并存储的修订号比较,只加载新增或变更的日志,在一个事务中对齐各行,然后执行查询。它绝不会调用后端会修改状态的 `load()` 来处理当前由 `ctx.sessions` 拥有的 id;TEMP 覆盖层会记录持久化可用性,实时所有者分离后,持久化基础层随之刷新。修订号同时标识其底层持久化存储与后端本地日志修订版本,因此针对同一存储重新打开服务可以复用已索引行,而切换到独立存储时不会因会话 id 与本地计数器相同而发生冲突。如果加载期间清单发生变化,系统会重复观察;因此,会修改状态的加载修复所产生的新修订号会在提交前纳入结果。重复查询与针对未变更存储的重新打开都不会加载完整的持久化日志。新增、变更与删除的会话会在下一次稳定搜索中更新。源或提取失败不能将某一行标记为当前状态,事务失败则会回滚,使后续搜索能够重试。 + +持久化文档在重启后仍然存在。实时会话使用连接本地的 TEMP 表,遮蔽相同 id 的持久化基础行,并在实时所有者分离时重新显露该基础行。关闭数据库会删除实时行。卸载持久化服务会隐藏持久化行,但不会把缺失视为权威删除;重新挂载后,系统会再次观察并对齐后端。实时会话头与持久化会话头的不可变字段发生冲突时,系统会失败,而不会合并两个来源。 + +派生 schema 拥有独立的 application id 与单调递增的 schema 版本。持久化与 TEMP 会话元数据均遵循 `SessionHeader.createdAt` 的整数契约,将其存入严格的 `INTEGER` 列。系统识别到不兼容版本时,只会重置该派生数据库。如果数据库具有不属于本应用的 application id 或无法识别的用户表,系统会在修改日志模式前拒绝该数据库,防止意外配置的规范会话数据库遭到修改。在 POSIX 文件系统上,缺失的目录与数据库文件会以仅所有者可访问的权限创建,使新的 SQLite 伴随文件沿用该模式;现有权限模式保持不变。一个进程中的一个服务独占一条派生索引路径;代际与实时 TEMP 遮蔽状态都归连接所有,因此不支持跨进程写入方。 + +取消会拒绝排队中的操作,并终止调用方对异步源观察的等待;已经中止的观察结果不会提交。Node 的同步 `DatabaseSync` MATCH 调用一旦开始在 JavaScript 线程上执行就无法中断,因此服务会在串行化边界检查信号,但不承诺在语句执行期间抢占。 + +## 曾考虑的替代方案 + +- **将 FTS 表添加到规范持久化数据库**:不予采纳,因为可重建索引不应与权威日志共享 schema、重置或故障边界。 +- **添加第一阶段的提供方注册表与协调器**:不予采纳,因为单一实现无法证明注册语义,并且会将一个对齐生命周期拆给两个所有者。 +- **立即持久化实时覆盖层**:不予采纳,因为在现有检查点提交前,实时事件并非规范数据。 +- **使用 FTS5 trigram 分词器**:不予采纳,因为它会遗漏短于三个字符的有用查询,并且测得的索引体积约为 `unicode61` 的 2.1 倍;扫描路径仍可提供字面子串过滤。 +- **在每个表中独立使用 FTS5 BM25**:不予采纳,因为填充内容不同的持久化语料库与 TEMP 语料库所产生的分数不可比较;实际匹配区段与文档长度采用同一套尺度。 + +## 后果 + +搜索只公开精简的提供方无关 API,而唯一后端负责派生索引的全部状态转换。独立数据库增加了配置与查询前的轻量快照读取,但索引损坏、重置与分词器变更都不会危及规范日志。持久化修订号使未变更会话无需读取或重写完整日志;TEMP 实时覆盖层保留当前会话事实,同时不会让尚未经过检查点的事件具有持久性。 + +选定的分词器以较小的索引体积支持短 token,但不承诺子串召回。字面短语使查询语法安全且可预测,代价是不支持布尔表达式或完整 MATCH 表达式。取消在操作排队或等待数据源期间有效,但同步 SQLite 执行仍是不可抢占区段。 + +单元测试将以下行为固化为契约:提取、过滤器、两种搜索范围、所有默认 surface、先过滤元数据再排序、摘要片段、字面量转义、确定性平局处理、完整分页、按范围的游标失效、动态挂载/卸载持久化服务、重启对齐、实时遮蔽、显露与重新打开、schema 安全、回滚重试,以及排队中或进行中的数据源等待取消。一个无需密钥的真实 Loader 路径测试会将该包与真实的 SQLite 持久化后端组合使用。 diff --git a/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.i18n.yaml b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.i18n.yaml new file mode 100644 index 0000000000..d7dfbedded --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-12-subagent-persona-tool-filter-and-depth.md: c690f4701a54272205eedf719fbfe0863bac566c +2026-07-12-subagent-persona-tool-filter-and-depth.zh.md: 6e9e9ad44fff4dee6ddb286227485420d100f4ee diff --git a/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md index 0f42a547cf..c690f4701a 100644 --- a/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md +++ b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-12-subagent-persona-tool-filter-and-depth.zh.md) + ## Problem A reusable subagent provider answers how to run a child, but different delegation tools need different child behavior. One deployment may want a reviewer persona, a research-only tool set, or a hard recursion bound without creating a new provider for every combination. diff --git a/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.zh.md b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.zh.md new file mode 100644 index 0000000000..6e9e9ad44f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.zh.md @@ -0,0 +1,96 @@ +# Agent Note: 配置 subagent 的人设、工具可见性与深度 + +Status: implemented + +[English](2026-07-12-subagent-persona-tool-filter-and-depth.md) | 中文 + +## 问题 + +一个可复用的 subagent 提供方解决的是「如何运行子 agent(智能体)」的问题,但不同的委派工具需要不同的子 agent 行为。某个部署可能需要评审者人设、仅限研究的工具集,或硬性递归上限,而不必为每种组合创建新的提供方。 + +这些控制影响子 agent 的第一次模型请求,因此不能在子 agent 可见之后再安装。它们还需要提供方的诚实支持:ACP(Agent Client Protocol)后端不能默默接受一个仅限进程内的工具过滤器,而过滤器在所有插件运行于同一可信进程的情况下也不应被描述为安全边界。 + +## 决策 + +subagent 启动有三个独立的组合控制:`persona`、`toolFilter` 和 `maxDepth`。提供方声明对每个控制的支持情况,服务在启动运行之前拒绝不受支持的请求,进程内提供方在子 agent 尚未发布时安装所请求的组合。 + +这些控制回答不同的问题: + +| 控制 | 问题 | 结果 | +|---|---|---| +| `persona` | 什么角色指令替换该子 agent 的部署人设? | 一个子 agent 局部的提示词段落遮蔽 `deployment:persona` | +| `toolFilter` | 部署全局工具中哪些进入该子 agent 的可见工具视图? | 一个有作用域的限制在添加子 agent 局部工具之前过滤全局工具 | +| `maxDepth` | 这棵委派树最深可以长到多少层? | 子 agent 深度超过绝对上限时,启动请求被拒绝 | + +`dsh-tool-subagent` 将这些控制作为插件配置暴露,并复制到它创建的每个请求中。直接调用 `SubagentService` 的调用方可以按请求选择这些控制。提供方的能力描述符仍然是后端能否兑现各字段的真源。 + +### 人设是有作用域的遮蔽 + +人设控制改变一个子 agent 的行为,而不改变部署级的提示词组装。在未发布的设置阶段,进程内提供方在子 agent 作用域中注册一个名为 `deployment:persona` 的段落;普通的最具体者优先解析规则仅在该子 agent 的组装中替换全局段落。 + +其值与部署人设具有相同的严格模板语义。省略时通过全局层继承部署段落;显式空字符串则以空段落遮蔽全局人设。父级和兄弟级的人设永远不会进入子 agent 的扁平作用域。 + +这使用的是常规的系统提示词注册机制,而非第二条人设通道。因此第一次提示词看到的命名贡献与后续提示词和提示词检查工具看到的一致。 + +### 工具过滤是一条作用于全局视图的活规则 + +工具过滤同时控制能力可见性和可执行查找。进程内提供方在发布前于子 agent 作用域中安装 `ToolRegistry.restrict()`,注册表的单一解析器对协议格式(wire format)的工具 schema、查找、执行和 Code Mode SDK 生成施加相同的结果。独立注册的系统提示词段落不在 `ToolRegistry` 内,因此过滤一个工具不会移除该插件的独立指导文本。 + +解析遵循以下规则: + +1. 每条限制对活跃的部署全局工具注册表先应用 `allow` 再应用 `deny`。 +2. 多条限制取交集,因此每条已安装的限制都必须放行一个全局工具。 +3. 子 agent 作用域的工具在全局过滤之后添加,可以遮蔽一个已放行的全局工具。 +4. 保留的 `run_code` 呈现和其他作用域局部的协议贡献不受全局过滤器影响。 + +当过滤器既未提供 `allow` 也未提供 `deny`,或命名了当前全局可限制集合之外的内容(包括仅作用域局部或保留名称)时,配置会显式失败。`allow: []` 合法,且有意隐藏所有全局工具。这些检查能捕获拼写错误,并防止配置在无法影响所命名条目时看起来仍然有效。 + +全局注册表保持活跃。仅 deny 的过滤器会放行后来注册的全局名称(除非显式 deny 该名称);allow 列表会排除后来注册的全局名称(除非显式 allow 该名称)。移除一个全局工具会将其从所有已解析视图中移除。这些语义在保持热注册的同时,使 allow 与 deny 的区别显式化。 + +### 深度是绝对的树上限 + +深度限制独立于工具可见性来约束递归委派。顶层 agent 深度为零;进程内子 agent 的深度为其父级已验证深度加一。`maxDepth` 是一个绝对的非负安全整数,当推导出的子 agent 深度大于上限时,启动在子 agent 所有权开始之前即被拒绝。 + +有效父级深度取持久 `SessionHeader.delegationDepth` 与运行时 `AgentOptions.subagentDepth` 中的较大值。进程内子 agent 把推导出的深度记录在会话 header 中,恢复时会重新载入该 header,因此重启无法降低递归计数。 + +每个公开入口都自行验证值域,而非依赖单一的面向模型配置路径。负值、小数、负零、非有限值、不安全整数、格式错误的存储父级深度以及推导溢出均被拒绝。直接的 `SubagentStartRequest` 可以省略上限,让此机制不约束深度;经 Loader 解析的 `dsh-tool-subagent` 配置则默认值为 `3`、接受数值覆盖,并使用显式的 `'provider-managed'` 来省略由进程外提供方部署拥有递归预算时的上限。三是一个较小的有限默认值,仍允许 root 加三代后代:[SDK 辅助函数生成的 subagent 条目](../../../../packages/sdk/helper/src/features/builtin/index.ts)和 [JSON-RPC 示例](../../../../examples/jsonrpc-agent/cordis.yml)采用这项通用策略,而已交付的交互式 ACP、headless 和 REPL 示例固定为一。提供方缺少 `depthLimit` 时,数值工具上限会在提供方挂载阶段失败。 + +部署可以组合深度与过滤,但数值上限不会合成过滤器。委派工具在上限处仍然可见,因为授权可能依赖运行时状态;每次尝试启动都会检查调用方 agent 当前的持久与运行时深度,被拒绝的启动返回错误工具结果,且不发布子 agent。可见性策略固定的部署可以另外在子 agent 中 deny 委派工具。两种选择都不改变提供方的对话历史行为。 + +### 能力门控保持提供方诚实 + +能力将请求的功能与提供方实现分离。`SubagentCapabilities` 声明 `persona`、`toolFilter` 和 `depthLimit`;`SubagentService.start()` 在调用提供方之前,对照这些标志检查请求中每个存在的字段。 + +这使 spawn 和 fork 提供方可以共享进程内实现,而外部提供方只声明自己能强制执行的部分。请求永远不会静默降级:选择不受支持的控制会产生 `UNSUPPORTED_CAPABILITY`,不会有运行或生命周期事件存在。 + +### 未发布设置使第一次请求正确 + +所有子 agent 局部的组合在子 agent 变得可观察之前完成。进程内提供方向 agent 创建提供一个设置回调;该回调在子 agent 作用域中安装人设、工具限制和结构化输出贡献。只有设置成功后,创建才发布会话和 agent 并允许驱动器启动。 + +设置失败会回滚私有子 agent。没有观察者能获取到一个「第一次提示词使用了部署人设或未过滤工具集、后续提示词才使用所请求配置」的子 agent。 + +## 可见性不是授权 + +这些控制组合的是同一可信进程内的行为,而非授权行为。`toolFilter` 改变工具注册表解析出的子 agent 视图,但它不创建父到子的授权格,不要求子 agent 仅持有父级子集授权,不沙箱化插件,也不阻止持有另一个 Cordis 上下文的代码直接调用服务。 + +具体而言,子 agent 局部工具在全局过滤之后添加,可能不在父级视图中。仅 deny 的子 agent 也能看到 deny 列表未命名的后来全局工具。这些是有意的活组合语义,而非不可升权保证。 + +安全设计需要独立的授权表示、传播规则和执行时强制点。创建时的授权快照、父级子集授权、显式的未来授权 API,以及通用的能力/输出/终止标签均不在本功能范围内。 + +## 曾考虑的替代方案 + +**为每种人设或工具集创建一个提供方。** 这会使共享相同传输和生命周期实现的提供方成倍增加,使动态部署配置变得笨拙,且仍需要递归机制。提供方的职责是执行传输;请求承载每个子 agent 的组合。 + +**复制父级的完整工具视图。** 注册作用域设计上是扁平的,生命周期所有权不意味着可见性继承。复制已解析视图还会冻结动态全局注册,并在未完整定义任一契约的情况下混淆组合与授权。 + +**在子 agent 创建时快照允许的全局工具。** 冻结的 allow 集合使未来注册统一不可用,但它改变了热注册语义并开启了授权设计。已实现的过滤器保持为活跃的注册表谓词,并直接记录 allow 与 deny 的行为。 + +**仅隐藏工具 schema。** 仅呈现层的过滤让模型可以通过 Code Mode 或伪造调用执行一个提示词声称不存在的工具。改为由一个解析器同时管控呈现和执行。 + +**把深度上限编码为自动工具过滤器。** 创建时过滤器会快照一个可能依赖运行时状态的决策,只影响一个已配置工具名,且不保护直接服务调用方或替代委派工具。提供方改为在每次启动时强制绝对上限。 + +## 后果 + +贡献者可以配置子 agent 的角色、可见全局工具和递归深度,而无需定义新的提供方。能力检查在所有权开始之前失败,未发布设置使第一次请求一致,单一工具解析器防止呈现/执行漂移。 + +代价是部署方必须理解活跃的 allow/deny 行为以及可见性与授权的区别。当前深度策略禁止再创建子 agent 后,模型仍可能调用可见的委派工具并收到错误。提供方作者必须准确声明每个受支持的控制,进程内提供方必须在发布前安装所有请求的贡献。这些控制有意不解决安全隔离或父到子的不可升权问题。 diff --git a/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.i18n.yaml b/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.i18n.yaml index 1a8c03cb52..ad0592ae57 100644 --- a/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.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 -2026-07-16-harness-level-loop.md: 9a9511b9dcea1b5fdc90f4fc716c4399f2346967 -2026-07-16-harness-level-loop.zh.md: 284e73051eaaa4633b9f56367de9096dadc8184e +2026-07-16-harness-level-loop.md: 15b5ce7e20b7afc429f6ff7b8a4d2d69150c22a0 +2026-07-16-harness-level-loop.zh.md: a3fabe40d36c45c715f613ce8def35faa427d3bd diff --git a/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.md b/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.md index 9a9511b9dc..15b5ce7e20 100644 --- a/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.md +++ b/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.md @@ -39,7 +39,7 @@ Time-based `/loop` or scheduled execution is a third policy and is not implement | `@deepseek-ai/dsh-tool-goal` | `packages/goal/tool-goal/`, model-facing consumer | Registers exclusive `get_goal`, `create_goal`, and `update_goal`; authenticates live turn provenance and narrows autonomous-round authority to completion or blocking reports with machine-routable reason codes. | | `@deepseek-ai/dsh-goal-session` | `packages/goal/goal-session/`, continuation policy | Reserves, fences, admits, attributes, settles, cancels, and quiescently drains same-session goal rounds without importing the concrete loop. | | `@deepseek-ai/dsh-commands` | `packages/ui/commands/`, UI registry | Owns `CommandDefinition`, discovery, scoped registration, direct dispatch, `CommandResult`, and request cancellation for human-only commands. | -| `@deepseek-ai/dsh-command-goal` | `packages/goal/command-goal/`, human-command producer | Registers `/goal` status, creation, edit, pause, resume, and clear over the goal domain for TUI and ACP. | +| `@deepseek-ai/dsh-command-goal` | `packages/goal/command-goal/`, human-command producer | Registers `/goal` status, creation, edit, pause, resume, and clear over the goal domain for TUI. | | `@deepseek-ai/dsh-tool-ralph` | `packages/workflow/tool-ralph/`, fixed workflow consumer | Registers `ralph({ objective, maxRounds? })`, validates the fresh structured provider and bounded `RalphRoundReport`, and returns `complete`, `blocked`, or `budget-limited`. | The detailed contracts live in the [goal-domain](2026-07-19-persisted-same-session-goal-domain.md), [model goal-tools](2026-07-19-model-facing-goal-tools.md), [goal-round driver](2026-07-19-same-session-goal-round-driver.md), [command registry](2026-07-19-plugin-command-registration.md), [human goal-command](2026-07-19-human-goal-command.md), and [Ralph workflow-tool](2026-07-19-fresh-agent-ralph-workflow-tool.md) Agent Notes. @@ -70,7 +70,7 @@ The human UX follows the compact Codex shape in the [public OpenAI Codex TUI dis The model receives only `get_goal`, `create_goal`, and `update_goal`. It may create a goal when a direct human request clearly asks for substantial multi-round work, and it may infer that intent in any language. It must not turn routine one-turn work into a goal. Direct-human provenance is enforced in code; semantic interpretation remains model judgment. An autonomous goal round may report `complete` or `blocked` for the exact current goal round but cannot edit, pause, resume, or replace the human objective. -TUI and ACP mount the shared command registry and complete goal stack by default and expose `/goal` through one producer. Every effective registered command is discoverable and invocable through every composed command adapter; a plugin incompatible with an application omits its command producer from that composition rather than relying on registry-level surface masks. The UI-less agent spine is opt-in so one-shot callers do not silently become multi-round operations. The headless CLI and JSON-RPC front doors do not consume the command plane; ordinary human text can still authorize model goal tools when that stack is composed. +TUI mounts the shared command registry and complete goal stack by default and exposes `/goal` through one producer. ACP mounts the goal domain, model tools, and same-session driver but deliberately omits the human command plane. Every effective registered command is discoverable and invocable through every composed command adapter; a plugin incompatible with an application omits its command producer from that composition rather than relying on registry-level surface masks. The UI-less agent spine is opt-in so one-shot callers do not silently become multi-round operations. The headless CLI and JSON-RPC front doors do not consume the command plane; ordinary human text can still authorize model goal tools when that stack is composed. ### Fresh-agent Ralph execution @@ -94,7 +94,7 @@ External products are comparators, not compatibility targets. The local source s ### Verification -The six owning Agent Notes record unit, integration, process, snapshot, cancellation, replay, and built-runtime coverage. The stack exercises strict goal-record folding, compare-and-set races, session fork inheritance, disarmed restoration, natural-language direct-human authority, configurable caps and blocked thresholds, exact goal-round attribution, adapter-wide command discovery, and transcript isolation. Shipped keyless snapshots cover model goal creation/inspection through the headless app, multi-round same-session lifecycle and cancellation through ACP, direct `/goal` status without a model turn, and two real Ralph rounds through the headless app. The Ralph snapshot boots the worker-thread engine, spawn provider, structured-output runtime, and agent loop, then inspects distinct unseeded child logs and exact one-way bounded handoff while pinning the parent stream. Focused real-stack tests additionally cover completion, blocker and round-limit outcomes, malformed and oversized reports, ordinary child failure with the last good handoff, one phase event, and cancellation to child quiescence. Package sources remain under the repository's per-file 100% coverage gate, and built-binary tests cover installed-artifact resolution. The implementation experience is recorded in the root testing policy: every non-trivial model- or human-visible change must carry a real-example keyless snapshot in the same PR rather than relying on package-only or mock-only fixture coverage. +The six owning Agent Notes record unit, integration, process, snapshot, cancellation, replay, and built-runtime coverage. The stack exercises strict goal-record folding, compare-and-set races, session fork inheritance, disarmed restoration, natural-language direct-human authority, configurable caps and blocked thresholds, exact goal-round attribution, adapter-wide command discovery, and transcript isolation. Shipped keyless snapshots cover model goal creation/inspection through the headless app, multi-round same-session lifecycle and cancellation through ACP, and two real Ralph rounds through the headless app; focused command tests pin direct `/goal` status without a model turn. The Ralph snapshot boots the worker-thread engine, spawn provider, structured-output runtime, and agent loop, then inspects distinct unseeded child logs and exact one-way bounded handoff while pinning the parent stream. Focused real-stack tests additionally cover completion, blocker and round-limit outcomes, malformed and oversized reports, ordinary child failure with the last good handoff, one phase event, and cancellation to child quiescence. Package sources remain under the repository's per-file 100% coverage gate, and built-binary tests cover installed-artifact resolution. The implementation experience is recorded in the root testing policy: every non-trivial model- or human-visible change must carry a real-example keyless snapshot in the same PR rather than relying on package-only or mock-only fixture coverage. ## Alternatives considered @@ -126,4 +126,4 @@ The six owning Agent Notes record unit, integration, process, snapshot, cancella - **No goal reflector** — concern events, automatic no-progress heuristics, goal revision by an independent reflector, stuck-pattern detection, and `loop_split` are not implemented. Humans can edit, pause, clear, or resume the goal directly. - **Ralph policy remains narrow** — one round creates one fresh child; within-round fan-out, evaluator/worker role separation, dynamic provider/model selection, and structural recursive-Ralph tool denial need separate policy surfaces. Prompt guidance is not enforcement. - **Ralph does not retry a failed child** — an ordinary failure preserves the failed round and last good handoff, while fatal workflow infrastructure failures can end before that state is available. Retry count, backoff, and richer failure transport need separate policy and seam design. -- **Portable UI remains modest** — TUI and ACP render plain-text goal status and generic Ralph cards. There is no continuous status widget, reconnectable command output, modal goal editor, or command plane in the headless CLI or JSON-RPC front doors. +- **Portable UI remains modest** — TUI renders plain-text goal status and generic Ralph cards. ACP carries only committed assistant text; there is no continuous status widget, reconnectable command output, modal goal editor, or command plane in ACP, the headless CLI, or JSON-RPC. diff --git a/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.zh.md b/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.zh.md index 284e73051e..a3fabe40d3 100644 --- a/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.zh.md +++ b/.agents/notes/implemented/feature/2026-07-16-harness-level-loop.zh.md @@ -39,7 +39,7 @@ Status: implemented | `@deepseek-ai/dsh-tool-goal` | `packages/goal/tool-goal/`,面向模型消费者 | 注册互斥的 `get_goal`、`create_goal` 与 `update_goal`;认证实时 Turn 来源,并把自治 Round 权限收窄到带机器可路由原因代码的完成或阻塞报告。 | | `@deepseek-ai/dsh-goal-session` | `packages/goal/goal-session/`,续行策略 | 在不导入具体 loop 的情况下,预留、设围栏、接纳、归属、结算、取消并静止排空同会话目标回合。 | | `@deepseek-ai/dsh-commands` | `packages/ui/commands/`,UI 注册表 | 拥有面向人类专用命令的 `CommandDefinition`、发现、作用域注册、直接分发、`CommandResult` 与请求取消。 | -| `@deepseek-ai/dsh-command-goal` | `packages/goal/command-goal/`,人类命令生产方 | 为 TUI 和 ACP 注册构建在目标领域之上的 `/goal` 状态、创建、编辑、暂停、恢复与清除。 | +| `@deepseek-ai/dsh-command-goal` | `packages/goal/command-goal/`,人类命令生产方 | 为 TUI 注册构建在目标领域之上的 `/goal` 状态、创建、编辑、暂停、恢复与清除。 | | `@deepseek-ai/dsh-tool-ralph` | `packages/workflow/tool-ralph/`,固定工作流消费者 | 注册 `ralph({ objective, maxRounds? })`,验证全新结构化 provider 与有界 `RalphRoundReport`,并返回 `complete`、`blocked` 或 `budget-limited`。 | 详细契约分别由[目标领域](2026-07-19-persisted-same-session-goal-domain.md)、[模型目标工具](2026-07-19-model-facing-goal-tools.md)、[目标回合驱动器](2026-07-19-same-session-goal-round-driver.md)、[命令注册表](2026-07-19-plugin-command-registration.md)、[人类目标命令](2026-07-19-human-goal-command.md)与 [Ralph 工作流工具](2026-07-19-fresh-agent-ralph-workflow-tool.md) Agent Note 拥有。 @@ -70,7 +70,7 @@ fork 会话会继承持久目标前缀,因为这是自然的重放结果。for 模型只接收 `get_goal`、`create_goal` 和 `update_goal`。当直接人类请求清楚要求大量多 Round 工作时,模型可以创建目标,并且可以从任何语言推断该意图。它不得把日常单 Turn 工作变成目标。直接人类来源由代码强制执行;语义解释仍是模型判断。自治目标 Round 可以为准确当前目标 Round 报告 `complete` 或 `blocked`,但不能编辑、暂停、恢复或替换人类目标。 -TUI 与 ACP 默认挂载共享命令注册表和完整目标栈,并通过同一个生产方暴露 `/goal`。每条有效已注册命令都能被每个已组合的命令适配器发现和调用;若插件与某应用不兼容,该应用组合会省略其命令生产方,而不是依赖注册表层面的表面掩码。无 UI agent spine 要求显式选择加入,以免单次调用方静默变成多 Round 操作。无头 CLI 与 JSON-RPC 前端不消费命令平面;挂载目标栈后,普通人类文本仍可授权模型目标工具。 +TUI 默认挂载共享命令注册表和完整目标栈,并通过一个生产方暴露 `/goal`。ACP 挂载目标领域、模型工具和同会话驱动器,但有意省略人类命令平面。每条有效已注册命令都能被每个已组合的命令适配器发现和调用;若插件与某应用不兼容,该应用组合会省略其命令生产方,而不是依赖注册表层面的表面掩码。无 UI agent spine 要求显式选择加入,以免单次调用方静默变成多 Round 操作。无头 CLI 与 JSON-RPC 前端不消费命令平面;挂载目标栈后,普通人类文本仍可授权模型目标工具。 ### 全新 agent Ralph 执行 @@ -94,7 +94,7 @@ Codex 提供了这里采用的最小可观察目标 UX:一个附着于聊天 ### 验证 -六份所属 Agent Note 记录了单元、集成、进程、快照、取消、重放与构建后运行时覆盖。该栈验证严格目标记录折叠、比较并交换竞争、会话 fork 继承、恢复后未激活、自然语言直接人类权限、可配置上限与阻塞阈值、准确目标回合归属、适配器范围的命令发现与转录隔离。已发布的无密钥快照覆盖通过无头应用创建/检查模型目标、通过 ACP 执行多 Round 同会话生命周期与取消、无需模型 Turn 的直接 `/goal` 状态,以及通过无头应用执行两个真实 Ralph Round。Ralph 快照会启动工作线程引擎、spawn provider、结构化输出运行时与 agent loop,随后检查互不相同且无种子的子日志和准确单向有界交接,同时固定父级事件流。聚焦的真实栈测试还覆盖完成、阻塞与 Round 上限结果、畸形及过大报告、保留上一份有效交接的普通子 agent 失败、单个阶段事件,以及取消后达到子 agent 静止状态。包源码继续受仓库逐文件 100% 覆盖率门禁约束,构建后二进制测试覆盖已安装产物解析。实现经验已记录进根测试策略:每项非平凡的模型或人类可见变更都必须在同一 PR 中携带真实示例无密钥快照,而不能依赖仅包级或仅模拟夹具的覆盖。 +六份所属 Agent Note 记录了单元、集成、进程、快照、取消、重放与构建后运行时覆盖。该栈验证严格目标记录折叠、比较并交换竞争、会话 fork 继承、恢复后未激活、自然语言直接人类权限、可配置上限与阻塞阈值、准确目标回合归属、适配器范围的命令发现与转录隔离。已发布的无密钥快照覆盖通过无头应用创建/检查模型目标、通过 ACP 执行多 Round 同会话生命周期与取消,以及通过无头应用执行两个真实 Ralph Round;聚焦的命令测试固定了无需模型 Turn 的直接 `/goal` 状态。Ralph 快照会启动工作线程引擎、spawn provider、结构化输出运行时与 agent loop,随后检查互不相同且无种子的子日志和准确单向有界交接,同时固定父级事件流。聚焦的真实栈测试还覆盖完成、阻塞与 Round 上限结果、畸形及过大报告、保留上一份有效交接的普通子 agent 失败、单个阶段事件,以及取消后达到子 agent 静止状态。包源码继续受仓库逐文件 100% 覆盖率门禁约束,构建后二进制测试覆盖已安装产物解析。实现经验已记录进根测试策略:每项非平凡的模型或人类可见变更都必须在同一 PR 中携带真实示例无密钥快照,而不能依赖仅包级或仅模拟夹具的覆盖。 ## 考虑过的替代方案 @@ -126,4 +126,4 @@ Codex 提供了这里采用的最小可观察目标 UX:一个附着于聊天 - **没有目标反思器**——concern 事件、自动无进展启发式、由独立反思器执行的目标修订、卡住模式检测与 `loop_split` 均未实现。人类可以直接编辑、暂停、清除或恢复目标。 - **Ralph 策略仍然狭窄**——一个 Round 创建一个全新子 agent;Round 内扇出、评估器/工作者角色分离、动态 provider/模型选择与结构化递归 Ralph 工具禁止都需要独立策略表面。提示词指导不是强制执行。 - **Ralph 不会重试失败的子 agent**——普通失败会保留失败 Round 与上一份有效交接,而致命工作流基础设施错误可能在该状态可用前结束。重试次数、退避与更丰富的失败传输需要独立的策略与接缝设计。 -- **可移植 UI 仍较朴素**——TUI 与 ACP 渲染纯文本目标状态和通用 Ralph 卡片。系统没有持续状态组件、可重连命令输出、模态目标编辑器,无头 CLI 与 JSON-RPC 前端也没有命令平面。 +- **可移植 UI 仍较朴素**——TUI 渲染纯文本目标状态和通用 Ralph 卡片。ACP 只承载已提交的助手文本;系统没有持续状态组件、可重连命令输出、模态目标编辑器,ACP、无头 CLI 与 JSON-RPC 也没有命令平面。 diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml index be66b14fbf..f7e242b78c 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.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 -2026-07-16-persistent-pty-sessions.md: b33993d36753d3195ec52d3b38dda62746a47bf3 -2026-07-16-persistent-pty-sessions.zh.md: 6ed330d75824a4e6fca9de0d82db61a7c6543322 +2026-07-16-persistent-pty-sessions.md: 148d4a2f47689e38a3ec83a7a41e4f75c4b73d95 +2026-07-16-persistent-pty-sessions.zh.md: 9a9d9cd4b0f61e8abaf011996ecd8739d13851f8 diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md index b33993d367..148d4a2f47 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md @@ -24,7 +24,7 @@ The implementation supports interactive shells and line-oriented REPLs on Linux |---|---|---| | `dsh-pty` | `PtyService`, branded `PtySessionId`, backend registry, owner-scoped session contract, and result types | `ctx.pty` | | `dsh-pty-local` | [`node-pty`](https://github.com/microsoft/node-pty)-based local backend, platform process inspection, bounded terminal buffer, sandbox resolution, and process-tree supervision | registers a backend on `ctx.pty` | -| `dsh-tool-pty` | Six model-facing tools, task-runtime integration for background sends, guidance, and ACP render intents | registers on `ctx.tools` | +| `dsh-tool-pty` | Six model-facing tools, task-runtime integration for background sends, guidance, and UI render intents | registers on `ctx.tools` | Idle detection is backend behavior, not a second public seam. A remote or container backend may have authoritative readiness signals that do not resemble local `/proc` inspection; every `PtyBackend` therefore returns the common send result while owning its detection mechanism internally. @@ -58,7 +58,7 @@ The implementation uses only public `node-pty` capabilities: child PID, `data` a | `terminal_close` | Close one session and await process-tree quiescence | `{ killed }` | | `terminal_list` | List the caller's live sessions | owner-scoped session summaries | -The ACP render contract is exact and location-free. `terminal_send` uses terminal call/result cards only for foreground sends; its background form is generic `execute`. `terminal_open`, `terminal_read`, `terminal_signal`, `terminal_close`, and `terminal_list` use generic `execute`, `read`, `execute`, `delete`, and `read` cards respectively. No PTY tool emits `locations`. +The UI render contract is exact and location-free. `terminal_send` uses terminal call/result cards only for foreground sends; its background form is generic `execute`. `terminal_open`, `terminal_read`, `terminal_signal`, `terminal_close`, and `terminal_list` use generic `execute`, `read`, `execute`, `delete`, and `read` cards respectively. No PTY tool emits `locations`. `terminal_send({ sessionId, text, submit?, run_in_background? })` treats `text` as UTF-8 bytes and resolves `submit` to `true` in the tool implementation. When `submit` is true it writes the platform Enter sequence after the text; when false it writes only the text, allowing control characters and REPL fragments without hidden content heuristics. `enableRunInBackground` defaults to true; false removes `run_in_background` from the schema and rejects the same undeclared argument if a caller forces it through execution. @@ -155,7 +155,7 @@ The package ships concise tool guidance explaining persistent state, owner isola - Per-file coverage pins owner fencing, concurrent reservations, unpublished-spawn cancellation and awaited teardown, sandbox-mode change rejection, retriable lifecycle cleanup, readiness tiers, sanitizer carry state, complete UTF-8 bounds, task integration, schemas, and exact render intents. - Linux process fixtures cover non-leader and non-main-thread stdin waits, zombie quiescence, unreadable process state, supported syscall tables, unsupported architectures, and false-positive rejection; macOS inspector logic is injected into the same unit suite. - Real `node-pty` tests exercise shell state, shared sandbox policy, environment scrubbing, raw-mode foreground `SIGINT`, a TERM-ignoring descendant, and immediate post-disposal quiescence on supported hosts. -- A Loader-driven `cordis.yml` test mounts the real three-package composition, while ACP and headless snapshots pin the six schemas, bounded results, error rendering, and terminal/generic cards through opt-in overlays. +- A Loader-driven `cordis.yml` test mounts the real three-package composition. ACP and headless snapshots pin the six schemas, bounded results, and errors through opt-in overlays; TUI snapshots pin terminal and generic card presentation. - Package contracts, the architecture map, core data structures, generated catalogs, and the website API describe the same shipped surface. - The repository CI-equivalent sequence owns type, lint, coverage, snapshot, documentation, build, hygiene, demo, and built-entry verification. diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md index 6ed330d758..9a9d9cd4b0 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md @@ -24,7 +24,7 @@ harness 可以运行前台与后台命令、编辑文件和委派工作,但无 |---|---|---| | `dsh-pty` | `PtyService`、branded `PtySessionId`、后端注册表、按 owner 隔离的会话契约和结果类型 | `ctx.pty` | | `dsh-pty-local` | 基于 [`node-pty`](https://github.com/microsoft/node-pty) 的本地后端、平台进程检查、有界终端缓冲、沙箱解析和进程树监管 | 在 `ctx.pty` 上注册后端 | -| `dsh-tool-pty` | 6 个面向模型的工具、后台发送的 task 运行时集成、使用指引和 ACP render intent | 注册到 `ctx.tools` | +| `dsh-tool-pty` | 6 个面向模型的工具、后台发送的 task 运行时集成、使用指引和 UI 渲染意图 | 注册到 `ctx.tools` | idle 检测属于后端行为,不是第二条公共 seam。远程或容器后端可能拥有完全不同于本地 `/proc` 检查的权威就绪信号;因此每个 `PtyBackend` 都返回统一的发送结果,同时在内部拥有自己的检测机制。 @@ -58,7 +58,7 @@ agent scope dispose 时先关闭注册,再等待全部所属 PTY 静默退出 | `terminal_close` | 关闭一个会话并等待进程树静默退出 | `{ killed }` | | `terminal_list` | 列出调用方的活会话 | 按 owner 隔离的会话摘要 | -ACP 渲染契约精确且不携带位置信息。`terminal_send` 只为前台发送使用 terminal 调用卡片和结果卡片;后台形式使用通用 `execute` 卡片。`terminal_open`、`terminal_read`、`terminal_signal`、`terminal_close` 和 `terminal_list` 分别使用通用 `execute`、`read`、`execute`、`delete` 和 `read` 卡片。所有 PTY 工具都不发出 `locations`。 +UI 渲染契约精确且不携带位置信息。`terminal_send` 只为前台发送使用 terminal 调用卡片和结果卡片;后台形式使用通用 `execute` 卡片。`terminal_open`、`terminal_read`、`terminal_signal`、`terminal_close` 和 `terminal_list` 分别使用通用 `execute`、`read`、`execute`、`delete` 和 `read` 卡片。所有 PTY 工具都不发出 `locations`。 `terminal_send({ sessionId, text, submit?, run_in_background? })` 将 `text` 视为 UTF-8 字节,并由工具实现在解析阶段把 `submit` 默认成 `true`。`submit` 为 true 时先写入文本,再写入平台 Enter 序列;为 false 时只写文本,使控制字符和 REPL 片段无需隐藏的内容启发式即可发送。`enableRunInBackground` 默认为 true;设为 false 时,schema 中会移除 `run_in_background`,调用方即使强行把这个未声明参数传入执行流程,也会被拒绝。 @@ -122,7 +122,7 @@ plugins: maxResultBytes: 262144 ``` -包提供简洁的工具指引,说明持久状态、owner 隔离、不确定的 idle 结果、清理,以及无需交互时优先使用现有一次性工具。已发布的基础示例不挂载 PTY:PTY 仅通过专用组合 opt-in,ACP 与 headless 快照 overlay 覆盖该组合。`dsh-tool-pty` 实例一旦启用,6 个工具和 `run_in_background` 就会默认启用;部署可通过配置仅禁用后台参数。 +包提供简洁的工具指引,说明持久状态、owner 隔离、不确定的 idle 结果、清理,以及无需交互时优先使用现有一次性工具。已发布的基础示例不挂载 PTY:PTY 仅通过专用组合 opt-in,ACP(Agent Client Protocol)与 headless 快照 overlay 覆盖该组合。`dsh-tool-pty` 实例一旦启用,6 个工具和 `run_in_background` 就会默认启用;部署可通过配置仅禁用后台参数。 ### 推迟的工作 @@ -155,7 +155,7 @@ plugins: - 每文件覆盖率固定 owner 隔离、并发预留、未发布 spawn 的取消与等待式 teardown、沙箱模式变更拒绝、可重试的生命周期清理、就绪层级、sanitizer carry state、完整 UTF-8 结果上限、task 集成、schema 和精确 render intent。 - Linux 进程 fixture 覆盖非 leader 与非主线程的 stdin 等待、僵尸进程静止性、不可读进程状态、受支持的 syscall 表、不支持的架构和误报拒绝;同一单元测试套件通过注入覆盖 macOS 检查器逻辑。 - 真实 `node-pty` 测试在受支持宿主上覆盖 shell 状态、共享沙箱策略、环境清洗、raw mode 下的前台 `SIGINT`、忽略 `SIGTERM` 的子进程,以及 dispose 返回后立即静默。 -- Loader 驱动的 `cordis.yml` 测试挂载真实三包组合;ACP 与 headless 快照通过 opt-in overlay 固定 6 个 schema、有界结果、错误渲染和 terminal/generic card。 +- Loader 驱动的 `cordis.yml` 测试挂载真实三包组合。ACP 与 headless 快照通过 opt-in overlay 固定 6 个 schema、有界结果和错误;TUI 快照固定 terminal 与 generic 卡片展示。 - 包契约、架构图、核心数据结构、生成目录和 website API 描述同一个已发布接口。 - 仓库 CI 等价序列负责类型、lint、覆盖率、快照、文档、构建、hygiene、demo 和 built-entry 验证。 diff --git a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.i18n.yaml b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.i18n.yaml index 8d6c7be831..79a4f5e7cc 100644 --- a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.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 -2026-07-17-dedicated-full-screen-tui-front-door.md: ecfda138593fc2b98ac42929acc586b11e437ee2 -2026-07-17-dedicated-full-screen-tui-front-door.zh.md: 6b8cc63f7657672a6da542e2033d765b54bd4f07 +2026-07-17-dedicated-full-screen-tui-front-door.md: aac67ffec89606d04d5abfd233d0469e2241b102 +2026-07-17-dedicated-full-screen-tui-front-door.zh.md: 0f64e2ce14b18d315f75913b82c731e77758e377 diff --git a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md index ecfda13859..aac67ffec8 100644 --- a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md +++ b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md @@ -14,7 +14,7 @@ The interactive channel must remain a Cordis plugin over the same agent, session DeepSeek Harness ships [`@deepseek-ai/dsh-tui`](../../../../packages/ui/tui/README.md) as a dedicated Cordis plugin. It owns terminal input and presentation only; agent lifecycle, session persistence, tool execution, and the model-facing question tool remain separate composition entries. The plugin requires both stdin and stdout to be TTYs and fails instead of silently changing to line-oriented behavior. -The app layer has one terminal front door. `@deepseek-ai/dsh-tui-demo` mounts the TUI before the configured agent, and `examples/tui-agent` owns the interactive coding composition and Code Mode overlay directly. Non-interactive tasks use `@deepseek-ai/dsh-cli-demo`; ACP remains a separate editor protocol. +The app layer has one terminal front door. `@deepseek-ai/dsh-tui-demo` mounts the TUI before the configured agent, and `examples/tui-agent` owns the interactive coding composition and Code Mode overlay directly. Non-interactive tasks use `@deepseek-ai/dsh-cli-demo`; ACP remains a separate automation protocol. The selected front door receives the exact generated or resumed `SessionId` used by the pre-created agent. It mounts before the agent composition, waits for the matching root agent, and enters full-screen mode only after that agent exists. A matching `agent-loop/config-start-failed` event is therefore reported before screen takeover and exits with status 1. diff --git a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.zh.md b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.zh.md index 6b8cc63f76..0f64e2ce14 100644 --- a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.zh.md +++ b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.zh.md @@ -14,7 +14,7 @@ Status: implemented DeepSeek Harness 将 [`@deepseek-ai/dsh-tui`](../../../../packages/ui/tui/README.md) 作为独立的 Cordis 插件交付。该插件只负责终端输入与呈现;agent 生命周期、会话持久化、工具执行以及模型可见的提问工具仍由不同组合项负责。插件要求 stdin 和 stdout 均为 TTY;条件不满足时会失败,不会静默切换为逐行输出。 -应用组合层只有一个终端入口。`@deepseek-ai/dsh-tui-demo` 在已配置 agent 之前挂载 TUI,`examples/tui-agent` 直接拥有交互式 coding 组装及其 Code Mode overlay。非交互任务使用 `@deepseek-ai/dsh-cli-demo`;ACP 仍是独立的编辑器协议。 +应用组合层只有一个终端入口。`@deepseek-ai/dsh-tui-demo` 在已配置 agent 之前挂载 TUI,`examples/tui-agent` 直接拥有交互式 coding 组装及其 Code Mode overlay。非交互任务使用 `@deepseek-ai/dsh-cli-demo`;ACP 仍是独立的自动化协议。 所选入口接收预创建 agent 使用的同一个新建或恢复 `SessionId`。入口先于 agent 组合挂载,等待相符的根 agent 出现,然后才进入全屏模式。因此,相符的 `agent-loop/config-start-failed` 事件会在接管屏幕前报告,并以状态码 1 退出。 diff --git a/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.i18n.yaml b/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.i18n.yaml index 17e3cdf5e2..67b6b8da3d 100644 --- a/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.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 -2026-07-19-fresh-agent-ralph-workflow-tool.md: c2db4d7dd30c27a25adecdfc425db261cc3dfeb5 -2026-07-19-fresh-agent-ralph-workflow-tool.zh.md: e33e9848d71c98c8f83494ebe8bf171ef10b9305 +2026-07-19-fresh-agent-ralph-workflow-tool.md: 6fe96587c49ef0316d1618fda2ee26b015b1ce87 +2026-07-19-fresh-agent-ralph-workflow-tool.zh.md: c615c16ac020a0c905f6c8b52d8dc487fbcfe8be diff --git a/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.md b/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.md index c2db4d7dd3..6fe96587c4 100644 --- a/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.md +++ b/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.md @@ -40,7 +40,7 @@ The workflow language maps a normally settled but unsuccessful child to `null`. The model may supply only `objective` and optional `maxRounds`; provider selection, report schema, handoff cap, and script are deployment-owned. A fixed prompt section says to use `ralph` only when the direct human explicitly asks for Ralph or fresh-agent iteration, and distinguishes it from same-session goals, bounded delegation, and general fan-out workflows. This is guidance rather than a new goal UX state machine. -ACP and terminal presentation use a generic `ralph` card whose raw input is the objective. Successful completion and blocker envelopes say that a worker reported the outcome rather than presenting it as independent certification. The parent transcript retains the original tool call and one bounded successful terminal report or an error, not intermediate child messages. Shipped headless, TUI, and ACP compositions load the plugin beside the existing workflow engine; JSON-RPC remains unchanged because its default composition does not expose workflows. +Human-facing presentation uses a generic `ralph` card whose raw input is the objective; ACP carries only the committed assistant text. Successful completion and blocker envelopes say that a worker reported the outcome rather than presenting it as independent certification. The parent transcript retains the original tool call and one bounded successful terminal report or an error, not intermediate child messages. Shipped headless, TUI, and ACP compositions load the plugin beside the existing workflow engine; JSON-RPC remains unchanged because its default composition does not expose workflows. ## Testing diff --git a/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.zh.md b/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.zh.md index e33e9848d7..c615c16ac0 100644 --- a/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.zh.md +++ b/.agents/notes/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.zh.md @@ -40,7 +40,7 @@ Ralph 插件的 `subagentProvider` 默认为 `spawn`。每次调用前,它要 模型只能提供 `objective` 和可选的 `maxRounds`;provider 选择、报告 schema、交接上限和脚本都由部署拥有。固定提示区段说明,只有直接人类明确要求 Ralph 或全新 agent 迭代时才使用 `ralph`,并将其与同会话目标、有界委派和通用扇出工作流区分开。这是指导,而不是新的目标 UX 状态机。 -ACP 和终端展示使用通用 `ralph` 卡片,并把目标作为原始输入。成功完成与阻塞的外层文本会说明结果由工作者报告,而不会把它呈现为独立认证。父转录只保留原始工具调用,以及一份有界成功终止报告或一个错误,不包含中间子 agent 消息。发布的无头、TUI 与 ACP 组合会在现有工作流引擎旁加载该插件;JSON-RPC 保持不变,因为其默认组合不暴露工作流。 +面向人类的展示使用通用 `ralph` 卡片,并把目标作为原始输入;ACP 只承载已提交的助手文本。成功完成与阻塞的外层文本会说明结果由工作者报告,而不会把它呈现为独立认证。父转录只保留原始工具调用,以及一份有界成功终止报告或一个错误,不包含中间子 agent 消息。发布的无头、TUI 与 ACP 组合会在现有工作流引擎旁加载该插件;JSON-RPC 保持不变,因为其默认组合不暴露工作流。 ## 测试 diff --git a/.agents/notes/implemented/feature/2026-07-19-human-goal-command.i18n.yaml b/.agents/notes/implemented/feature/2026-07-19-human-goal-command.i18n.yaml index 5379f25772..44e1412cc4 100644 --- a/.agents/notes/implemented/feature/2026-07-19-human-goal-command.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-19-human-goal-command.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 -2026-07-19-human-goal-command.md: a272206a3bfad50a01ce871c56c7e7bcf924684e -2026-07-19-human-goal-command.zh.md: 370c9bc24510320c70e3d789926c492e543968b1 +2026-07-19-human-goal-command.md: ce5c37fd28f9432d8c9a8797cac32c632617e317 +2026-07-19-human-goal-command.zh.md: d5ce36bd75a6f1070ee1eaeb1ac6ee97778c246b diff --git a/.agents/notes/implemented/feature/2026-07-19-human-goal-command.md b/.agents/notes/implemented/feature/2026-07-19-human-goal-command.md index a272206a3b..ce5c37fd28 100644 --- a/.agents/notes/implemented/feature/2026-07-19-human-goal-command.md +++ b/.agents/notes/implemented/feature/2026-07-19-human-goal-command.md @@ -6,7 +6,7 @@ English | [中文](2026-07-19-human-goal-command.zh.md) ## Problem -The same-session goal domain and model tools provide the state machine and semantic natural-language path, but they are not a sufficient human UX. A user needs to inspect the exact current phase and round budget without asking the model, explicitly pause or clear work without spending a model turn, and rearm a restored active goal after the required post-resume human decision. Implementing those actions independently in TUI and ACP would duplicate parsing, let the surfaces drift, and risk routing an unknown or unavailable command into the model. +The same-session goal domain and model tools provide the state machine and semantic natural-language path, but they are not a sufficient human UX. A user needs to inspect the exact current phase and round budget without asking the model, explicitly pause or clear work without spending a model turn, and rearm a restored active goal after the required post-resume human decision. Implementing those actions independently in each UI would duplicate parsing, let the surfaces drift, and risk routing an unknown or unavailable command into the model. The command must also respect the goal design's two kinds of state. Durable phase, objective, revisions, and rounds come from the session log; process-local activation decides whether an active goal may continue automatically. Showing only “active” after a resume would be misleading when the restored goal is intentionally disarmed and waiting for human authorization. @@ -22,7 +22,7 @@ The command follows the compact Codex shape in the [public OpenAI Codex TUI disp `/goal <objective>` creates an active armed goal. A completed goal may be replaced, which creates a fresh goal identity through the existing domain rule. Any unfinished goal makes the command fail directly with instructions to use inline edit or explicit clear. The generic command service deliberately has no modal confirmation API, so silently clearing and creating two durable records would manufacture destructive consent and expose a non-atomic failure window. -`/goal edit <objective>` edits the current non-complete goal without changing phase or activation. On a completed goal it creates a fresh active goal because the domain does not permit completed state to resume and a new completion objective is a new goal identity. Bare `edit` is an error rather than an editor launch because ACP's shared unstructured command contract has no portable modal editor. +`/goal edit <objective>` edits the current non-complete goal without changing phase or activation. On a completed goal it creates a fresh active goal because the domain does not permit completed state to resume and a new completion objective is a new goal identity. Bare `edit` is an error rather than an editor launch because the portable unstructured command contract has no modal editor. `/goal pause`, `/goal resume`, and `/goal clear` call the matching compare-and-set domain verbs against the current view. Resume covers both stopped durable phases and an active-but-disarmed goal after session resume, fork, or driver replacement. Domain rules still reject exhausted round caps, redundant active/armed resume, invalid phase transitions, and stale identity. Clear removes the current pointer while the session log retains the revisioned tombstone and earlier snapshots. @@ -40,16 +40,16 @@ Generic slash input, status text, and errors are not persisted. Successful goal `agent-spine-demo` accepts an optional `goals` composition object containing the goal-domain and model-tool owner configs. Omission or `false` leaves the stack unmounted. This explicit opt-in is important for headless one-shot callers: their result API settles one correlated physical turn and must not silently become a long-running logical goal operation. -The interactive app bundles make the opposite product choice. ACP and TUI default `goals` to the owner defaults and mount the goal domain, model tools, same-session driver, command registry, and this producer. Both apps accept `goals: false` as one coherent stack opt-out. The Python SDK runtime closure ships this producer alongside ACP, commands, and the goal stack so an external `cordis.yml` can compose the same command. +The TUI app bundle makes the opposite product choice. It defaults `goals` to the owner defaults and mounts the goal domain, model tools, same-session driver, command registry, and this producer; `goals: false` removes the stack coherently. The [ACP automation app](../simplification/2026-07-23-acp-automation-only-protocol.md) also defaults the goal domain and model tools but deliberately omits command services. The Python SDK runtime closure ships this producer, commands, and the goal stack so an external `cordis.yml` can compose the same command. ## Testing -The producer suite uses the real command registry, goal service, agent registry, and session log. It covers Loader-safe exports, registry discovery, disposal, empty status, objective parsing, unfinished replacement refusal, inline edit, completed replacement, all missing-state controls, pause/resume/clear, every durable phase, blocked code/explanation presentation, armed/disarmed presentation, sanitized domain errors, unexpected failures, and persisted mutation records. App composition tests cover explicit spine opt-in, TUI/ACP defaults, coherent opt-out, forwarded domain/tool config, command discovery, the packaged-runtime closure, and the expanded model-tool assembly. A keyless snapshot boots the shipped ACP application, observes its advertised `/goal` metadata, invokes `/goal` directly, and pins the no-model-turn result; the surrounding ACP snapshots also pin the goal tool schemas in that composition. +The producer suite uses the real command registry, goal service, agent registry, and session log. It covers Loader-safe exports, registry discovery, disposal, empty status, objective parsing, unfinished replacement refusal, inline edit, completed replacement, all missing-state controls, pause/resume/clear, every durable phase, blocked code/explanation presentation, armed/disarmed presentation, sanitized domain errors, unexpected failures, and persisted mutation records. App composition tests cover explicit spine opt-in, TUI defaults, coherent opt-out, forwarded domain/tool config, command discovery, the packaged-runtime closure, and the expanded model-tool assembly. ACP backend snapshots continue to pin the goal tool schemas independently of this human command. ## Alternatives considered -- **Let the model handle `/goal` as ordinary text** — rejected because status and direct lifecycle actions would cost a model turn, could be reinterpreted, and would not provide deterministic ACP discovery. -- **Implement separate TUI and ACP handlers** — rejected because grammar, error behavior, and goal-state formatting would drift and optional deployments could not add or remove the capability as one effect. +- **Let the model handle `/goal` as ordinary text** — rejected because status and direct lifecycle actions would cost a model turn, could be reinterpreted, and would not provide deterministic command discovery. +- **Implement separate handlers in each UI** — rejected because grammar, error behavior, and goal-state formatting would drift and optional deployments could not add or remove the capability as one effect. - **Add modal editing and replacement confirmation to `ctx.commands`** — rejected because the existing cross-surface contract is unstructured input plus direct output; a general interaction protocol needs more than this one producer. - **Silently replace an unfinished goal** — rejected because it combines clear and create without atomicity or explicit destructive intent. - **Expose goal id and revision in human status** — rejected because human actions always target the exact current view inside one synchronous handler; those fields add implementation noise without preventing another race. @@ -57,7 +57,7 @@ The producer suite uses the real command registry, goal service, agent registry, ## Consequences -- TUI and ACP expose one Codex-shaped `/goal` command supplied by a removable plugin. +- TUI exposes one Codex-shaped `/goal` command supplied by a removable plugin. - Human status distinguishes durable phase from live activation and reports the exact goal-round cap. - Direct pause, resume, clear, creation, and edit consume no model turn while their accepted mutations remain reconstructable from the session log. - Restored sessions wait for a human decision; `/goal resume` is the literal command path, while an ordinary prompt in any language may authorize the model tool path. @@ -67,6 +67,6 @@ The producer suite uses the real command registry, goal service, agent registry, - The portable command contract has no modal editor or confirmation interaction; inline edit and explicit clear are intentional until a general cross-surface interaction primitive exists. - `/goal` does not accept a per-command round cap. Deployment config owns the default, and the authorized model tool can edit a cap after direct human instruction. -- TUI and ACP render portable plain text rather than a continuously updated goal status widget. Reconnectable command output and adapter-specific status indicators are deferred. -- The headless CLI and JSON-RPC front doors do not consume the command registry. +- TUI renders portable plain text rather than a continuously updated goal status widget. Reconnectable command output and adapter-specific status indicators are deferred. +- The ACP automation server, headless CLI, and JSON-RPC front doors do not consume the command registry. - The command observes and mutates state but does not certify completion or blockers. Evaluator-backed certification remains deferred to a separate policy layer with an explicit authority and isolation contract. diff --git a/.agents/notes/implemented/feature/2026-07-19-human-goal-command.zh.md b/.agents/notes/implemented/feature/2026-07-19-human-goal-command.zh.md index 370c9bc245..d5ce36bd75 100644 --- a/.agents/notes/implemented/feature/2026-07-19-human-goal-command.zh.md +++ b/.agents/notes/implemented/feature/2026-07-19-human-goal-command.zh.md @@ -6,7 +6,7 @@ Status: implemented ## 问题 -同会话目标领域和模型工具提供了状态机与自然语言语义路径,但尚不足以构成面向人类的 UX。用户需要在不询问模型的情况下检查准确的当前阶段与回合预算,在不消耗模型轮次的情况下明确暂停或清除工作,并在会话恢复后经过必要的人类决策重新激活已恢复的活跃目标。若在 TUI 与 ACP 中分别实现这些操作,就会重复解析逻辑、导致两个表面发生偏差,还可能把未知或不可用的命令交给模型处理。 +同会话目标领域和模型工具提供了状态机与自然语言语义路径,但尚不足以构成面向人类的 UX。用户需要在不询问模型的情况下检查准确的当前阶段与回合预算,在不消耗模型轮次的情况下明确暂停或清除工作,并在会话恢复后经过必要的人类决策重新激活已恢复的活跃目标。若在各 UI 中分别实现这些操作,就会重复解析逻辑、导致各界面发生偏差,还可能把未知或不可用的命令交给模型处理。 该命令还必须遵守目标设计中的两类状态。持久阶段、目标描述、修订号与回合来自会话日志;进程本地激活态决定活跃目标能否自动继续。恢复后若只显示“活跃”,就会掩盖目标已被有意设为未激活、正在等待人类授权这一事实。 @@ -22,7 +22,7 @@ Status: implemented `/goal <objective>` 创建活跃且已激活的目标。已完成目标可以被替换,此时通过现有领域规则创建新的目标身份。任何未完成目标都会让命令直接失败,并提示用户使用行内编辑或明确清除。通用命令服务有意不提供模态确认 API;若静默执行清除再创建两条持久记录,就等于凭空制造破坏性同意,并暴露一个非原子的失败窗口。 -`/goal edit <objective>` 编辑当前未完成目标,但不改变其阶段或激活态。若目标已经完成,则创建一个新的活跃目标,因为领域不允许恢复已完成状态,而新的完成条件应拥有新的目标身份。单独使用 `edit` 会返回错误而不是启动编辑器,因为 ACP 共享的非结构化命令契约没有可移植的模态编辑器。 +`/goal edit <objective>` 编辑当前未完成目标,但不改变其阶段或激活态。若目标已经完成,则创建一个新的活跃目标,因为领域不允许恢复已完成状态,而新的完成条件应拥有新的目标身份。单独使用 `edit` 会返回错误而不是启动编辑器,因为可移植的非结构化命令契约没有模态编辑器。 `/goal pause`、`/goal resume` 与 `/goal clear` 使用当前视图调用相应的比较并交换领域动词。恢复既适用于停止的持久阶段,也适用于会话恢复、fork 或驱动器替换后处于活跃但未激活状态的目标。领域规则仍会拒绝已耗尽的回合上限、对已活跃且已激活目标的重复恢复、非法阶段转换与陈旧身份。清除会移除当前指针,而会话日志保留带修订号的墓碑和此前快照。 @@ -40,16 +40,16 @@ Status: implemented `agent-spine-demo` 接受可选的 `goals` 组合对象,其中包含目标领域与模型工具的所有者配置。省略或设为 `false` 时不会挂载该栈。对无头单次调用方而言,明确选择加入非常重要:它们的结果 API 会在一个相关物理轮次后结束,不能静默变成长时间运行的逻辑目标操作。 -交互式应用包作出相反的产品选择。ACP 与 TUI 默认让 `goals` 使用所有者默认值,并挂载目标领域、模型工具、同会话驱动器、命令注册表与本生产方。两个应用都接受 `goals: false` 作为一致的整体退出选项。Python SDK 运行时闭包把本生产方与 ACP、命令及目标栈一并交付,使外部 `cordis.yml` 能组合相同命令。 +TUI 应用包作出相反的产品选择。它默认让 `goals` 使用所有者默认值,并挂载目标领域、模型工具、同会话驱动器、命令注册表与本生产方;`goals: false` 会一致地移除整个栈。[ACP(Agent Client Protocol)自动化应用](../simplification/2026-07-23-acp-automation-only-protocol.md)也默认挂载目标领域与模型工具,但有意省略命令服务。Python SDK 运行时闭包交付本生产方、命令与目标栈,使外部 `cordis.yml` 能组合相同命令。 ## 测试 -生产方测试套件使用真实命令注册表、目标服务、agent 注册表与会话日志。它覆盖 Loader 安全导出、注册表发现、资源释放、空状态、目标描述解析、拒绝未完成目标替换、行内编辑、已完成目标替换、所有缺失状态控制、暂停/恢复/清除、每个持久阶段、阻塞代码/说明展示、已激活/未激活展示、经净化的领域错误、意外失败与持久变更记录。应用组合测试覆盖显式主干选择加入、TUI/ACP 默认值、一致退出、转发的领域/工具配置、命令发现、打包运行时闭包与扩展后的模型工具组装。一个无密钥快照会启动交付的 ACP 应用,观察其公布的 `/goal` 元数据,直接调用 `/goal`,并固定不经过模型轮次的结果;周边 ACP 快照还会固定该组合中的目标工具 schema。 +生产方测试套件使用真实命令注册表、目标服务、agent 注册表与会话日志。它覆盖 Loader 安全导出、注册表发现、资源释放、空状态、目标描述解析、拒绝未完成目标替换、行内编辑、已完成目标替换、所有缺失状态控制、暂停/恢复/清除、每个持久阶段、阻塞代码/说明展示、已激活/未激活展示、经净化的领域错误、意外失败与持久变更记录。应用组合测试覆盖显式主干选择加入、TUI 默认值、一致退出、转发的领域/工具配置、命令发现、打包运行时闭包与扩展后的模型工具组装。ACP 后端快照继续固定目标工具 schema,与这项面向人类的命令无关。 ## 考虑过的替代方案 -- **让模型把 `/goal` 当作普通文本处理**——不予采纳,因为状态与直接生命周期操作会消耗模型轮次、可能被重新解释,也无法提供确定性的 ACP 发现。 -- **分别实现 TUI 和 ACP 处理器**——不予采纳,因为语法、错误行为与目标状态格式会发生偏差,可选部署也无法把该功能作为一个 effect 统一增删。 +- **让模型把 `/goal` 当作普通文本处理**——不予采纳,因为状态与直接生命周期操作会消耗模型轮次、可能被重新解释,也无法提供确定性的命令发现。 +- **在各 UI 中分别实现处理器**——不予采纳,因为语法、错误行为与目标状态格式会发生偏差,可选部署也无法把该功能作为一个 effect 统一增删。 - **为 `ctx.commands` 添加模态编辑与替换确认**——不予采纳,因为现有跨表面契约是非结构化输入加直接输出;通用交互协议所需的设计远超这一个生产方。 - **静默替换未完成目标**——不予采纳,因为这会在没有原子性或明确破坏性意图的情况下组合清除与创建。 - **在人类状态中暴露目标 id 与修订号**——不予采纳,因为人类操作始终在一个同步处理器内针对准确当前视图;这些字段只会增加实现噪声,无法消除其他竞争。 @@ -57,7 +57,7 @@ Status: implemented ## 后果 -- TUI 与 ACP 暴露由可移除插件提供的同一个 Codex 形态 `/goal` 命令。 +- TUI 暴露由可移除插件提供的 Codex 形态 `/goal` 命令。 - 人类状态会区分持久阶段与实时激活态,并报告准确的目标回合上限。 - 直接暂停、恢复、清除、创建与编辑不消耗模型轮次,而其已接受变更仍可从会话日志重建。 - 恢复后的会话等待人类决策;`/goal resume` 是字面命令路径,任何语言的普通提示词则可以授权模型工具路径。 @@ -67,6 +67,6 @@ Status: implemented - 可移植命令契约没有模态编辑器或确认交互;在出现通用跨表面交互原语之前,行内编辑与明确清除是有意选择。 - `/goal` 不接受逐命令回合上限。部署配置拥有默认值;得到直接人类指示后,已授权模型工具可以编辑上限。 -- TUI 与 ACP 渲染可移植纯文本,而不是持续更新的目标状态组件。可重连命令输出和适配器专用状态指示器予以延期。 -- 无头 CLI 与 JSON-RPC 前端不消费命令注册表。 +- TUI 渲染可移植纯文本,而不是持续更新的目标状态组件。可重连命令输出和适配器专用状态指示器予以延期。 +- ACP 自动化服务器、无头 CLI 与 JSON-RPC 前端不消费命令注册表。 - 该命令观察并改变状态,但不认证完成或阻塞。基于评估器的认证延期到具有明确权限与隔离契约的独立策略层。 diff --git a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.i18n.yaml index 70ca07b414..9beb453252 100644 --- a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-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 -2026-07-19-model-facing-goal-tools.md: 286329390a058c0302520fd2203e5becb8c81395 -2026-07-19-model-facing-goal-tools.zh.md: b0b4fc99ada3597fbab58081f52309e21dd43bac +2026-07-19-model-facing-goal-tools.md: 2c53a7658e213dee4fecc93709244f97b821aca0 +2026-07-19-model-facing-goal-tools.zh.md: aa7b5ea14b7afff88819f0efa35c5f2d5e2e933e diff --git a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.md b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.md index 286329390a..2c53a7658e 100644 --- a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.md +++ b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.md @@ -20,7 +20,7 @@ The surface also needs to preserve the separation between durable state and live The prompt tells the model that it may infer goal intent from a direct human request in any wording or language, but should not convert routine single-turn work into a goal. It must read the current goal before updating and copy the exact id and revision. On a restored or forked active-but-disarmed goal, a semantic human request to continue is grounds for `resume`. Completion is reserved for an achieved objective, and difficulty or uncertainty alone is not a blocker; a block report must name the concrete condition. -All three tools use exclusive execution so a model-ordered batch observes prior mutations and their new revisions. Results are compact JSON. ACP presentation is a pure function of arguments and uses generic read or mutation cards; mutation cards select meaningful action values before the goal id, so accepted fillers cannot blank their input. Activation is reported only as live observation and is never written into replay state. +All three tools use exclusive execution so a model-ordered batch observes prior mutations and their new revisions. Results are compact JSON. UI presentation is a pure function of arguments and uses generic read or mutation cards; mutation cards select meaningful action values before the goal id, so accepted fillers cannot blank their input. Activation is reported only as live observation and is never written into replay state. An autonomous goal round that successfully reports completion or blocking contributes the existing terminal `agent/turn-stop` decision for that physical turn, preventing an unnecessary follow-up request. Direct-human mutations do not contribute a terminal stop: the assistant can acknowledge the change, and concurrent human steering remains available to ordinary continuation folding. diff --git a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.zh.md b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.zh.md index b0b4fc99ad..aa7b5ea14b 100644 --- a/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.zh.md +++ b/.agents/notes/implemented/feature/2026-07-19-model-facing-goal-tools.zh.md @@ -20,7 +20,7 @@ Status: implemented 提示词告诉模型:它可以从任何措辞或语言的直接人类请求中推断目标意图,但不应把常规单轮工作转换为目标。更新前必须读取当前目标,并复制准确的 id 和修订号。对于恢复或派生后处于活跃但未激活状态的目标,人类在语义上要求继续即可成为执行 `resume` 的依据。只有目标已经实现时才能标记完成,困难或不确定性本身不构成阻塞;阻塞报告必须说明具体条件。 -三个工具都采用独占执行,使模型排序的批次可以观察此前变更及其新修订号。结果为紧凑 JSON。ACP 展示是参数的纯函数,使用通用读取或变更卡片;变更卡片选择输入时,先取有实际意义的操作值,再取目标 id,因此允许的占位值不会使卡片输入留空。激活态仅作为实时观察返回,绝不会写入回放状态。 +三个工具都采用独占执行,使模型排序的批次可以观察此前变更及其新修订号。结果为紧凑 JSON。UI 展示是参数的纯函数,使用通用读取或变更卡片;变更卡片选择输入时,先取有实际意义的操作值,再取目标 id,因此允许的占位值不会使卡片输入留空。激活态仅作为实时观察返回,绝不会写入回放状态。 自主目标回合成功报告完成或阻塞后,插件会为该物理轮次贡献现有的终止型 `agent/turn-stop` 决策,避免再发起一次不必要的模型请求。直接人类发起的变更不会贡献终止决策:智能体可以确认该变更,并且并发的人类 steering(转向)仍可参与普通的继续执行折叠。 diff --git a/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.i18n.yaml b/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.i18n.yaml index 9789d902fc..8b2ddb5ac1 100644 --- a/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.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 -2026-07-19-plugin-command-registration.md: bc3d33f9abf7cd87b78aac8f7d36ac9c021a7910 -2026-07-19-plugin-command-registration.zh.md: 054ab3a90eeecc8c5ddc2ff072b53112fd8e7845 +2026-07-19-plugin-command-registration.md: 343cb5d946dba9fb881adf12c197961dfd6a359b +2026-07-19-plugin-command-registration.zh.md: 27757f05afe04d7cbd4ceaf9380b6f73441cc4b9 diff --git a/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md b/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md index bc3d33f9ab..343cb5d946 100644 --- a/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md +++ b/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md @@ -6,17 +6,17 @@ English | [中文](2026-07-19-plugin-command-registration.zh.md) ## Problem -The TUI owns seven slash commands, while ACP defines a standard command catalog and invocation shape. Keeping command names, help text, autocomplete, dispatch, and cancellation inside each adapter makes every new command an adapter edit, prevents optional plugins from contributing commands, and lets the two front doors drift. Treating slash input as an ordinary model prompt is also unsafe: a user-visible direct action can unexpectedly consume tokens or let the model reinterpret an unknown command. +The TUI owns slash commands. Keeping command names, help text, autocomplete, dispatch, and cancellation inside the adapter makes every new command a TUI edit and prevents optional plugins from contributing commands. Treating slash input as an ordinary model prompt is also unsafe: a user-visible direct action can unexpectedly consume tokens or let the model reinterpret an unknown command. -A shared mechanism must remain a UI concern rather than a model tool or agent-loop branch. It also needs exact per-agent visibility, HMR-safe removal, per-session ACP discovery, direct result rendering, and request-scoped cancellation without automatically adding command text or output to model history. +A shared mechanism must remain a UI concern rather than a model tool or agent-loop branch. It also needs exact per-agent visibility, HMR-safe removal, direct result rendering, and request-scoped cancellation without automatically adding command text or output to model history. ## Decision -`@deepseek-ai/dsh-commands` in `packages/ui/commands/` is the product command registry. The terminal and ACP app bundles mount it beside their consuming front door, and the SDK project helper emits the same service when scaffolding ACP directly; the executor-less, UI-less agent spine remains independent. TUI and ACP inject the service, while command producers depend only on the registry and any domain they operate. +`@deepseek-ai/dsh-commands` in `packages/ui/commands/` is the product command registry. The TUI app bundle mounts it beside its consuming front door; the [automation-only ACP app](../simplification/2026-07-23-acp-automation-only-protocol.md) and the executor-less, UI-less agent spine omit it. TUI injects the service, while command producers depend only on the registry and any domain they operate. ### Registry contract -A `CommandDefinition` contains a lowercase name without `/`, a non-empty description, an optional unstructured-input hint, and an abortable handler. Registration validates and detaches the metadata, freezes the effective definition, and returns the exact Cordis effect disposer. Duplicate names fail within one layer. Every adapter consuming the registry sees every effective definition; a command plugin that cannot operate in a deployment omits its registration there instead of encoding adapter identities in the shared domain. +A `CommandDefinition` contains a lowercase name without `/`, a non-empty description, an optional unstructured-input hint, and an abortable handler. Registration validates and detaches the metadata, freezes the effective definition, and returns the exact Cordis effect disposer. Duplicate names fail within one layer. Every consumer sees every effective definition; a command plugin that cannot operate in a deployment omits its registration there instead of encoding consumer identities in the shared domain. `list(agent)` returns immutable name-sorted descriptors after scoped shadowing. `find(agent, name)` resolves the effective definition. `execute(agent, line, signal)` parses and runs a known definition, returning a detached `success` or `error` result; invalid syntax and unknown names return `undefined` so the adapter owns its direct error text. @@ -36,46 +36,36 @@ Expected handler failures return `CommandResult.error`. Thrown or malformed resu ### TUI mapping -The TUI registers `help`, `clear`, `cancel`, `reasoning`, `tools`, `redraw`, and `exit` as agent-scoped command definitions instead of switching on strings. Its autocomplete and help view read the live catalog, so plugin commands appear and disappear with their effects. Any submitted line beginning with `/` stays in the command plane; unknown input produces a terminal warning rather than falling through to `Agent.send()` or `Agent.steer()`. +The TUI registers its built-in slash commands as agent-scoped command definitions instead of switching on strings. Its autocomplete and help view read the live catalog, so plugin commands appear and disappear with their effects. Any submitted line beginning with `/` stays in the command plane; unknown input produces a terminal warning rather than falling through to `Agent.send()` or `Agent.steer()`. Each submitted command owns an `AbortController`. TUI disposal aborts outstanding dispatches, removes the local definitions, and waits for the command-producing fiber before completing teardown. -### ACP mapping - -The bridge follows the current [ACP v1 slash-command contract](https://agentclientprotocol.com/protocol/v1/slash-commands). `session/new` and `session/load` emit the exact agent's full `available_commands_update` snapshot; a new session's RPC response introduces its server-generated id before the snapshot is enqueued. Every registry change emits a replacement snapshot for each live session. Names, descriptions, and optional unstructured-input hints map directly to `AvailableCommand`. - -ACP permits a command prompt to contain additional supported content blocks. The bridge applies its ordinary lossless `text` and `resource_link` flattening, then enters the command plane when the result starts with `/`. Unsupported prompt blocks are rejected by the existing capability boundary. Known commands execute directly; unknown or malformed slash input returns a direct error and never reaches the model. Successful text, expected errors, and thrown-failure diagnostics stream as live `agent_message_chunk` output and settle `end_turn`. - -One model prompt or direct command may be in flight per ACP session, independently across sessions. `session/cancel` aborts the direct command when one owns the request; it calls `Agent.cancel()` only for an agent prompt, so cancelling a command cannot destroy unrelated queued or injected agent work. Connection teardown aborts commands and then disposes the owned agents. - ## Testing The registry suite covers syntax boundaries, immutable normalization, runtime metadata validation, deterministic sorting, global and scoped shadowing, duplicate rejection, exact disposal, contained change-notification failures, direct invocation, expected and malformed results, synchronous and asynchronous failure, and every abort timing edge at per-file 100% statement, branch, function, and line coverage. -TUI tests exercise all migrated built-ins, live plugin discovery, help/autocomplete refresh, direct results, unknown-command rejection, raw-input delivery, definition removal, startup rollback, and disposal cancellation. ACP tests use the real SDK connection, agent factory, loop, and JSONL persistence to verify create/load snapshots, dynamic updates, scoped multi-session catalogs, supported-block flattening, direct success/error/failure, unknown-command isolation, cancellation, and the absence of model requests or session messages. The SDK helper suite pins direct-ACP composition. Keyless ACP and terminal snapshots pin the new protocol and rendered transcript shapes. +TUI tests exercise all migrated built-ins, live plugin discovery, help/autocomplete refresh, direct results, unknown-command rejection, raw-input delivery, definition removal, startup rollback, and disposal cancellation. Keyless terminal snapshots pin the rendered help, error, and command-result shapes. ## Alternatives considered -- **Keep adapter-local switches** — rejected because optional plugins cannot contribute discovery and behavior without editing every front door. +- **Keep adapter-local switches** — rejected because optional plugins cannot contribute discovery and behavior without editing the TUI. - **Represent human commands as model tools** — rejected because discovery and direct invocation are human UI behavior; routing through the model adds latency, token cost, and reinterpretation. -- **Put the registry in the core agent spine** — rejected because headless and JSON-RPC agents do not consume it, while the two UI app bundles can compose it explicitly. +- **Put the registry in the core agent spine** — rejected because UI-less front doors do not consume it, while TUI can compose it explicitly. - **Make `dsh-agent-loop` inject commands** — rejected because the loop does not execute or discover human commands. Agent-scoped producers declare the UI dependency in a child plugin instead. - **Attach adapter masks to each definition** — rejected because support is a composition fact, not command-domain state. Every composed adapter exposes a registered command; an incompatible plugin omits registration in that deployment. - **Send unknown slash input to the model** — rejected because typoed or unavailable direct actions must fail predictably rather than change execution planes. - **Persist generic command input and output** — rejected because adapter notices are not model-visible state. A handler that changes durable behavior calls the owning domain API, which records its own events. -- **Restrict ACP commands to one text block** — rejected because ACP v1 permits accompanying content; the bridge already has a lossless accepted-block translation. ## Consequences -- Command producers are ordinary removable plugins, and TUI/ACP share one validated catalog and dispatch contract. +- Command producers are ordinary removable plugins, and TUI consumes their validated catalog and dispatch contract. - Agent-specific definitions retain existing flat scope and shadow semantics without a core-to-UI dependency. - Unknown slash input and command output are deterministic UI behavior with zero direct model tokens. -- ACP clients receive current per-session snapshots after creation, load, registration, and HMR removal. - Direct command cancellation is isolated from model-turn cancellation. ## Known limitations and deferred work -- Input metadata is ACP's current unstructured text hint. Typed forms, argument schemas, and completion providers remain command-owned or require a later protocol extension. -- Generic command output is live-only and is not reconstructed after TUI restart or ACP reconnect. +- Input metadata is limited to an unstructured text hint. Typed forms, argument schemas, and completion providers remain command-owned or require a later registry or consumer extension. +- Generic command output is live-only and is not reconstructed after TUI restart. - Registry cancellation stops awaiting immediately, but external work stops only when a handler cooperates with its signal. -- The headless CLI and JSON-RPC SDK front doors do not expose the command plane; only TUI and ACP consume it. +- The ACP automation server, headless CLI, and JSON-RPC SDK front doors do not expose the command plane; only TUI consumes it. diff --git a/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.zh.md b/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.zh.md index 054ab3a90e..27757f05af 100644 --- a/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.zh.md +++ b/.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.zh.md @@ -6,17 +6,17 @@ Status: implemented ## 问题 -TUI 拥有七个斜杠命令,而 ACP 定义了标准命令目录与调用形态。如果命令名、帮助文本、自动补全、分派和取消都留在各适配器内部,每个新命令都需要修改适配器,可选插件无法贡献命令,两个前端也会逐渐偏离。把斜杠输入当作普通模型提示同样不安全:用户可见的直接操作可能意外消耗 token,或让模型重新解释未知命令。 +TUI 拥有斜杠命令。如果命令名、帮助文本、自动补全、分派和取消都留在适配器内部,每个新命令都需要修改 TUI,可选插件也无法贡献命令。把斜杠输入当作普通模型提示同样不安全:用户可见的直接操作可能意外消耗 token,或让模型重新解释未知命令。 -共享机制必须仍是 UI 关注点,而不是模型工具或智能体循环分支。它还需要精确的逐智能体可见性、可安全 HMR 移除、逐会话 ACP 发现、直接结果渲染和请求作用域取消,同时不会自动把命令文本或输出加入模型历史。 +共享机制必须仍是 UI 关注点,而不是模型工具或智能体循环分支。它还需要精确的逐智能体可见性、可安全 HMR 移除、直接结果渲染和请求作用域取消,同时不会自动把命令文本或输出加入模型历史。 ## 决策 -位于 `packages/ui/commands/` 的 `@deepseek-ai/dsh-commands` 是产品命令注册表。终端与 ACP 应用 bundle(组合包)把它挂载在消费该服务的前端旁,SDK 项目 helper(辅助器)在直接搭建 ACP 时也会生成同一服务;无执行器、无 UI 的智能体 spine(主干)保持独立。TUI 与 ACP 注入该服务,命令生产者只依赖注册表及其操作的领域。 +位于 `packages/ui/commands/` 的 `@deepseek-ai/dsh-commands` 是产品命令注册表。TUI 应用 bundle(组合包)把它挂载在消费该服务的前端旁;[仅面向自动化的 ACP(Agent Client Protocol)应用](../simplification/2026-07-23-acp-automation-only-protocol.md)和无执行器、无 UI 的智能体 spine(主干)都省略该服务。TUI 注入该服务,命令生产者只依赖注册表及其操作的领域。 ### 注册表契约 -`CommandDefinition` 包含不带 `/` 的小写名称、非空描述、可选的非结构化输入提示,以及可取消处理器。注册会校验并分离元数据、冻结有效定义,并返回准确的 Cordis effect disposer(副作用释放器)。同一层中的重复名称会失败。每个消费该注册表的适配器都能看到所有有效定义;若命令插件无法在某种部署中运行,它就不在该部署中注册,而不是把适配器身份编码进共享领域。 +`CommandDefinition` 包含不带 `/` 的小写名称、非空描述、可选的非结构化输入提示,以及可取消处理器。注册会校验并分离元数据、冻结有效定义,并返回准确的 Cordis effect disposer(副作用释放器)。同一层中的重复名称会失败。每个消费方都能看到所有有效定义;若命令插件无法在某种部署中运行,它就不在该部署中注册,而不是把消费方身份编码进共享领域。 `list(agent)` 在作用域遮蔽后返回不可变、按名称排序的描述符。`find(agent, name)` 解析有效定义。`execute(agent, line, signal)` 解析并运行已知定义,返回分离后的 `success` 或 `error` 结果;无效语法和未知名称返回 `undefined`,由适配器拥有直接错误文本。 @@ -36,46 +36,36 @@ TUI 拥有七个斜杠命令,而 ACP 定义了标准命令目录与调用形 ### TUI 映射 -TUI 把 `help`、`clear`、`cancel`、`reasoning`、`tools`、`redraw` 和 `exit` 注册为智能体作用域命令定义,不再对字符串执行 switch。自动补全与帮助视图读取实时目录,因此插件命令会随其副作用出现和消失。任何以 `/` 开头的提交行都留在命令平面;未知输入产生终端警告,不会落入 `Agent.send()` 或 `Agent.steer()`。 +TUI 把内置斜杠命令注册为智能体作用域命令定义,不再对字符串执行 switch。自动补全与帮助视图读取实时目录,因此插件命令会随其副作用出现和消失。任何以 `/` 开头的提交行都留在命令平面;未知输入产生终端警告,不会落入 `Agent.send()` 或 `Agent.steer()`。 每个提交的命令拥有一个 `AbortController`。TUI 释放会中止未完成的分派、移除本地定义,并等待命令生产者 fiber(纤程)后再完成清理。 -### ACP 映射 - -桥接遵循当前的 [ACP v1 斜杠命令契约](https://agentclientprotocol.com/protocol/v1/slash-commands)。`session/new` 与 `session/load` 发出准确智能体的完整 `available_commands_update` 快照;新会话的 RPC 响应会先引入服务端生成的 id,随后快照才会入队。每次注册表变更都会为每个实时会话发出替换快照。名称、描述和可选非结构化输入提示直接映射到 `AvailableCommand`。 - -ACP 允许命令提示携带额外的受支持内容块。桥接应用普通的无损 `text` 与 `resource_link` 扁平化,然后在结果以 `/` 开头时进入命令平面。不支持的提示块由现有能力边界拒绝。已知命令直接执行;未知或格式错误的斜杠输入返回直接错误,绝不会到达模型。成功文本、预期错误和抛出失败的诊断作为实时 `agent_message_chunk` 输出流式发送,并以 `end_turn` 结束请求。 - -每个 ACP 会话同时只能有一个模型提示或直接命令进行中,各会话彼此独立。当直接命令拥有请求时,`session/cancel` 会中止它;只有智能体提示才调用 `Agent.cancel()`,因此取消命令不会销毁无关的排队或注入智能体工作。连接清理会先中止命令,再释放所拥有的智能体。 - ## 测试 注册表测试覆盖语法边界、不可变规范化、运行时元数据校验、确定性排序、全局与作用域遮蔽、重复拒绝、准确释放、变更通知失败隔离、直接调用、预期和格式错误结果、同步与异步失败,以及每种中止时序边沿;该源文件达到逐文件 100% 语句、分支、函数和行覆盖率。 -TUI 测试覆盖全部迁移后的内置命令、实时插件发现、帮助与自动补全刷新、直接结果、未知命令拒绝、原始输入交付、定义移除、启动回滚和释放取消。ACP 测试使用真实 SDK 连接、智能体工厂、循环与 JSONL 持久化,验证创建/加载快照、动态更新、作用域多会话目录、受支持块扁平化、直接成功/错误/失败、未知命令隔离、取消,以及不存在模型请求或会话消息。SDK helper 测试固定直接 ACP 组合。无密钥 ACP 与终端快照固定新的协议和渲染记录形态。 +TUI 测试覆盖全部迁移后的内置命令、实时插件发现、帮助与自动补全刷新、直接结果、未知命令拒绝、原始输入交付、定义移除、启动回滚和释放取消。无密钥终端快照固定渲染后的帮助、错误与命令结果形态。 ## 考虑过的替代方案 -- **保留适配器本地 switch**——不予采纳,因为可选插件无法贡献发现与行为,除非修改每个前端。 +- **保留适配器本地 switch**——不予采纳,因为可选插件无法贡献发现与行为,除非修改 TUI。 - **把人类命令表示为模型工具**——不予采纳,因为发现与直接调用属于人类 UI 行为;经由模型路由会增加延迟、token 成本和重新解释。 -- **把注册表放入核心智能体主干**——不予采纳,因为无头和 JSON-RPC 智能体不消费它,而两个 UI 应用组合包可以显式组合它。 +- **把注册表放入核心智能体主干**——不予采纳,因为无 UI 前端不消费它,而 TUI 可以显式组合它。 - **让 `dsh-agent-loop` 注入 commands**——不予采纳,因为循环不执行也不发现人类命令。智能体作用域生产者改为在子插件中声明 UI 依赖。 - **为每个定义附加适配器掩码**——不予采纳,因为支持能力是组合事实,而不是命令领域状态。每个已组合适配器都暴露已注册命令;不兼容插件不会在该部署中注册。 - **把未知斜杠输入发送给模型**——不予采纳,因为输入错误或不可用的直接操作必须可预测地失败,而不能改变执行平面。 - **持久化通用命令输入与输出**——不予采纳,因为适配器提示不是模型可见状态。改变持久行为的处理器会调用拥有该状态的领域 API,由后者记录自己的事件。 -- **把 ACP 命令限制为单个文本块**——不予采纳,因为 ACP v1 允许附带内容,而桥接已有无损的已接纳块转换。 ## 后果 -- 命令生产者是普通的可移除插件,TUI 与 ACP 共享一个经过校验的目录和分派契约。 +- 命令生产者是普通的可移除插件,TUI 消费其经过校验的目录与分派契约。 - 智能体特定定义保留现有扁平作用域与遮蔽语义,不引入核心到 UI 的依赖。 - 未知斜杠输入与命令输出是确定性 UI 行为,直接模型 token 成本为零。 -- ACP 客户端在创建、加载、注册和 HMR 移除后收到当前的逐会话快照。 - 直接命令取消与模型轮次取消彼此隔离。 ## 已知限制与延期工作 -- 输入元数据仅为 ACP 当前的非结构化文本提示。类型化表单、参数模式和补全提供器仍由命令拥有,或需要后续协议扩展。 -- 通用命令输出仅实时存在,TUI 重启或 ACP 重新连接后不会重建。 +- 输入元数据仅限非结构化文本提示。类型化表单、参数模式和补全提供器仍由命令拥有,或需要后续注册表或消费方扩展。 +- 通用命令输出仅实时存在,TUI 重启后不会重建。 - 注册表取消会立即停止等待,但外部工作只有在处理器配合信号时才会停止。 -- 无头 CLI 与 JSON-RPC SDK 前端不暴露命令平面;只有 TUI 和 ACP 消费它。 +- ACP 自动化服务器、无头 CLI 与 JSON-RPC SDK 前端不暴露命令平面;只有 TUI 消费它。 diff --git a/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.i18n.yaml b/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.i18n.yaml index f28ec1e2b7..8f948d3d45 100644 --- a/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.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 -2026-07-19-same-session-goal-round-driver.md: 34d59456b5a8b54c92aba581da0ff22ea045b626 -2026-07-19-same-session-goal-round-driver.zh.md: dc2afd1ce18a45964bc1db04121211a9958445f3 +2026-07-19-same-session-goal-round-driver.md: d23af9a9b05d60d2dccad095455524844f1185b9 +2026-07-19-same-session-goal-round-driver.zh.md: f4f0cd6fd575d14427025bdbd8d10bc90e25f780 diff --git a/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.md b/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.md index 34d59456b5..d23af9a9b0 100644 --- a/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.md +++ b/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.md @@ -70,7 +70,7 @@ An inbox acceptance can win the microtask race immediately before plugin unload The unit suite uses the real agent loop and session service with only the model scripted. It covers exact sequential admission and cap enforcement, load/resume inertness, every outcome classification, rate limiting, request errors, max tokens, downstream prompt veto, pre-admission and in-flight cancellation, unrelated-human cancellation, failed-pause fallback, human-input ordering, queued and downstream revision races, forged goal attribution, failed mutation and turn checkpoints including a later one-shot injection, scheduler and custom-agent failures, session-start reset, exact lifecycle retirement, and queued/running plugin teardown. The new driver source has per-file 100% statement, branch, function, and line coverage. -A keyless ACP snapshot mounts the shipped editor app with the real goal domain, goal tools, goal driver, agent loop, persistence, and replay adapter through `cordis.yml`. One human turn creates and inspects a two-round goal, the first automatic turn stops normally, and ACP cancellation of a deliberately stalled second round records a durable pause. The normalized wire transcript and external JSONL assertions prove one session, round sources `1, 2`, the lifecycle mutation, and exact replay accounting without using `echo-agent` as an application surrogate. +A keyless ACP snapshot mounts the shipped automation app with the real goal domain, goal tools, goal driver, agent loop, persistence, and replay adapter through `cordis.yml`. One human-originated turn creates and inspects a two-round goal, the first automatic turn stops normally, and ACP cancellation of a deliberately stalled second round records a durable pause. The normalized wire transcript and external JSONL assertions prove one session, round sources `1, 2`, the lifecycle mutation, and exact replay accounting without using `echo-agent` as an application surrogate. The core cancellation test proves notification order and containment: observers run only for effective cancellation, can queue replacement work before the inbox clear, cannot veto later observers by throwing, and an idle call emits nothing. diff --git a/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.zh.md b/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.zh.md index dc2afd1ce1..f4f0cd6fd5 100644 --- a/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.zh.md +++ b/.agents/notes/implemented/feature/2026-07-19-same-session-goal-round-driver.zh.md @@ -70,7 +70,7 @@ Status: implemented 单元测试使用真实 agent loop 与会话服务,只对模型编写脚本。覆盖内容包括精确连续接纳和上限执行、加载与恢复的惰性、所有结果分类、限流、请求错误、最大 token、下游提示词否决、接纳前与执行中取消、无关人类工作取消、暂停失败回退、人类输入排序、排队时与下游修订竞争、伪造目标来源、变更与轮次检查点失败(包括后续一次性注入)、调度器与自定义 agent 失败、会话启动重置、精确生命周期退出,以及排队中和运行中的插件卸载。新驱动器源码达到逐文件 100% 语句、分支、函数和行覆盖率。 -无密钥 ACP 快照通过 `cordis.yml` 挂载已发布的编辑器应用,以及真实目标领域、目标工具、目标驱动器、agent loop、持久化和回放适配器。一个人类轮次创建并检查一个两回合目标;第一个自动轮次正常停止,ACP 随后取消刻意停滞的第二个回合并记录持久暂停。规范化线协议和外部 JSONL 断言证明只有一个会话、回合来源依次为 `1, 2`、生命周期变更与回放计数精确,并且没有把 `echo-agent` 当作应用替身。 +无密钥 ACP 快照通过 `cordis.yml` 挂载已发布的自动化应用,以及真实目标领域、目标工具、目标驱动器、agent loop、持久化和回放适配器。一个源自人类的轮次创建并检查一个两回合目标;第一个自动轮次正常停止,ACP 随后取消刻意停滞的第二个回合并记录持久暂停。规范化线协议和外部 JSONL 断言证明只有一个会话、回合来源依次为 `1, 2`、生命周期变更与回放计数精确,并且没有把 `echo-agent` 当作应用替身。 核心取消测试固定通知顺序与隔离:只有有效取消才会通知;观察者可以在清空收件箱前排入替代工作;抛错不能阻止后续观察者;空闲调用不会发出事件。 diff --git a/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.i18n.yaml b/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.i18n.yaml index 0f1bead590..190a2b773f 100644 --- a/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.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 -2026-07-20-code-mode-typed-tool-returns.md: 29f139a7e965de3a374d195ecc205210e6ae7e93 -2026-07-20-code-mode-typed-tool-returns.zh.md: 431c0b1717c6783771255ce8291c241f8f92c30b +2026-07-20-code-mode-typed-tool-returns.md: 1b5cbb9f4664c371a03cfefd079d5dc531711b51 +2026-07-20-code-mode-typed-tool-returns.zh.md: 70fd9ee72803c5cd2fa228a1d38ddf7ae47a4814 diff --git a/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.md b/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.md index 29f139a7e9..1b5cbb9f46 100644 --- a/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.md +++ b/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.md @@ -75,7 +75,7 @@ Dynamic Cordis mounting follows the same rule: `cordis_mount` returns `{ id, plu Nested dispatch keeps the existing bounded `tool/code-dispatch.resultSummary` for diagnostics but does not persist canonical values. `tool/result` continues to persist only rendered content, error, and optional metadata. This is deliberately not a session-format change, so `SESSION_FORMAT_VERSION` remains unchanged and replay cannot recreate intermediate program values. -The opaque `exec.parent` token marks nested calls. Presentation metadata and generic or tool-owned spill projections skip those calls because they have no direct result card and their canonical values never enter context. The outer `run_code` call alone produces one card and may spill its final post-policy presentation; `run_code` intentionally declares neither a result presenter nor presentation metadata, so ACP and TUI complete the card through their generic raw-content fallback using durable `tool/result.content`. +The opaque `exec.parent` token marks nested calls. Presentation metadata and generic or tool-owned spill projections skip those calls because they have no direct result card and their canonical values never enter context. The outer `run_code` call alone produces one card and may spill its final post-policy presentation; `run_code` intentionally declares neither a result presenter nor presentation metadata, so UI adapters complete the card through their generic raw-content fallback using durable `tool/result.content`. ## Testing @@ -95,7 +95,7 @@ Keyless real-worker integration tests pin the two handle workflows that prose re ## Consequences -Code programs can compose tools through stable values instead of reverse-engineering Native prose. Native and Both Mode retain their existing text and editor presentation, while Code Mode receives output-schema types and exact runtime JSON. Tool authors must treat the canonical value as their programmatic API and put display-only formatting in the renderer. +Code programs can compose tools through stable values instead of reverse-engineering Native prose. Native and Both Mode retain their existing text and UI presentation, while Code Mode receives output-schema types and exact runtime JSON. Tool authors must treat the canonical value as their programmatic API and put display-only formatting in the renderer. The worker performs bounded-depth flat-wire transport and lossless validation but does not make intermediate values cheap or durable. Outer overflow is an explicit failed run, and error handling remains intentionally human-guided rather than a versioned code union. diff --git a/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.zh.md b/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.zh.md index 431c0b1717..70fd9ee728 100644 --- a/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.zh.md +++ b/.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.zh.md @@ -75,7 +75,7 @@ Code Mode 通过运行时请求中的 `{ name: "ToolCallError", memberNameProper 嵌套分发会为诊断保留既有的有界 `tool/code-dispatch.resultSummary`,但不会持久化规范值。`tool/result` 继续只持久化渲染后的内容、错误和可选元数据。这并非会话格式变更,因此 `SESSION_FORMAT_VERSION` 保持不变,回放也无法重建程序的中间值。 -不透明的 `exec.parent` token 用于标识嵌套调用。由于这些调用没有直接对应的结果卡片,而且其规范值永远不会进入上下文,展示元数据以及通用或工具自有的输出落盘投影都会跳过它们。只有外层 `run_code` 调用会生成一张卡片,并且可能将 post-policy 处理后的最终展示写入落盘文件;`run_code` 有意既不声明结果展示器,也不声明展示元数据,因此 ACP 和 TUI 通过其通用的原始内容回退机制,使用持久化的 `tool/result.content` 补全该卡片。 +不透明的 `exec.parent` token 用于标识嵌套调用。由于这些调用没有直接对应的结果卡片,而且其规范值永远不会进入上下文,展示元数据以及通用或工具自有的输出落盘投影都会跳过它们。只有外层 `run_code` 调用会生成一张卡片,并且可能将 post-policy 处理后的最终展示写入落盘文件;`run_code` 有意既不声明结果展示器,也不声明展示元数据,因此 UI 适配器会通过通用的原始内容回退机制,使用持久化的 `tool/result.content` 补全该卡片。 ## 测试 @@ -95,7 +95,7 @@ Code Mode 通过运行时请求中的 `{ name: "ToolCallError", memberNameProper ## 影响 -Code Mode 程序可以通过稳定值组合工具,无需逆向解析 Native 自然语言。Native 和 Both Mode 保留现有文本与编辑器展示,Code Mode 则获得输出 schema 类型和精确的运行时 JSON。工具作者必须把规范值视为程序化 API,并将仅用于展示的格式化放入渲染器。 +Code Mode 程序可以通过稳定值组合工具,无需逆向解析 Native 自然语言。Native 和 Both Mode 保留现有文本与 UI 展示,Code Mode 则获得输出 schema 类型和精确的运行时 JSON。工具作者必须把规范值视为程序化 API,并将仅用于展示的格式化放入渲染器。 worker 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。外层输出溢出会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。 diff --git a/.agents/notes/implemented/feature/2026-07-21-cross-session-references.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-cross-session-references.i18n.yaml index 9c0118a72d..b1f73ed15a 100644 --- a/.agents/notes/implemented/feature/2026-07-21-cross-session-references.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-21-cross-session-references.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 -2026-07-21-cross-session-references.md: bfa015b24cda6c8651829b6a7f0800326da5b502 -2026-07-21-cross-session-references.zh.md: e8e99124f7e2ccfe9fbe97323c17143372017562 +2026-07-21-cross-session-references.md: fc084b36e7920a72efff0f363278d24eaebc4c69 +2026-07-21-cross-session-references.zh.md: fe4a876b5265fa7ad298adf3b829bcec70e878e8 diff --git a/.agents/notes/implemented/feature/2026-07-21-cross-session-references.md b/.agents/notes/implemented/feature/2026-07-21-cross-session-references.md index bfa015b24c..fc084b36e7 100644 --- a/.agents/notes/implemented/feature/2026-07-21-cross-session-references.md +++ b/.agents/notes/implemented/feature/2026-07-21-cross-session-references.md @@ -6,13 +6,13 @@ English | [中文](2026-07-21-cross-session-references.zh.md) ## Problem -TUI and ACP users need to bring relevant work from another conversation into one new message without resuming, forking, or granting the source transcript authority over the current session. The harness already exposes exact session enumeration and raw event inspection, but every host independently parsing logs would duplicate compaction folding, provenance filtering, size limits, error behavior, and persistence. Encoding host markup directly into the agent message contract would also bind the core loop to one UI syntax. +TUI users need to bring relevant work from another conversation into one new message without resuming, forking, or granting the source transcript authority over the current session. The harness already exposes exact session enumeration and raw event inspection, but every host independently parsing logs would duplicate compaction folding, provenance filtering, size limits, error behavior, and persistence. Encoding host markup directly into the agent message contract would also bind the core loop to one UI syntax. ## Decision `@deepseek-ai/dsh-session-reference` is one context consumer service at `ctx.sessionReferences`. Hosts normalize their protocol into `SessionReferenceInput[]`, call `prepare()` before enqueue, and pass the returned contexts through the generic `SendOptions.contexts` boundary. Core agent packages know only that one queued message may carry frozen `HookContext[]`; they do not parse session URIs or read another log. -`dsh-session:<base64url(JSON.stringify(sessionId))>` is the canonical host-independent identifier. JSON string encoding precedes base64url so quotes, slashes, backslashes, Unicode, newlines, and every other JavaScript string value round-trip without delimiter ambiguity. TUI renders that URI inside `@[label](uri)` and ACP uses standard `resource_link`; text-only clients may use the same inline mention. Explicit Markdown mentions and resource links reject malformed URIs. Bare text becomes a reference only for a non-empty base64url-shaped payload, whose decode must still be canonical; empty or punctuation-only uses remain ordinary discussion text. +`dsh-session:<base64url(JSON.stringify(sessionId))>` is the canonical host-independent identifier. JSON string encoding precedes base64url so quotes, slashes, backslashes, Unicode, newlines, and every other JavaScript string value round-trip without delimiter ambiguity. TUI renders that URI inside `@[label](uri)`; text-only clients may use the same inline mention. Explicit Markdown mentions reject malformed URIs. Bare text becomes a reference only for a non-empty base64url-shaped payload, whose decode must still be canonical; empty or punctuation-only uses remain ordinary discussion text. The service uses `ctx.sessionQuery.readSurface(sessionId)`, which loads one live-preferred corpus observation, folds it with the session package's canonical surface algorithm, and returns a detached header, capture seq, and current nodes. FTS is not a dependency: v1 discovery filters only id and cwd, and future title/body search can replace the candidate layer without changing reference identity or preparation. @@ -28,13 +28,13 @@ One aggregated context is serialized as JSON beneath a fixed untrusted-backgroun `send()` and `steer()` snapshot content, resolved source, and contexts together as one deeply frozen lossless-JSON inbox record. Synthetic `inject()` accepts source and model-hidden metadata but not attached contexts, which belong to inbox messages. A claimed ordinary message exposes its attached contexts as the default `agent/prompt-submit` additional contexts; a block writes neither user message nor contexts. The waterfall's returned allow is authoritative, so a listener wrapping `next()` preserves downstream content and contexts unless it intentionally replaces them. After admission, absent or `separate` placement writes an independent `context/message`, while `prompt-prefix` placement bakes context and the effective request into one prompt event. Drained steering bypasses `agent/prompt-submit` but applies the same placement split. Late steering retains the same record when converted to queued input, while cancellation, disposal, and terminal discard drop message and contexts together. `agent/queued` reports the frozen contexts so the observation event describes the complete retained item. -This preserves host driving semantics: TUI decides `send()` versus `steer()` from the agent state after preparation, so only its queued path dispatches UserPromptSubmit hooks; ACP continues to call `send()` once per `session/prompt`. Reference preparation is not a new steering protocol and does not create a turn by itself. +This preserves host driving semantics: TUI decides `send()` versus `steer()` from the agent state after preparation, so only its queued path dispatches UserPromptSubmit hooks. Reference preparation is not a new steering protocol and does not create a turn by itself. ## Host adapters TUI combines session candidates with the existing `@` file provider. Each candidate displays the latest folded session title and falls back to the session id; lookup follows the editor's cancellation signal, and session id, cwd, and mention labels escape external terminal controls while the canonical URI retains the original id. TUI prepares only submissions containing structured mentions, disables duplicate submit while awaiting snapshots, restores failed input, renders the prompt envelope's display content as the user message, and renders its session-reference metadata as a compact source list instead of exposing the complete JSON in the terminal. -ACP detects direct slash commands from ordinary prompt flattening before extracting `dsh-session:` resource links and canonical inline mentions, so URI-shaped command arguments remain opaque while ordinary resource-link rendering is preserved. Standard `session/list` exposes each loadable session's folded title and, when references are mounted, a canonical URI under `_meta["deepseek-harness/sessionReference"]`; a client can use `title ?? sessionId` as the resource-link name. A valid reference without the optional service returns a capability-unavailable RPC error, and preparation failure occurs before the in-flight turn slot and agent send. A preparation-specific abort owner makes `session/cancel` and bridge teardown stop pending reads. Picker UI remains an ACP client responsibility because ACP does not define a cross-session mention menu. +The [automation-only ACP transport](../simplification/2026-07-23-acp-automation-only-protocol.md) deliberately does not mount session-query or session-reference services. ## Budget and retention @@ -43,8 +43,8 @@ Each of at most three references is independently capped at 65,536 UTF-8 bytes b ## Alternatives considered - **Wait for SQLite FTS5** — rejected because snapshot correctness requires exact id reads and canonical surface folding, not content search. FTS improves discovery only. -- **Put mention syntax in `Agent.send()`** — rejected because it would make the core protocol parse TUI/ACP presentation and prevent typed non-text hosts from sharing the semantic layer. -- **Implement references inside TUI and ACP separately** — rejected because projection, security warning, retention, and persistence would drift across hosts. +- **Put mention syntax in `Agent.send()`** — rejected because it would make the core protocol parse one host's presentation syntax and prevent typed non-text hosts from sharing the semantic layer. +- **Implement references separately in each host** — rejected because projection, security warning, retention, and persistence would drift across hosts. - **Place a separate user-role context message beside the prompt** — rejected because two adjacent user messages weaken the prompt's deictic binding: in `@foo what does this session discuss?`, the model may resolve “this session” as the current conversation instead of the referenced snapshot. - **Bake the prefix host-side before `send()`** — rejected because `agent/prompt-submit` must inspect and rewrite only the direct prompt. The effective prompt and attached contexts meet only after admission in AgentLoop, which can apply an `allow.content` rewrite consistently to both combined model content and `envelope.displayContent`; earlier host assembly would expose snapshot bytes to the hook or let those two views diverge. - **Replay the raw source log or restore shadowed events** — rejected because compact defines the current model surface and may intentionally retire sensitive or expensive history. @@ -53,8 +53,8 @@ Each of at most three references is independently capped at 65,536 UTF-8 bytes b ## Verification -Unit and integration coverage pins URI round-trips and text-boundary punctuation, explicit malformed references, title-aware candidate ranking, terminal-control escaping, projection exclusions, non-recursive prompt-envelope projection, backend-independent compact checkpoints, tag-safe framing, deduplication, self-reference, count limits, all-or-nothing reads, prompt cancellation against a non-settling storage read, independent per-source byte retention, frozen message ownership, prompt blocking, send/steer placement, title isolation, missing capability, title-aware ACP session listing, ordinary ACP resource links, opaque ACP command arguments, and compact TUI/ACP replay. A keyless TUI snapshot runs the real agent loop: the source surface replaces old user/assistant history with a compact checkpoint, the target submits a mention, and the captured model request contains one user message ordered as snapshot, request delimiter, and current prompt, without either shadowed string. +Unit and integration coverage pins URI round-trips and text-boundary punctuation, explicit malformed references, title-aware candidate ranking, terminal-control escaping, projection exclusions, non-recursive prompt-envelope projection, backend-independent compact checkpoints, tag-safe framing, deduplication, self-reference, count limits, all-or-nothing reads, prompt cancellation against a non-settling storage read, independent per-source byte retention, frozen message ownership, prompt blocking, send/steer placement, title isolation, missing capability, and compact TUI replay. A keyless TUI snapshot runs the real agent loop: the source surface replaces old user/assistant history with a compact checkpoint, the target submits a mention, and the captured model request contains one user message ordered as snapshot, request delimiter, and current prompt, without either shadowed string. ## Consequences -The new plugin is the stable semantic boundary and adds no persistence schema, event type, FTS dependency, source subscription, or compact shadow access. Standard TUI/ACP demo bundles mount it explicitly and expose its count and per-source byte limits in their own config; custom hosts remain unchanged until they mount the service and adapt their input. Reference contexts increase target history size within configured bounds and can later be summarized by ordinary target compaction, after which the source session is irrelevant. +The new plugin is the stable semantic boundary and adds no persistence schema, event type, FTS dependency, source subscription, or compact shadow access. The standard TUI demo bundle mounts it explicitly and exposes its count and per-source byte limits in its config; custom hosts remain unchanged until they mount the service and adapt their input. Reference contexts increase target history size within configured bounds and can later be summarized by ordinary target compaction, after which the source session is irrelevant. diff --git a/.agents/notes/implemented/feature/2026-07-21-cross-session-references.zh.md b/.agents/notes/implemented/feature/2026-07-21-cross-session-references.zh.md index e8e99124f7..fe4a876b52 100644 --- a/.agents/notes/implemented/feature/2026-07-21-cross-session-references.zh.md +++ b/.agents/notes/implemented/feature/2026-07-21-cross-session-references.zh.md @@ -6,13 +6,13 @@ Status: implemented ## 问题 -TUI 与 ACP(Agent Client Protocol)用户需要把另一场对话中的相关工作带入一条新消息,但不恢复、不 fork,也不让源 transcript(文本记录)对当前会话拥有权威性。harness 已经提供准确的会话枚举与原始事件检查,但若每个宿主都独立解析日志,就会重复实现压缩(compaction)折叠、来源过滤、大小限制、错误行为和持久化。把宿主标记直接编码进 agent(智能体)消息契约,还会让核心循环绑定某一种 UI 语法。 +TUI 用户需要把另一场对话中的相关工作带入一条新消息,但不恢复、不 fork,也不让源 transcript(文本记录)对当前会话拥有权威性。harness 已经提供准确的会话枚举与原始事件检查,但若每个宿主都独立解析日志,就会重复实现压缩(compaction)折叠、来源过滤、大小限制、错误行为和持久化。把宿主标记直接编码进 agent(智能体)消息契约,还会让核心循环绑定某一种 UI 语法。 ## 决策 `@deepseek-ai/dsh-session-reference` 是注册在 `ctx.sessionReferences` 上的单一上下文消费服务。宿主先把各自的协议规范化为 `SessionReferenceInput[]`,在入队前调用 `prepare()`,再通过通用的 `SendOptions.contexts` 边界传递返回的上下文。核心 agent 包只知道一条排队消息可以携带已冻结的 `HookContext[]`;它们既不解析会话 URI,也不读取其他日志。 -`dsh-session:<base64url(JSON.stringify(sessionId))>` 是与宿主无关的规范标识符。系统先执行 JSON 字符串编码,再执行 base64url 编码,因此引号、正斜杠、反斜杠、Unicode、换行符以及其他任意 JavaScript 字符串值都能无损往返,不会因分隔符产生歧义。TUI 把该 URI 渲染到 `@[label](uri)` 中,ACP 使用标准 `resource_link`;纯文本客户端可以使用同一种行内提及标记。显式 Markdown 提及标记与资源链接会拒绝格式错误的 URI。裸文本只有在负载非空且形状符合 base64url 时才会成为引用,而且解码过程仍须通过规范性校验;空负载或只含标点符号的用法仍按普通讨论文本处理。 +`dsh-session:<base64url(JSON.stringify(sessionId))>` 是与宿主无关的规范标识符。系统先执行 JSON 字符串编码,再执行 base64url 编码,因此引号、正斜杠、反斜杠、Unicode、换行符以及其他任意 JavaScript 字符串值都能无损往返,不会因分隔符产生歧义。TUI 把该 URI 渲染到 `@[label](uri)` 中;纯文本客户端可以使用同一种行内提及标记。显式 Markdown 提及标记会拒绝格式错误的 URI。裸文本只有在负载非空且形状符合 base64url 时才会成为引用,而且解码过程仍须通过规范性校验;空负载或只含标点符号的用法仍按普通讨论文本处理。 该服务使用 `ctx.sessionQuery.readSurface(sessionId)`:它优先从实时会话加载一次语料观察结果,使用会话包的规范表层算法执行折叠,并返回与源数据分离的会话头、捕获序号和当前节点。FTS 不是功能依赖:v1 的候选发现只按 id 和 cwd 过滤;未来的标题或正文搜索可以替换候选层,而无需改变引用标识或准备过程。 @@ -28,13 +28,13 @@ TUI 与 ACP(Agent Client Protocol)用户需要把另一场对话中的相关 `send()` 与 `steer()` 会把内容、解析后的来源和上下文一起快照为一条深度冻结、无损 JSON 的收件箱记录。合成的 `inject()` 接受来源和模型不可见的元数据,但不接受附加上下文,因为上下文属于收件箱消息。普通消息被认领后,其附带的上下文会作为 `agent/prompt-submit` 的默认附加上下文公开;提示词被阻止时,系统既不写入用户消息,也不写入上下文。waterfall(瀑布式事件)返回的 allow 结果具有最终权威性,因此监听器包装 `next()` 时会保留下游内容与上下文,除非它有意替换这些值。消息被接纳后,未指定放置方式或指定为 `separate` 时会写入独立的 `context/message`;指定为 `prompt-prefix` 时则会把上下文与最终生效的请求合并写入同一个提示词事件。排空 steering 消息时会绕过 `agent/prompt-submit`,但采用相同的放置方式分流。延迟到达的 steering 转换为排队输入时保留同一条记录;取消、dispose(资源释放)和到达终止态后的丢弃则会同时丢弃消息与上下文。`agent/queued` 会报告已冻结的上下文,使观察事件能够描述完整的保留项。 -这保留了宿主的驱动语义:TUI 在准备完成后根据 agent 状态决定调用 `send()` 还是 `steer()`,因此只有它的排队路径才会分派 UserPromptSubmit 钩子;ACP 则继续调用 `send()`,每个 `session/prompt` 调用一次。引用准备过程不是新的 steering 协议,本身也不会创建轮次。 +这保留了宿主的驱动语义:TUI 在准备完成后根据 agent 状态决定调用 `send()` 还是 `steer()`,因此只有它的排队路径才会分派 UserPromptSubmit 钩子。引用准备过程不是新的 steering 协议,本身也不会创建轮次。 ## 宿主适配器 TUI 把会话候选与现有 `@` 文件提供方组合在一起。每个候选项显示最新折叠后的会话标题,没有标题时回退到 session id。候选查询遵循编辑器的取消信号;session id、cwd 和提及标签中的外部终端控制字符会被转义,但规范 URI 仍保留原始 id。TUI 只准备包含结构化提及标记的提交;等待快照时禁用重复提交;失败时恢复输入;它把提示词封套的显示内容渲染为用户消息,并把其中的会话引用元数据渲染为精简的来源列表,不在终端中暴露完整 JSON。 -ACP 先从普通提示词扁平化结果中检测直接斜杠命令,再提取 `dsh-session:` 资源链接和规范的行内提及标记,因此形如 URI 的命令参数保持不透明,同时保留普通资源链接的渲染方式。标准 `session/list` 会公开每个可加载会话折叠后的标题;挂载会话引用功能时,还会在 `_meta["deepseek-harness/sessionReference"]` 下公开规范 URI。客户端可以使用 `title ?? sessionId` 作为资源链接名称。若引用有效但可选服务未挂载,系统会返回「功能不可用」RPC 错误;准备失败会发生在占用进行中轮次槽位并调用 agent send 之前。引用准备过程单独拥有中止控制权,因此 `session/cancel` 和桥接释放都能停止待处理的读取。选择器 UI 仍由 ACP 客户端负责,因为 ACP 未定义跨会话提及菜单。 +[仅面向自动化的 ACP(Agent Client Protocol)传输层](../simplification/2026-07-23-acp-automation-only-protocol.md)有意不挂载会话查询或会话引用服务。 ## 预算与保留策略 @@ -43,8 +43,8 @@ ACP 先从普通提示词扁平化结果中检测直接斜杠命令,再提取 ## 考虑过的替代方案 - **等待 SQLite FTS5**:不予采纳,因为快照正确性依赖按准确 id 读取和规范表层折叠,而不是内容搜索。FTS 只改进候选发现。 -- **把提及标记语法放入 `Agent.send()`**:不予采纳,因为这会迫使核心协议解析 TUI/ACP 的表现层,并阻止带类型的非文本宿主复用同一语义层。 -- **在 TUI 和 ACP 中分别实现引用**:不予采纳,因为投影、安全警告、保留策略和持久化会在不同宿主之间逐渐偏离。 +- **把提及标记语法放入 `Agent.send()`**:不予采纳,因为这会迫使核心协议解析某个宿主的展示语法,并阻止带类型的非文本宿主复用同一语义层。 +- **在每个宿主中分别实现引用**:不予采纳,因为投影、安全警告、保留策略和持久化会在不同宿主之间逐渐偏离。 - **在提示词旁放置单独的用户角色上下文消息**:不予采纳,因为相邻的两条用户消息会削弱提示词的指示语绑定:在 `@foo what does this session discuss?` 中,模型可能把「this session」解析为当前对话,而不是被引用的快照。 - **在调用 `send()` 前由宿主合并前缀**:不予采纳,因为 `agent/prompt-submit` 必须只检查和改写直接提示词。最终生效的提示词与附加上下文只有在 AgentLoop 接纳后才汇合;此时 AgentLoop 可以把 `allow.content` 改写一致应用于合并后的模型内容和 `envelope.displayContent`。若由宿主更早组装,就会向该钩子暴露快照字节,或使这两个视图发生偏离。 - **回放原始源日志或恢复被遮蔽的事件**:不予采纳,因为压缩定义了当前模型表层,并且可能有意淘汰敏感或开销高昂的历史内容。 @@ -53,8 +53,8 @@ ACP 先从普通提示词扁平化结果中检测直接斜杠命令,再提取 ## 验证 -单元与集成测试覆盖 URI 无损往返与文本边界标点、显式格式错误的引用、会考虑标题的候选排序、终端控制字符转义、投影排除规则、提示词封套的非递归投影、与后端无关的压缩检查点、标签安全封套、去重、自引用、数量限制、读取的全有或全无、存储读取不结束时取消提示词、逐源独立字节保留、冻结的消息所有权、提示词阻止、send/steer 放置方式、标题隔离、功能缺失、包含标题信息的 ACP 会话列表、普通 ACP 资源链接、不透明的 ACP 命令参数,以及精简的 TUI/ACP 回放。无密钥 TUI 快照会运行真实的 agent loop(智能体循环):源表层用一个压缩检查点替换旧的用户/assistant 历史,目标会话提交一个提及标记,捕获到的模型请求只包含一条用户消息,其中依次为快照、请求分隔符和当前提示词,并且不包含任一被遮蔽的字符串。 +单元与集成测试覆盖 URI 无损往返与文本边界标点、显式格式错误的引用、会考虑标题的候选排序、终端控制字符转义、投影排除规则、提示词封套的非递归投影、与后端无关的压缩检查点、标签安全封套、去重、自引用、数量限制、读取的全有或全无、存储读取不结束时取消提示词、逐源独立字节保留、冻结的消息所有权、提示词阻止、send/steer 放置方式、标题隔离、功能缺失和精简的 TUI 回放。无密钥 TUI 快照会运行真实的 agent loop(智能体循环):源表层用一个压缩检查点替换旧的用户/assistant 历史,目标会话提交一个提及标记,捕获到的模型请求只包含一条用户消息,其中依次为快照、请求分隔符和当前提示词,并且不包含任一被遮蔽的字符串。 ## 后果 -新插件构成稳定的语义边界,不会新增持久化 schema、事件类型、FTS 依赖、源会话订阅或对压缩所遮蔽内容的访问。标准 TUI/ACP 演示组合包会显式挂载它,并在各自的配置中暴露引用数量和逐源字节上限;自定义宿主在挂载该服务并适配输入前保持不变。引用上下文会在配置的界限内增大目标历史,随后可由目标会话的普通压缩进行摘要;完成压缩后,源会话便不再相关。 +新插件构成稳定的语义边界,不会新增持久化 schema、事件类型、FTS 依赖、源会话订阅或对压缩所遮蔽内容的访问。标准 TUI 演示组合包会显式挂载它,并在自身配置中暴露引用数量和逐源字节上限;自定义宿主在挂载该服务并适配输入前保持不变。引用上下文会在配置的界限内增大目标历史,随后可由目标会话的普通压缩进行摘要;完成压缩后,源会话便不再相关。 diff --git a/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.i18n.yaml index 929a802080..2dee4d6261 100644 --- a/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.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 -2026-07-21-log-backed-session-titles.md: 183aa6909fecffdaf18c77c2a66fbc38c67c2d2c -2026-07-21-log-backed-session-titles.zh.md: c6a0c2ce2ad4b2cddec2ada36f655fe55adb143b +2026-07-21-log-backed-session-titles.md: 4cf238a278a4eec7b894a0fcfb0f2ac464325bb0 +2026-07-21-log-backed-session-titles.zh.md: 933cc14eb245581c128cb18055df726174f953ec diff --git a/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.md b/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.md index 183aa6909f..4cf238a278 100644 --- a/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.md +++ b/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.md @@ -40,7 +40,7 @@ Automatic provider failures are nonfatal warnings and retain the latest title. E A fork inherits seed title events unchanged, like the rest of its source log. The first-message provider does not automatically retitle a fork. The all-messages provider may append a child-owned revision after a later child prompt, using inherited and new eligible messages. -`ctx.sessionQuery.readTitle()` folds one live-preferred or persisted log without loading titles during `listSessions()`. ACP maps the event to `session_info_update` during both live streaming and load replay, using the event timestamp for `updatedAt`. The TUI uses the latest title as its header subtitle and sets the terminal window title to `<session title> — <configured product title>` after terminal-safe rendering. The Web host folds the same log state into a validated mux control frame after each attached-session subscription baseline and immediately after forwarding a live raw title event. The browser retains only newer title event seqs even when the control frame precedes list or session-instance creation; sidebar labels, search, breadcrumbs, and the browser title then react to the projected revision. `session.list` remains metadata-only, so a cold persisted session uses the cwd basename or id until opening or resuming it attaches the log. The browser title uses `<session title> — <existing HTML title>` only for a selected titled session and otherwise preserves the product title. A synthetic title turn remains a completed durability boundary for the metadata write; consumers reporting agent completion use the core `findLastMessageTurnEnd()` fold so a later title, injection, or other plugin-owned turn cannot replace the preceding message-triggered outcome. +`ctx.sessionQuery.readTitle()` folds one live-preferred or persisted log without loading titles during `listSessions()`. The TUI uses the latest title as its header subtitle and sets the terminal window title to `<session title> — <configured product title>` after terminal-safe rendering. The Web host folds the same log state into a validated mux control frame after each attached-session subscription baseline and immediately after forwarding a live raw title event. The browser retains only newer title event seqs even when the control frame precedes list or session-instance creation; sidebar labels, search, breadcrumbs, and the browser title then react to the projected revision. `session.list` remains metadata-only, so a cold persisted session uses the cwd basename or id until opening or resuming it attaches the log. The browser title uses `<session title> — <existing HTML title>` only for a selected titled session and otherwise preserves the product title. A synthetic title turn remains a completed durability boundary for the metadata write; consumers reporting agent completion use the core `findLastMessageTurnEnd()` fold so a later title, injection, or other plugin-owned turn cannot replace the preceding message-triggered outcome. ## Alternatives considered @@ -54,7 +54,7 @@ A fork inherits seed title events unchanged, like the rest of its source log. Th ## Consequences -- Titles survive JSONL and SQLite persistence, replay through ACP, and follow fork inheritance without a separate mutable record. +- Titles survive JSONL and SQLite persistence, replay, and fork inheritance without a separate mutable record. - Web title delivery stays incremental and log-backed without a title index or persisted-list scan; cold list rows improve after attach. - A fallback appears immediately. Each fresh Web session adds one first-message auxiliary call; other compositions choose whether better titles justify model cost and whether later prompts should retitle a session. - Auxiliary request records and late accepted titles consume event seqs and may create balanced zero-step turns, so persistence exposes both attempted dispatches and accepted updates even though model history and KV-cache identity do not change. diff --git a/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.zh.md b/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.zh.md index c6a0c2ce2a..933cc14eb2 100644 --- a/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.zh.md +++ b/.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.zh.md @@ -40,7 +40,7 @@ Status: implemented 与源日志的其他部分相同,fork 会原样继承作为种子的标题事件。首消息提供方不会自动为 fork 重新生成标题。全部消息提供方可以在子会话出现后续提示词后追加一项归子会话所有的修订,并使用继承的合格消息和新增的合格消息。 -`ctx.sessionQuery.readTitle()` 会折叠一份实时优先或已持久化的日志,而不会在 `listSessions()` 期间加载标题。ACP(Agent Client Protocol)会在实时流式输出和加载回放期间把该事件映射到 `session_info_update`,并使用事件时间戳作为 `updatedAt`。TUI 使用最新标题作为其标题栏副标题,并在完成终端安全渲染后,将终端窗口标题设置为 `<session title> — <configured product title>`。Web host 会在每个已附加会话的订阅基线之后,以及转发实时原始标题事件后立即,将同一份日志状态折叠为经过校验的 mux 控制帧。即使控制帧先于列表或会话实例创建抵达,浏览器也只保留标题事件 seq 较新的版本;侧边栏标签、搜索、面包屑和浏览器标题会随投影后的修订更新。`session.list` 仍只包含元数据,因此尚未打开的持久化会话会继续以 cwd 基名或 id 作为回退,直至打开或恢复会话时附加其日志。浏览器仅在选中已有标题的会话时将标题设置为 `<session title> — <existing HTML title>`,否则保留产品标题。合成标题轮次本身仍会完成,并作为元数据写入的持久性边界;报告 agent 完成情况的消费方使用核心的 `findLastMessageTurnEnd()` 折叠逻辑,因此后续的标题轮次、注入轮次或其他归插件所有的轮次无法取代此前由消息触发的结果。 +`ctx.sessionQuery.readTitle()` 会折叠一份实时优先或已持久化的日志,而不会在 `listSessions()` 期间加载标题。TUI 使用最新标题作为其标题栏副标题,并在完成终端安全渲染后,将终端窗口标题设置为 `<session title> — <configured product title>`。Web host 会在每个已附加会话的订阅基线之后,以及转发实时原始标题事件后立即,将同一份日志状态折叠为经过校验的 mux 控制帧。即使控制帧先于列表或会话实例创建抵达,浏览器也只保留标题事件 seq 较新的版本;侧边栏标签、搜索、面包屑和浏览器标题会随投影后的修订更新。`session.list` 仍只包含元数据,因此尚未打开的持久化会话会继续以 cwd 基名或 id 作为回退,直至打开或恢复会话时附加其日志。浏览器仅在选中已有标题的会话时将标题设置为 `<session title> — <existing HTML title>`,否则保留产品标题。合成标题轮次本身仍会完成,并作为元数据写入的持久性边界;报告 agent 完成情况的消费方使用核心的 `findLastMessageTurnEnd()` 折叠逻辑,因此后续的标题轮次、注入轮次或其他归插件所有的轮次无法取代此前由消息触发的结果。 ## 考虑过的替代方案 @@ -54,7 +54,7 @@ Status: implemented ## 后果 -- 标题可以在 JSONL 和 SQLite 持久化中存续,通过 ACP 回放,并遵循 fork 继承语义,而无需单独的可变记录。 +- 标题可以在 JSONL 和 SQLite 持久化中存续、重放并遵循 fork 继承语义,而无需单独的可变记录。 - Web 标题仍以增量方式从日志交付,无需标题索引或扫描持久化列表;冷启动列表项会在会话附加后改用标题。 - 回退标题会立即出现。每个新建的 Web 会话都会增加一次针对首消息的辅助调用;其他组合可以自行决定更优标题是否值得模型成本,以及后续提示词是否需要重新生成会话标题。 - 辅助请求记录和延迟接受的标题会占用事件 seq,并可能创建平衡的零步骤轮次,因此持久化会同时呈现尝试发起的调用与已接受的更新,尽管模型历史和 KV 缓存标识保持不变。 diff --git a/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.i18n.yaml b/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.i18n.yaml new file mode 100644 index 0000000000..19b6055f0a --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-doc-sync-enforcement.md: 375059312c312dff7b5ddcb95ea5b82ac8cd4d06 +2026-06-11-doc-sync-enforcement.zh.md: 5c17263bdc2b4908a82237d1fc3b08f1f22a62d9 diff --git a/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.md b/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.md index 67cdfd6771..375059312c 100644 --- a/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.md +++ b/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-doc-sync-enforcement.zh.md) + ## Problem AGENTS.md promises that docs and code stay strictly in sync, but the promise was verified by eyeball. Review caught drift twice — a cookbook example contradicting the type policy, and a README citing the wrong `registerAdapter` call. Out-of-sync docs are worse than no docs, and this codebase is built primarily by agents that follow gates far more reliably than prose (mechanical quality gates). Two classes of doc drift are mechanically checkable: code blocks that no longer compile, and the event-taxonomy table that duplicates the `interface Events` declarations. diff --git a/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.zh.md b/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.zh.md new file mode 100644 index 0000000000..5c17263bdc --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.zh.md @@ -0,0 +1,32 @@ +# Agent Note: Doc-sync 强制 + +Status: implemented + +[English](2026-06-11-doc-sync-enforcement.md) | 中文 + +## 问题 + +AGENTS.md 承诺文档与代码严格同步,但这一承诺此前仅靠人眼核查。评审曾两次发现漂移:一次是实操手册(cookbook)示例与类型策略矛盾,一次是 README 引用了错误的 `registerAdapter` 调用。失去同步的文档比没有文档更糟;而本代码库主要由 agent(智能体)构建,agent 遵守门禁远比遵守行文约定可靠(机械质量门禁)。有两类文档漂移可以被机械检查:不再能编译的代码块,以及与 `interface Events` 声明重复的事件分类体系表。 + +## 决策 + +两道门禁,沿用既有的 `scripts/` 风格(tsx ESM,每个脚本一项职责): + +1. **`doc-typecheck`** 从 `README.md`、`docs/**` 和 `packages/*/README.md` 中提取所有 ` ```ts ` 围栏代码块,写入一个继承根 `tsconfig.json` 的临时项目,然后用 `tsc -b` 编译。临时项目复用源码的 `paths` 映射和根 project references,因此文档示例能看到源码,而 vendor 代码仍在其自身的 tsconfig 设置下被检查。刻意作为草图的代码块可通过显式的 ` ```ts ignore-check ` 信息字符串来 opt-out;脚本会报告 opt-out 比例,超过一半即失败,防止该豁免机制悄然成为常态。 +2. **`verify-event-taxonomy`** 从 `packages/*/src` 中的 `interface Events` 块和 `docs/architecture.md` 中的分类体系表分别提取事件名称,断言两个集合完全一致。只校验,不生成:表格保留手写的 Mode/Purpose 列,仅检查名称集合。(落地此门禁时发现了表格遗漏的三个事件:`tools/change`、`llm/adapter-change`、`system-prompt/change`。)**已被取代**:由[生成式 Cordis 目录](2026-06-20-generated-cordis-catalog.md)取代。此门禁及其 `architecture.md` 表格已退役,取而代之的是完全生成的 `docs/cordis-catalog/events.md` + `docs/cordis-catalog/services.md` 及其 `verify-cordis-catalog` 新鲜度门禁。本 Agent Note(agent 决策记录)中的其他门禁(`doc-typecheck` 以及下文修订中的 `verify-md-wrap`)不受影响。 + +两者都通过 package.json 中共享的 `doc-sync` 脚本运行;贡献者在相关文档变更中调用它,CI 则执行完整检查。[快速本地 Git 钩子](2026-07-22-fast-local-git-hooks.md)决策使这类按变更面选择的工作不进入 commit 和 push 钩子。 + +**修订(2026-06-17):** 第三道门禁 **`verify-md-wrap`** 随后被纳入 `doc-sync`。它使用 `mdast-util-from-markdown` + GFM 解析范围内的每个 Markdown 文件(`README.md`、`docs/**`、`packages/*/README.md`,加上 `AGENTS.md` / `packages/AGENTS.md`),如果任何 `paragraph` 节点跨越多个源码行则失败,从而强制执行 docs/AGENTS.md 中「一个段落一个物理行」的写作规则。同样遵循只校验不生成的原则:它报告硬换行但从不重写,因此不会引入格式化噪音。`doc-sync` 现在包含三道门禁。 + +## 曾考虑的替代方案 + +- **API-extractor 基准报告**([已推迟的提案](../../proposed/process/2026-06-11-api-extractor-reports.md)):有意推迟。对于评审者已能直接看到源码 diff 的内部 monorepo 而言价值有限,且依赖重、配置繁琐。 +- **从源码生成分类体系表**而非仅校验名称:否决,机制比问题本身更重;表格保留了手写的 Mode/Purpose 列,直到[生成式 Cordis 目录](2026-06-20-generated-cordis-catalog.md)完全取代了这项检查。 + +## 后果 + +- 可检查类别中的文档漂移会直接使 `doc-sync` 和 CI 失败,而不是等评审人发现。这是「机械门禁优于行文规范」原则的具体应用。 +- 让文档代码片段可编译需要少量 stub import/`declare`;`ignore-check` 比例必须保持低位,否则门禁形同虚设(比例守卫强制执行此约束)。 +- 分类体系检查仅限名称——Mode 或 Purpose 列的错误仍需人工评审。 +- 如果包(package)未来对外发布,API 报告方案仍可重新考虑。 diff --git a/.agents/notes/implemented/process/2026-06-11-quality-gates.i18n.yaml b/.agents/notes/implemented/process/2026-06-11-quality-gates.i18n.yaml new file mode 100644 index 0000000000..6d017a8961 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-11-quality-gates.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-quality-gates.md: e1af110387936d644208dc1829fde4a4fdf8a3f9 +2026-06-11-quality-gates.zh.md: a4e57b7a08ecf20babb33b55d8c94414df1b10b1 diff --git a/.agents/notes/implemented/process/2026-06-11-quality-gates.md b/.agents/notes/implemented/process/2026-06-11-quality-gates.md index 5e1db16e52..e1af110387 100644 --- a/.agents/notes/implemented/process/2026-06-11-quality-gates.md +++ b/.agents/notes/implemented/process/2026-06-11-quality-gates.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-quality-gates.zh.md) + The hook/CI symmetry in this record is superseded by [Fast local Git hooks](2026-07-22-fast-local-git-hooks.md); CI remains the exhaustive enforcement path. ## Problem diff --git a/.agents/notes/implemented/process/2026-06-11-quality-gates.zh.md b/.agents/notes/implemented/process/2026-06-11-quality-gates.zh.md new file mode 100644 index 0000000000..a4e57b7a08 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-11-quality-gates.zh.md @@ -0,0 +1,30 @@ +# Agent Note: 以机械质量门禁取代行文约定 + +Status: implemented + +[English](2026-06-11-quality-gates.md) | 中文 + +本记录中的钩子/CI 对称设计已由[快速本地 Git 钩子](2026-07-22-fast-local-git-hooks.md)取代;CI 仍是执行完整检查的路径。 + +## 问题 + +本代码库主要由 coding agent(智能体)开发。相比行文约定,agent 遵守强制门禁的可靠性远高得多;而当劳动由 agent 承担时,「工作量大」不构成成本论据。早期证据:未通过类型检查的测试被提交(vitest 不做类型检查),仅在评审中才被发现。 + +## 决策 + +每条可机械检查的 AGENTS.md 承诺都有一个以非零状态退出的命令。CI 执行完整集合,而 Git 钩子将延迟预算留给可低成本发现的本地缺陷: + +- 最严格的 TypeScript 配置(`noUncheckedIndexedAccess`、`exactOptionalPropertyTypes` 等);示例、测试和脚本通过根目录的 no-emit `tsconfig.json` 在 CI 中进行类型检查,而包(package)/vendor 代码保持在各自 project-reference 边界之后。 +- ESLint strict-type-checked + @stylistic(作为强制执行的统一代码风格),包括文件内重复逻辑检查;vendor 代码排除在外。 +- jscpd 检测包的生产 TypeScript 代码与仓库脚本中的跨文件克隆;窄范围的源码区间例外用于记录有意为之的并行实现。 +- `packages/*/*/src` 下按文件 100% 覆盖率(v8);不可达的防御性守卫使用 `/* v8 ignore */ ` 并注明理由,而非删除。 +- knip(死代码/依赖)、publint(包的正确性)、workspace 约束(workspace 规则:private、cordis peer+dev、统一版本、ESM),以及对构建出的包声明文件进行 NodeNext 消费方类型检查。 +- lefthook pre-commit 修复已暂存文件的 lint 问题、拒绝已暂存的空白问题并检查 vendor manifest;pre-push 运行增量类型检查。CI 在 Node 22.19/24/26 上运行完整矩阵,并对 Headless、TUI、ACP(Agent Client Protocol)、JSON-RPC、工作流和代码运行时入口路径执行已构建应用的冒烟测试。 + +## 后果 + +- 约定不会因 agent 更替而失效;可低成本发现的 commit/push 缺陷在本地失败,其余完整规则违规在 CI 中失败。 +- 门禁本身也是需要维护的代码;配置变更与其他变更一样需要评审。 +- 100% 覆盖率的压力可能催生无断言的测试——变异测试是计划中的对策(见[变异测试提案](../../proposed/testing/2026-06-11-mutation-testing.md))。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.i18n.yaml b/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.i18n.yaml new file mode 100644 index 0000000000..4ac1a926c4 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-tsdown-over-dumble.md: e8cdaeb1e3331ffb04de024acff5b0e6ca3e6366 +2026-06-11-tsdown-over-dumble.zh.md: bb5feef585c1748f41d1b204313f1a4d8b357a17 diff --git a/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.md b/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.md index 0629acabb4..e8cdaeb1e3 100644 --- a/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.md +++ b/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-tsdown-over-dumble.zh.md) + ## Problem The initial build used **dumble**, the cordiverse zero-config esbuild wrapper that upstream Cordis itself builds with — maximum alignment with the vendored packages' conventions (it reads each package.json and infers entries/formats from the `exports` field). But dumble is a liability as a load-bearing tool in this repo: v0.2.x, ~530 npm downloads/week, effectively one maintainer, and we were invoking it through a custom orchestration script (`scripts/build.ts`) because it has no workspace mode. diff --git a/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.zh.md b/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.zh.md new file mode 100644 index 0000000000..bb5feef585 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.zh.md @@ -0,0 +1,30 @@ +# Agent Note: 使用 tsdown 替代 dumble 进行 JS 打包 + +Status: implemented + +[English](2026-06-11-tsdown-over-dumble.md) | 中文 + +## 问题 + +最初的构建使用 **dumble**,即 cordiverse 的零配置 esbuild 包装层——上游 Cordis 自身也用它构建——与 vendor 包(package)的约定最大程度对齐(它读取每个 package.json 并从 `exports` 字段推断入口/格式)。但 dumble 作为本仓库的承重工具存在隐患:v0.2.x,每周约 530 次 npm 下载,实质上只有一位维护者,而且由于它没有 workspace 模式,我们不得不通过自定义编排脚本(`scripts/build.ts`)来调用它。 + +目前构建产物只在 `pnpm run build` + publint 中有意义(尚未发布任何包;开发/测试/演示通过 tsx 直接运行未打包的源码),因此切换成本现在最低,一旦包开始发布就只会更高。 + +## 决策 + +用 **tsdown**(基于 rolldown,每周约 250 万次下载,VoidZero 支持,活跃发布)替代 dumble: + +- 根目录 `tsdown.config.ts`,配置 `workspace: ['vendor/*', 'packages/*/*']`(显式 glob 将打包范围限定在 vendor 的 Cordis 与 TypeScript 包目录树内;`workspace: true` 还会发现示例 manifest 和不需要打包的 workspace 成员)。 +- 共享形状:入口为 `lib/types/index.js`,`outDir: 'lib'`,ESM,`platform: node`,`target: es2024`,`fixedExtension: false`(为 `"type": "module"` 包保留 `.js`),`dts: false`(声明归 tsc -b 所有),`clean: false`(lib/ 还保存 TSC 的 `lib/types` 中间树)。入口最初是 `src/index.ts`;[TSC 优先构建 Agent Note(agent 决策记录)](2026-06-17-ts-build-config.md)随后将 tsdown 改为打包 TSC 输出的 JS,使 TypeScript 转换行为统一由一个编译器提供。 +- vendor/ 中有两个按包覆盖的配置(属于我们自己的修改,与重新生成的 tsconfig 类似;记录在 vendor/README.md 中):schemastery(通过 `outExtensions` 输出双格式 `.mjs`/`.cjs`)、logger-console(两次单入口 pass,使共享基类被内联到每个入口而非生成哈希命名的分片,与上游发布形态一致)。 +- `scripts/build.ts` 删除;`pnpm run build` = `tsc -b && tsdown`(根 solution 拥有 emit 图)。 + +## 曾考虑的替代方案 + +- **直接编写 esbuild 脚本**:最成熟的引擎,零包装层风险,但需要手动维护 tsdown workspace 模式自动提供的按包规格表。 +- **pkgroll**:理念上最接近的直接替代品,但每周仅 78k 下载且基于 Rollup,维护前景严格弱于 tsdown。 +- **保留 dumble**:与上游完美对齐,但巴士因子不可接受。 + +## 后果 + +运行时 bundle 输出仍沿用 dumble 时代的公开入口形状(`lib/index.js`,以及包特有的变体,例如 `schemastery` 的 `lib/index.mjs`/`lib/index.cjs` 与 `logger-console` 的 `lib/browser.js`);根据 [TSC 优先构建 Agent Note](2026-06-17-ts-build-config.md),声明现位于 `lib/types` 下。External 仍来自各包的 dependencies/peerDependencies。我们放弃了 dumble 的 exports 字段推断:采用非默认形状的新包需要逐包提供 `tsdown.config.ts`,不能只依赖 package.json 字段。未来如果 `tsc -b` 成为瓶颈,tsdown 也可以接管声明打包(isolatedDeclarations);这需要另写一份 Agent Note。 diff --git a/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.i18n.yaml b/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.i18n.yaml new file mode 100644 index 0000000000..0e0c6693a2 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-vendor-cordis-as-source.md: ae6f5438c5817c61a549d9edb2041d538fbcebe6 +2026-06-11-vendor-cordis-as-source.zh.md: 8d6f0e39d53e1c85eaaa50c4c4bf1d9ef648d953 diff --git a/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.md b/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.md index a8895ba5e8..ae6f5438c5 100644 --- a/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.md +++ b/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-vendor-cordis-as-source.zh.md) + ## Problem DeepSeek Harness SDK is built on the Cordis framework. Cordis core was at 4.0.0-rc.6 (a release candidate) when this repo started; the harness depends on framework internals (fiber lifecycle, effect disposal, waterfall dispatch) whose exact behavior matters to the agent loop's correctness guarantees. diff --git a/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.zh.md b/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.zh.md new file mode 100644 index 0000000000..8d6f0e39d5 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.zh.md @@ -0,0 +1,27 @@ +# Agent Note: 将 Cordis 以源码形式收录,而非作为 npm 依赖 + +Status: implemented + +[English](2026-06-11-vendor-cordis-as-source.md) | 中文 + +## 问题 + +DeepSeek Harness SDK 构建于 Cordis 框架之上。本仓库启动时,Cordis core 处于 4.0.0-rc.6(一个候选发布版本);harness 依赖框架内部实现(fiber 生命周期、dispose(资源释放)、waterfall(瀑布式事件)分发),其确切行为直接关系到 agent loop(智能体循环)的正确性保证。 + +## 决策 + +将所需的 Cordis 包(core、loader、include、group、timer、hmr、logger-console)与 cordiverse 基础库(cosmokit、schemastery)以源码形式复制到 `vendor/`,扁平化放置,保留其原始 npm 包名以实现透明的 workspace 解析。真正的第三方依赖(js-yaml、chokidar、@standard-schema/spec 等)仍从 npm 获取。 + +`vendor/README.md` 是 manifest(元数据清单):记录每个包(package)的上游仓库 + commit SHA,以及一份详尽的本地修改日志。pre-commit 守卫(`scripts/check-vendor-manifest.sh`)会拒绝未在同一次提交中更新 manifest 的 vendor 源码变更。 + +## 曾考虑的替代方案 + +- **依赖 npm 包**:否决。core 处于候选发布阶段,harness 依赖框架内部实现(fiber 生命周期、dispose、waterfall 分发),agent loop 的正确性保证取决于这些行为的确切表现;上游 RC 版本升级可能在没有本地修复路径的情况下破坏它们。 +- **递归收录所有传递依赖**:否决。真正的第三方依赖(js-yaml、chokidar、@standard-schema/spec 等)仍从 npm 获取;只有内部实现对我们有影响的框架层才需要自行持有。 + +## 后果 + +- harness 完全持有其框架层:可审计、可打补丁、版本锁定。上游 RC 无法影响我们,框架 bug 可以在仓库内直接修复。 +- 上游同步是手动操作(流程记录在 manifest 中)。修改日志使 diff 范围始终可知。 +- 收录的包保留上游代码风格;lint 与严格性门禁将其排除(它们的 tsconfig 在本地放宽了我们较新的编译器选项)。 +- 从第一天起就有一个本地补丁:移除了 hmr 的 locale-YAML 导入(运行时 YAML 导入钩子未被收录)。 diff --git a/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.i18n.yaml b/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.i18n.yaml new file mode 100644 index 0000000000..6ae4e17a2b --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-16-pnpm-over-yarn.md: 9dee405f509897e2a173399e466d574c518fa9ab +2026-06-16-pnpm-over-yarn.zh.md: 3a5ff5e9b1fb0511a9191b2e3c35b61f00b705cd diff --git a/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.md b/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.md index 42eb4228b6..9dee405f50 100644 --- a/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.md +++ b/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-16-pnpm-over-yarn.zh.md) + ## Problem The repo shipped on **Yarn 4** with the `node-modules` linker — a deliberately conservative choice that behaves like npm's flat layout while giving us Yarn's workspaces and `yarn constraints`. It worked. But Yarn 4's Plug'n'Play heritage makes the `node-modules` linker the off-the-beaten-path mode, and the broader JS ecosystem — tooling defaults, CI actions, Corepack examples, contributor familiarity — increasingly centers on pnpm. For a repo that is built primarily by agents and read by occasional human contributors, "the package manager most tools and people expect" has real value: fewer surprises, better-trodden failure paths, more copy-pasteable answers. diff --git a/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.zh.md b/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.zh.md new file mode 100644 index 0000000000..3a5ff5e9b1 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.zh.md @@ -0,0 +1,43 @@ +# Agent Note: 使用 pnpm 替代 Yarn 4 作为包管理器 + +Status: implemented + +[English](2026-06-16-pnpm-over-yarn.md) | 中文 + +## 问题 + +本仓库最初使用 **Yarn 4** 搭配 `node-modules` 链接器启动。这是一个刻意保守的选择:行为类似 npm 的扁平布局,同时享有 Yarn 的 workspaces 和 `yarn constraints`。它能正常工作。但 Yarn 4 源自 Plug'n'Play 的血统,使得 `node-modules` 链接器成为非主流模式;而更广泛的 JS 生态——工具默认值、CI action、Corepack 示例、贡献者的熟悉度——正日益以 pnpm 为中心。对于一个主要由 agent(智能体)构建、偶尔有人类贡献者阅读的仓库而言,「大多数工具和人所期望的包管理器」具有实际价值:更少的意外、更成熟的故障路径、更多可直接复用的解答。 + +切换成本目前处于最低点。本仓库尚无任何包(package)发布(每个包都是 `private: true`);开发/测试/演示全部通过 tsx **未构建**运行,因此包管理器只需做到:(a)解析并链接 `node_modules`,(b)运行 workspace 脚本,(c)强制执行 workspace 约束。唯一的 Yarn 特有资产是 `yarn.config.cjs`(`@yarnpkg/types` 约束引擎),体量小且可机械地重新表达。这与 [tsdown 决策](2026-06-11-tsdown-over-dumble.md)的逻辑一致:在爆炸半径尚小时,将承重工具换为生态更健康的选项。 + +## 决策 + +采用 **pnpm 11.7.0**,通过 `packageManager` 字段固定版本,经 Corepack 安装(与 Yarn 使用的机制相同): + +- **Workspaces** 从 `package.json` 的 `workspaces` 数组 + `.yarnrc.yml` 迁移到 `pnpm-workspace.yaml`(`vendor/*`、`packages/*`——同样的 glob;`examples/*` 保持非 workspace,与先前设置及 tsdown 的显式 glob 一致)。 +- **严格符号链接链接器**(pnpm 默认)取代 Yarn 的提升式 `node-modules` 链接器。我们刻意**不**添加 `node-linker=hoisted` / `shamefully-hoist` 逃生口:pnpm 的非扁平 `node_modules` 会让幻影依赖(引用未声明的传递依赖)大声失败,这对于一个以机械门禁为核心质量保障的仓库(见[机械质量门禁](2026-06-11-quality-gates.md))是一项*优势*。门禁套件(类型检查、lint、test、build、knip)是证明不存在此类幻影导入的安全网。 +- **构建脚本白名单。** pnpm 10+ 不运行依赖的生命周期脚本,除非将其加入白名单。`pnpm-workspace.yaml` 携带一份显式的 `allowBuilds` 映射(`esbuild`、`lefthook`、`@google/genai`、`protobufjs`)——与本仓库对模型/工具输出已有的供应链加固姿态一致,现在也应用于安装时的代码执行。`peerDependencyRules.allowedVersions.typescript: '>=5 <7'` 消除仓库内 TypeScript 的良性 peer 范围警告。 +- **约束变为包管理器无关。** `yarn.config.cjs`(导入 `@yarnpkg/types`,使用 `Yarn.workspaces()` / `workspace.set()`)被 `scripts/check-workspace-constraints.ts` 取代——一个纯 tsx 脚本,通过 `pnpm run constraints` 运行。它在相同的 `vendor` + `packages` 范围上强制执行完全相同的不变式:每个包 `private: true`;`@deepseek-ai/dsh-*` 包将 `cordis` 同时声明为对等依赖(peer dependency)和 dev 依赖且范围一致、使用根 `package.json` 的版本、设置 `type: module`;vendor 包仅检查 privacy。 +- 所有 CI、lefthook 钩子、`package.json` 脚本和文档中的 `yarn …` 动词变为 `pnpm …` / `pnpm run …`。`yarn.lock` → `pnpm-lock.yaml`(lockfile v9)。`.gitignore` 将 `.yarn/` 换为 `.pnpm-store/`。vendor README(如 `vendor/cordis/README.md`)按 Vendoring Policy 保持其上游 `yarn` 示例不变。 + +## 曾考虑的替代方案 + +- **保留 Yarn 4**——零变动,但押注于使用率较低的链接器模式和一个绑定单一包管理器的约束引擎。 +- **npm workspaces**——无处不在,但没有约束方案,monorepo 开发体验也较差。 +- **pnpm 搭配提升式链接器**——迁移更平滑,但放弃了幻影依赖安全性,而这正是迁移的核心正确性理由。 + +## 后果 + +约束检查失去了 Yarn 的自动**修复**能力(`workspace.set()` 能原地改写 manifest);tsx 脚本仅做检查,不通过时以非零退出码和消息退出。这是可接受的:CI 从未运行过 `--fix`,且需要手动编辑的情况很少。贡献者现在为 pnpm 而非 Yarn 运行 `corepack enable`;`pnpm exec lefthook install` 取代 `yarn lefthook install`(`postinstall` 钩子仍会运行 `lefthook install`)。 + +性能(迁移时在开发 NFS 文件系统上测量;单次运行样本,方差大——仅供方向性参考,非基准测试套件): + +| 场景 | Yarn 4 | pnpm 11 | +|---|---|---| +| 冷启动(空缓存/store,无 `node_modules`) | ~14 s | ~16 s | +| 热重链接(缓存/store 已热,`node_modules` 已删除) | ~12–14 s | ~15–22 s | +| 冻结,`node_modules` 存在(无操作重验证) | ~2–8 s | ~0.5–7 s | + +在快速本地磁盘上,pnpm 的内容寻址 store 通常在冷/热安装中胜出,尤其在多个检出之间的**磁盘占用**方面优势明显(一个全局 store 通过硬链接接入每个 `node_modules`,而 Yarn 每个 worktree 复制约 279 MB——部分开发者经常为本仓库保持约 10 个或更多 worktree)。该去重优势在上述迁移时数据中**未能**体现,因为测试 store 和 `node_modules` 位于不同文件系统,硬链接失效;在单文件系统的开发机或 CI 缓存上则适用。诚实的总结:在我们的 NFS 开发文件系统上,安装速度在噪声范围内不分伯仲;迁移的理由是生态对齐、幻影依赖安全性和跨检出磁盘去重,而非原始安装时间的胜出。 + +所有质量门禁(constraints、类型检查、lint、doc-sync、达到 100% 的 test:coverage、构建、knip、publint 以及已构建应用的冒烟测试)均在 pnpm 下通过,证明更换 linker 没有引入幽灵依赖故障。 diff --git a/.agents/notes/implemented/process/2026-06-17-ts-build-config.i18n.yaml b/.agents/notes/implemented/process/2026-06-17-ts-build-config.i18n.yaml new file mode 100644 index 0000000000..80f7838d45 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-17-ts-build-config.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-17-ts-build-config.md: 1275a635242ea887c941db9dc0554fd33acd4102 +2026-06-17-ts-build-config.zh.md: 7691118dd152874e2849f1ace686069c9ea3f61f diff --git a/.agents/notes/implemented/process/2026-06-17-ts-build-config.md b/.agents/notes/implemented/process/2026-06-17-ts-build-config.md index 529400b8d7..1275a63524 100644 --- a/.agents/notes/implemented/process/2026-06-17-ts-build-config.md +++ b/.agents/notes/implemented/process/2026-06-17-ts-build-config.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-17-ts-build-config.zh.md) + > Root project topology (which tsconfig owns which graph) has since moved to a solution root over two aggregate programs; see the [solution-root note](2026-07-22-tsconfig-solution-root-two-aggregates.md). The tsc-first pipeline decided here is unchanged. ## Problem diff --git a/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md b/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md new file mode 100644 index 0000000000..7691118dd1 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md @@ -0,0 +1,80 @@ +# Agent Note: TSC 优先构建与编译器单一归属 + +Status: implemented + +[English](2026-06-17-ts-build-config.md) | 中文 + +> 根项目拓扑(即哪个 tsconfig 拥有哪张图)后来改为由一个 solution 根文件统辖两个聚合 program;见[solution 根文件 Agent Note](2026-07-22-tsconfig-solution-root-two-aggregates.md)。本文确定的 TSC 优先流水线保持不变。 + +## 问题 + +此前的 TypeScript 构建与类型检查配置存在以下问题: + +- `build` 使用 `tsc` 将 `packages/<group>/<pkg>` 和 `vendor/*` 下的 `.ts` 转换为 `.d.ts` 文件,然后使用 `tsdown` 将 `.ts` 转换为打包后的 `.js` 文件。这导致两个工具各自执行 TypeScript 转换。 +- `typecheck` 倾向于通过一个根目录的类型检查配置来校验包(package)、vendor 源码、示例、测试和脚本。 + +目标是让构建与类型检查使用一致的 tsconfig 边界和 TypeScript 解析/转换行为。构建应通过单一编译器和配置生成 `.js`、`.d.ts`、`.js.map` 和 `.d.ts.map`,使发布产物与类型校验保持一致。 + +验证过程中发现了若干具体的技术问题和可能的路径: + +- `tsdown` 使用 `oxc` 进行 TypeScript 转换,其行为与 `tsc` 不同。 + - `tsdown` 输出的打包 `.d.ts` 与 Cordis 内部的相对模块增强(module augmentation)结构冲突。 + - tsc 的输出受 `allowImportingTsExtensions` 影响,因此需要确保生成的 `.js` 文件不会导入 `.ts` 文件,且生成的 `.d.ts` 文件保留 NodeNext/Node16 接受的显式相对说明符。为此,包内相对导入在 TypeScript 源码中使用显式 `.ts` 说明符,由 `rewriteRelativeImportExtensions` 在输出的 JS 中将其重写为 `.js`。 + - `tsdown` 输出的打包 `.js` 与 `tsc -b` 逐文件输出的 `.js` 行为不同,例如装饰器转换行为。 +- `vendor/*/src`、示例、测试和脚本无法全部以 plain-include 方式纳入一个根目录的严格程序。 + - 在根目录严格配置下直接对 `vendor/*/src` 做类型检查,会触发大量不属于本项目所有权范围的类型错误。 + - `packages/*/*` 对 `vendor` 的包依赖解析到 `vendor/*/lib`,以适应不同的 tsconfig 严格度。 + + +## 决策 + +包内相对导入使用显式 `.ts` 说明符。 + +`pnpm run build` 是两阶段构建: + +- 阶段 1:在根 solution 上执行 `tsc -b`,将逐模块的 `.js`、声明文件 `.d.ts`、JS sourcemap `.js.map` 和声明 sourcemap `.d.ts.map` 输出到各包的 `lib/types`。这是权威的 TypeScript 编译结果。发布时保留 `.d.ts` / `.d.ts.map`,忽略 `.js` / `.js.map`。 + - 该图是从根 solution `tsconfig.json` 经两个聚合可达的 project-reference 图([拓扑](2026-07-22-tsconfig-solution-root-two-aggregates.md)),用于校验并输出包/vendor 的构建结果。 +- 阶段 2:打包器读取 `lib/types` 下输出的 JS,将打包后的运行时入口写为 `lib/index.js` 或 `lib/index.mjs`(沿用当前行为)。此阶段仅做打包,禁止读取 TypeScript 源码或输出声明文件。 + +`tsdown` 不再负责 TypeScript 编译或声明文件输出。 + +`pnpm run typecheck` 运行同一张 `tsc -b` 图。 +- 两个聚合(`tsconfig.host.json`、`tsconfig.client.json`)以 `noEmit` 方式检查示例、测试和脚本,并通过 references 校验包/vendor 源码。 +- 被引用的包/vendor 项目保持与构建相同的输出行为,因此类型检查会刷新它们的 `lib/types` 输出,而无需使用独立的 no-emit 图。项目特定的严格度变更放在各自的 `packages/*/*/tsconfig.json` 或 `vendor/*/tsconfig.json` 中。 +- 两个 no-emit 聚合禁用 `rewriteRelativeImportExtensions`;它们不输出任何文件,且包含跨 project-reference 边界导入 helper 的测试。包/vendor 的 emit 项目保持重写开启。 + +命令编排结构如下: + +```sh +pnpm run build: +tsc -b +tsdown + +pnpm run verify-node-next-types: +tsx scripts/verify-node-next-types.ts + +pnpm run typecheck: +tsc -b +``` + +`pnpm run demo:*` 仍通过 tsx 和根路径直接运行 `src`,无需编译步骤。 + +## 曾考虑的替代方案 + +- **继续使用 `tsdown`/oxc 作为 TypeScript 转换器**:oxc 的转换行为与 `tsc` 不同(装饰器转换有差异、打包 JS 与逐文件输出不同),且其打包 `.d.ts` 与 Cordis 内部的相对模块增强结构冲突。 +- **用一个根目录严格程序覆盖包、vendor、示例、测试和脚本**:vendor 源码在根目录严格标志下会触发不属于本项目所有权范围的类型错误;带有逐项目严格度的 project references 才是可行的边界。 + +## 后果 + +构建职责更加清晰: + +- `packages/<group>/<pkg>` 和 `vendor/*` 下的每个模块有一份本地 tsconfig,同时服务于构建、类型检查和直接运行源码的工具(如 `tsx` 和 `vitest`)。 +- `build` 命令驱动根 solution 图。`tsc -b` 负责可发布的逐模块 `.js` 和 `.d.ts` 输出,打包器仅负责 `lib/index.*`。 + - `lib/types/*.d.ts` 和 `.d.ts.map` 是发布用的声明输出。 + - `lib/types/*.d.ts` 使用显式 `.ts` 相对说明符,TypeScript 的 NodeNext/Node16 解析器会将其映射到同级的 `.d.ts` 文件。 + - `lib/types/*.js` 仅作为打包器输入,禁止用作运行时入口或公开导入目标。 + - `lib/index.*` 是发布用的运行时输出,由打包器(当前为 `tsdown`)生成。 +- `pnpm run verify-node-next-types` 扫描构建出的声明文件,检查是否存在缺少文件扩展名的相对说明符,然后以 `moduleResolution: "NodeNext"` 对构建出的 `types`/`exports` 接口进行临时外部 ESM 消费方的类型检查,确保声明说明符的回归在发布前被捕获。 +- `typecheck` 命令使用 `tsconfig.json`。示例、测试和脚本由根 no-emit 项目检查,包和 vendor 模块保持与 `build` 相同的输出行为。包和 vendor 源码始终处于 project-reference 边界之后。 + +Cordis 的 vendor 副本现在与上游多了一处类型结构差异。在上游同步时,该差异必须被重新应用或明确废弃。 diff --git a/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.i18n.yaml b/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.i18n.yaml new file mode 100644 index 0000000000..601a077189 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-18-markdown-cross-link-lint.md: 2e3b0f1fcd03f244756b0030f2da758c516a2bbb +2026-06-18-markdown-cross-link-lint.zh.md: cfe973ae939eceb50d6381ecf35c80df508907c3 diff --git a/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.md b/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.md index e57c75575b..2e3b0f1fcd 100644 --- a/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.md +++ b/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-18-markdown-cross-link-lint.zh.md) + ## Problem Docs in this repo link to each other by relative path — `[topic](../implemented/2026-…-….md)`, `[the cookbook](adding-a-tool.md)`, `[architecture.md](../../architecture.md)`. Nothing verified those targets exist. A rename or a move silently breaks every inbound link, and the break is invisible until a reader clicks it. [Doc-sync enforcement](2026-06-11-doc-sync-enforcement.md) already mechanized two classes of doc drift (uncompilable code blocks, a stale event-taxonomy table) and [verify-md-wrap](2026-06-11-doc-sync-enforcement.md) a third (hard-wrapped prose) — but a dead cross-link is a fourth, equally mechanical class that was still verified by eyeball. diff --git a/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.zh.md b/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.zh.md new file mode 100644 index 0000000000..cfe973ae93 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.zh.md @@ -0,0 +1,33 @@ +# Agent Note: Markdown 交叉链接有效性检查 + +Status: implemented + +[English](2026-06-18-markdown-cross-link-lint.md) | 中文 + +## 问题 + +本仓库的文档通过相对路径互相链接:`[topic](../implemented/2026-…-….md)`、`[the cookbook](adding-a-tool.md)`、`[architecture.md](../../architecture.md)`。此前没有任何机制验证这些目标是否存在。重命名或移动文件会静默破坏所有指向它的链接,且在读者点击之前不可见。[Doc-sync 强制](2026-06-11-doc-sync-enforcement.md)已经将两类文档漂移机械化(无法编译的代码块、陈旧的事件分类表),[verify-md-wrap](2026-06-11-doc-sync-enforcement.md) 覆盖了第三类(硬换行的段落),但死链是第四类同样可机械检查、却仍靠肉眼验证的问题。 + +引入这道门禁的直接动因是 Agent Note(agent 决策记录)目录树重组:将 `docs/adr/` 与 `.agents/notes/` 统一到同一个 `.agents/notes/` 下,并设置 `proposed/`、`implemented/`、`rejected/` 子目录,需要手工重命名约 40 条文档间链接。只要有一处路径输入错误,就会在没有任何检查拦截的情况下交付断链。 + +## 决策 + +新增第四道 `doc-sync` 门禁 `verify-md-links`(`scripts/verify-md-links.ts`),风格与 `verify-md-wrap` 一致(tsx ESM、基于 AST、只验证不生成): + +- 使用 `mdast-util-from-markdown` + GFM 解析每个范围内的 Markdown 文件,遍历所有 `link`、`image` 和 `definition` 节点。 +- 仅当目标是**相对路径**时才检查。跳过带协议的 URL(`https:`、`mailto:` 等)、协议相对路径(`//host`)、根绝对路径(`/path`,在检出目录中没有稳定基准)以及纯页内锚点(`#section`)。剥除 `#fragment`/`?query`,相对于链接所在文件的目录解析路径,并断言目标在磁盘上存在。 +- 只报告、不改写;发现第一条死链即以非零状态退出。 + +检查范围与其他门禁一致,并额外包含 AGENTS.md 文件对以及 `.agents/skills/` 下仓库自有的 agent-skill(技能)Markdown(这些 skill 文件会交叉链接到 docs 目录树,因此本次重组也改写了其中的链接):`README.md`、`docs/**/*.md`、`packages/*/README.md`、`AGENTS.md`、`packages/AGENTS.md`、`.agents/skills/**/*.md`。系统按真实路径去重(`CLAUDE.md` symlink 会解析到 AGENTS.md 文件)。该检查接入 `doc-sync`,因此相关文档变更与 CI 执行同一套断链检查。 + +本门禁检查的是*文件存在性*,而非锚点有效性:指向一个真实文件但带有 `#wrong-heading` 片段的链接仍会通过(文件可解析;片段被剥除)。 + +## 曾考虑的替代方案 + +**锚点级有效性检查**:更重且价值更低;实际造成问题的是文件级死链。这一范围裁剪是有意为之:作者在链接到某个锚点时自行验证 `#fragment`。 + +## 后果 + +- 造成交叉链接失效的重命名与移动会直接使 `doc-sync` 和 CI 失败,而不是等读者点击死链才暴露。由此,引入该门禁的 Agent Note 重组具备自校验能力:同一个 PR(Pull Request)在改写 40 条链接的同时,也添加了证明这些链接均未悬空的检查。 +- `doc-sync` 链中多了一个快速 tsx 脚本;无新增依赖(mdast/GFM 技术栈已作为 `verify-md-wrap` 的 devDependencies 存在)。 +- 该门禁强制执行的约定是:文档交叉引用必须使用可机械检查的相对链接,绝不能只写纯文本或编号。[docs/AGENTS.md](../../../../docs/AGENTS.md)记录了这项约定,使作者了解该门禁及其理由。 diff --git a/.agents/notes/implemented/process/2026-06-20-agent-note-classification.i18n.yaml b/.agents/notes/implemented/process/2026-06-20-agent-note-classification.i18n.yaml new file mode 100644 index 0000000000..cc0a877084 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-20-agent-note-classification.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-agent-note-classification.md: 094233ed108e35e390cdc66b419179249c2d9173 +2026-06-20-agent-note-classification.zh.md: b424b07e051507a894c8f5961feb5fe24a9da3c6 diff --git a/.agents/notes/implemented/process/2026-06-20-agent-note-classification.md b/.agents/notes/implemented/process/2026-06-20-agent-note-classification.md index 750a3586e0..094233ed10 100644 --- a/.agents/notes/implemented/process/2026-06-20-agent-note-classification.md +++ b/.agents/notes/implemented/process/2026-06-20-agent-note-classification.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-agent-note-classification.zh.md) + ## Problem A lifecycle-only Agent Note tree — `proposed/` / `implemented/` / `rejected/` — does not record what *kind* of decision each file contains. A reader browsing one lifecycle cannot distinguish a new capability from a removal or a tooling-policy change without opening each file. diff --git a/.agents/notes/implemented/process/2026-06-20-agent-note-classification.zh.md b/.agents/notes/implemented/process/2026-06-20-agent-note-classification.zh.md new file mode 100644 index 0000000000..b424b07e05 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-20-agent-note-classification.zh.md @@ -0,0 +1,48 @@ +# Agent Note: 通过路径编码的子目录对 Agent Note 进行分类 + +Status: implemented + +[English](2026-06-20-agent-note-classification.md) | 中文 + +## 问题 + +仅按生命周期组织的 Agent Note(agent 决策记录)目录树(`proposed/` / `implemented/` / `rejected/`)无法记录每个文件包含哪一*类*决策。读者浏览某个生命周期时,如果不逐一打开文件,就无法区分新功能、移除项或工具策略变更。 + +本仓库一贯的倾向是[机械质量门禁优于行文规范](2026-06-11-quality-gates.md):不被机器检查的约定终将腐烂。因此这里的分类方案必须可强制执行,而非靠自觉的文件头。 + +## 决策 + +增加第二个维度,即 Agent Note 的**类别**,并将其编码在路径中:`{lifecycle}/{class}/yyyy-mm-dd-topic.md`。文件夹*就是*标签。文件位置声明其类别;封闭集合限定为「这些文件夹且仅限这些」;既有的 [verify-md-links](2026-06-18-markdown-cross-link-lint.md) 门禁已经保护移动文件所需的路径改写。 + +### 六个类别的封闭集合 + +| 类别 | 涵盖范围 | +|---|---| +| `feature` | 面向用户或模型的新功能。 | +| `bug-fix` | 修正缺陷或填补事后复盘暴露的空白。 | +| `simplification` | 移除代码、行为或对外表面积,不引入新功能。 | +| `architecture` | 关于**交付源码**的结构性决策——包(package)之间的关系、运行时词汇。 | +| `process` | **围绕**代码的工具、策略或工作流,而非运行时行为。 | +| `testing` | 测试基础设施与策略。 | + +`architecture` 与 `process` 的分界是:**architecture** 关乎我们交付的源码;**process** 关乎源码周边的工具与工作流。本 Agent Note 本身属于 `process` 决策:它改变仓库的组织方式与门禁,而不是 harness 的运行时行为,因此位于 `implemented/process/` 下。 + +### 两道门禁 + +两者都是 `doc-sync`(文档同步门禁)的成员,风格与 `verify-md-wrap` 一致(tsx ESM,只校验不生成,首个违规即以非零退出码退出): + +- **`scripts/verify-agent-note-classification.ts`**:定义封闭的生命周期与类别集合。它断言生命周期文件夹下的每个文件都位于规范集合中的类别文件夹内(生命周期根目录下散落的 `.md` 或未知类别文件夹都会失败),并拒绝集中式 `INDEX.md`。规范集合位于 `scripts/agent-note-tree.ts` 中,[README](../../README.md)则以行文记录每个类别。 +- **`scripts/verify-doc-refs.ts`**:检查引用文档的源码注释。Agent Note 路径不仅出现在 Markdown 中,也出现在 TypeScript 文档注释中(例如以仓库根为起点的 `.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md`)。`verify-md-links` 看不到这些引用,因此目录重组可能静默留下失效引用。该门禁扫描 `packages/**` 与 `examples/**` 下仓库自有的 `.ts` 文件(排除已构建的 `lib/` 与 `vendor/`),查找 `docs/….md` 和 `.agents/notes/….md` token,解析每个以仓库根为起点的路径并断言其存在。它要求使用 `.md` 扩展名,因此不处理无扩展名的行文。 + +## 曾考虑的替代方案 + +- **在每个文件中添加 `Classification:` 行文行**(紧邻 `Status:`),由门禁解析。可行,但它将路径已能承载的事实重复到文件中,且行内容可能与所在文件夹不一致。路径编码使标签与其存储合二为一,没有需要保持同步的东西。 +- **设立 `refactor` 类别。** 与 `simplification` 几乎完全重叠;唯一有人试图用来区分的标准是「可观察行为是否改变?」,而 `simplification` 已经编码了这一点(它不改变)。一个类别即可,无需两个。 +- **生成或手工维护的语料索引。** 不予采纳:生命周期/类别目录树才是权威结构;集中式清单会制造合并热点,却没有提供目录树导航或仓库搜索无法实现的发现能力。单独的[索引提案](../../rejected/process/2026-07-04-generate-agent-note-index-tables.md)记录了被放弃的生成形状。 + +## 后果 + +- 每份 Agent Note 都位于一个类别文件夹下。读者浏览单个文件夹,即可查看某个生命周期内的全部简化或测试决策。 +- `doc-sync` 链中多了两个快速 tsx 脚本;无新依赖(mdast/GFM 栈已因 `verify-md-wrap`/`verify-md-links` 而存在)。 +- 新增类别必须是显式决策:修改 `scripts/agent-note-tree.ts` 中的 `const` 与 [Classification 章节](../../README.md#classification),而不是只用 `mkdir` 创建文件夹。门禁会拒绝未知文件夹,因此临时类别无法悄然混入。 +- 源码注释中的文档引用同样受门禁约束:被 `.ts` 注释引用的文档一旦移动或重命名,`doc-sync` 与 CI 中的 `verify-doc-refs` 就会失败,从而堵住 `verify-md-links` 在结构上无法发现的一类漂移。 diff --git a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.i18n.yaml b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.i18n.yaml new file mode 100644 index 0000000000..f59c523dce --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-core-data-structures-catalog.md: d7e9d3d9b14fe723e3396c8167fe714b7613e2b5 +2026-06-20-core-data-structures-catalog.zh.md: 8d2f16a46216cba8df0539be0abd2f1ad840eec3 diff --git a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.md b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.md index 6e832fb73b..d7e9d3d9b1 100644 --- a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.md +++ b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-core-data-structures-catalog.zh.md) + ## Problem A reader trying to understand the harness could find its *behavior* in [architecture.md](../../../../docs/architecture.md) (the service map, the session/turn/step lifecycle, the event taxonomy) but had no single place describing its *vocabulary* — the data structures that behavior moves around. The type shapes lived only in source, scattered across `packages/*/src/types.ts`, so understanding "what is a `Message`, a `SessionEvent`, a `StreamChunk`" meant reading the declarations directly. A prose catalog would help, but a catalog that paraphrases or paste-copies type definitions rots the instant a field changes — and an out-of-sync type doc is worse than none, because a reader trusts it. diff --git a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.zh.md b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.zh.md new file mode 100644 index 0000000000..8d2f16a462 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.zh.md @@ -0,0 +1,60 @@ +# Agent Note: 核心数据结构目录与 `ts type-equiv` 漂移门禁 + +Status: implemented + +[English](2026-06-20-core-data-structures-catalog.md) | 中文 + +## 问题 + +试图理解 harness 的读者可以在 [architecture.md](../../../../docs/architecture.md) 中找到它的*行为*(服务图、会话/轮次/步骤生命周期、事件分类),却找不到一个统一描述其*词汇*的地方,也就是这些行为所传递的数据结构。类型形状只存在于源码中,散落在 `packages/*/src/types.ts` 各处,因此要理解“什么是 `Message`、`SessionEvent`、`StreamChunk`”,就必须直接阅读声明。文字目录会有所帮助,但复述或复制粘贴类型定义的目录会在字段发生变化时立即腐化,而不同步的类型文档比没有文档更糟,因为读者会信任它。 + +因此,这项工作有两个相互交织的问题:**这样的目录应包含什么**(范围问题——harness 有数十种跨包(package)边界的类型,把它们全部倾倒进来对谁都没有帮助),以及**如何避免粘贴的类型定义发生漂移**(持久性问题)。本 Agent Note(agent 决策记录)记下了这两项决策。与它配套的[生成式 Cordis 事件与服务目录](2026-06-20-generated-cordis-catalog.md)从*接线*维度形成补充:本文对数据结构编目,另一篇则对传递这些结构的事件和服务编目。 + +## 决策 + +新增的 `docs/core-data-structures/` 目录对这些词汇编目,并配有新的 `verify-type-equiv` 文档同步门禁,使每个粘贴的类型声明及其 JSDoc 与源码保持同步。 + +### 何为"核心"——主干与 seam 的分界线 + +范围界定并非自上而下拍定,而是将候选定义逐一对照具体的边界类型反复测试,直到一条规则在所有案例中都成立。决定性的测试是 `BashExecRequest`/`BashExecSpec`/`BashRunResult`:bash 是一个能力 *seam*,不属于 agent loop(智能体循环)主干;如果这些算"核心",那么"核心"就意味着*所有跨包词汇*,目录沦为平铺罗列;如果不算,"核心"就意味着*中央主干*,bash 词汇归入子页面。后者胜出,由此确定了整体结构:一个**分层文件夹**,而非一份平铺文档。 + +确定其余案例的规则是:***你编写、持有或接收的类型是核心;为其提供类型推导、渲染或持久化的机制是子页面细节。*** 逐一验证如下: + +- 一个数据结构是**核心**的,如果它流经 agent loop 主干——无论加载了哪些插件,循环在每个轮次都会持有、派生、流式输出或记录它(`Message`、`StreamChunk`、`SessionEvent`、`Agent` 句柄)——**或者**它是插件作者面对某条流水线时编写的唯一标志性类型(`ToolDefinition`)。 +- `ToolDefinition` 是核心(它是每个工具作者编写的东西),**即使循环从不持有它**——对于这一个标志性类型,撰写重要性压过了严格的"流经主干"规则。但它的类型推导机制——`ValueSchemaSpec`、`ParameterSchemaSpec`、`InferValue` 与 `InferArgs`——是子页面细节。这就是主干与 seam 分界线的精确表述。 +- `ToolSchema` 是核心(它是流经每个步骤的模型请求 `GenerateOptions` 的一个字段),即使它在概念上属于工具流水线——当*流经主干*与*概念归属*冲突时,前者胜出。 +- 工具展示词汇(`ToolCallView`/`ToolResultView` 等)、`SessionPersistence` 持久性 seam 以及 bash 词汇是子页面。 + +`core.md` 是一份**自包含的主干文档**:它给出每个主干结构的确切类型定义,辅以最少的行文,并链接到子页面获取各 seam 的细节。子页面包括 `llm-streaming.md`、`session.md`、`persistence.md`(沿内存模型与持久性 seam 的分界线从会话页面拆出)、`tools.md` 和 `bash.md`。 + +### `ts type-equiv` 机制——既逐字又防漂移 + +持久性要求很具体:文档展示当前类型声明与原始 JSDoc 的**逐字**内容(让读者看到真实形状和源码契约,而非复述),**并且**以机械方式保证其与源码匹配。仓库已经会编译 ` ```ts ` 围栏块(`doc-typecheck`),但真正接受类型检查的块需要导入噪音,而且只能证明*可赋值性*——字段改名或 JSDoc 变化仍可能通过。因此: + +- 完整的类型声明及其 JSDoc 会逐字粘贴到专用的 ` ```ts type-equiv ` 围栏中。简洁的 ` ```ts public-api ` 围栏承载与源码等价的类环境投影,用于实现体不应进入目录的类。`doc-typecheck` 会识别并跳过这两种围栏(裸声明无法独立编译),并且**将它们排除在 opt-out 比例之外**——它们是单独受检的类别,而不是未经检查的草图。 +- 新增的 `scripts/verify-type-equiv.ts` 通过 TypeScript 解析器提取每个块,并断言其声明结构和每条 JSDoc 注释都与所声明的符号匹配,只忽略格式空白和非 JSDoc 注释。普通块保留完整声明。`public-api` 投影保留类的公共字段、构造函数、访问器和方法及其原始 JSDoc,同时移除实现体以及私有或受保护成员。之所以选择它而非编译式 `_Check` 断言,是因为目录所保留的是源码名称与文档一致性,而不是可赋值性。 +- 来源信息存放在集中的 `scripts/type-equiv.manifest.json`(`{ doc, symbol, source }` 条目)中,**而非**行文中的指令注释。脚本强制执行 **1:1 对应**:每个 type-equiv 块恰好有一条 manifest 条目,反之亦然;因此一个块永远不会被静默漏检,一条条目也永远不会腐烂。 +- 接入 `doc-sync`,因此相关文档变更会在本地运行它,CI 也会与其他文档检查一起运行它。 + +### 维护是作者的职责,门禁作为兜底 + +`verify-type-equiv` 能捕获已记录类型的*粘贴漂移*,但无法告诉你一个全新的核心类型没有被记录。因此 AGENTS.md 和 `dsh-code-review` skill(技能)已更新,要求在变更添加或重塑已记录类型时同步更新目录——门禁处理漂移,人处理新增表面。 + +## 曾考虑的替代方案 + +- **平铺罗列所有跨包词汇**:`BashExecRequest` 测试案例否决了它。如果 seam 词汇算"核心",目录对谁都没帮助;分层的主干与 seam 结构胜出。 +- **用编译式 `_Check` 可赋值性断言**代替源码匹配:否决。可赋值性不会保留名称或 JSDoc;同类型字段改名或契约注释变化仍会通过。 +- **来源信息作为行文中的指令注释**:否决,改用集中 manifest;其强制的 1:1 对应确保一个块永远不会被静默漏检,一条条目也永远不会腐烂。 + +## 验证教训 + +主干与 seam 规则在采纳前经过了 `BashExecRequest`、工具 schema 与定义、schema DSL、展示类型以及会话/持久化拆分的逐一测试。 + +`verify-type-equiv` 必须扫描完整的 Markdown 范围,而不仅是清单点名的文档。否则,未列入清单的 `type-equiv` 块就会逃过所宣称的一一检查。因此,门禁会将此类块报告为孤儿。本 Agent Note 将这条失败关闭扫描规则,连同主干与 seam 的分界决策及逐字匹配决策一并记录;生成式 Cordis 目录在[其 Agent Note](2026-06-20-generated-cordis-catalog.md) 中有对称的设计记录。 + +## 后果 + +- 这些词汇现在有一个**无法悄然漂移**的唯一归属:源码中的字段或公共类成员发生变化后,`doc-sync` 和 CI 中的 `verify-type-equiv` 会持续失败,直至粘贴内容刷新。Cordis 服务方法仍由生成式服务目录负责,而不会在此重复。 +- 主干与 seam 分界线是一个可复用的范围界定工具,而非一次性的:同一条「你编写/持有/接收的东西是核心;为其提供类型推导/渲染/持久化的机制是细节」规则,后来也被用于界定事件/服务目录的 harness 层与继承层分层。 +- `ts type-equiv` 围栏是继 ` ```ts `(编译)和 ` ```ts ignore-check `(草稿)之后的第三种文档块类别。后续的姊妹门禁又增加了第四种 ` ```ts cordis-catalog `(生成签名),复用了相同的跳过并排除处理。 +- 添加或重塑核心类型现在附带一项文档义务,作者必须履行(门禁无法检测缺失的*新*类型),由 `dsh-code-review` 检查清单兜底。 diff --git a/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.i18n.yaml b/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.i18n.yaml new file mode 100644 index 0000000000..16fb9e2d1e --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-generated-cordis-catalog.md: b5957cf06a9316447aae70183de462024bb24be3 +2026-06-20-generated-cordis-catalog.zh.md: 35ed06c4a8e13245a37adaa4d5da7a842e97c0c7 diff --git a/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.md b/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.md index 4ca9b7e42c..b5957cf06a 100644 --- a/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.md +++ b/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-generated-cordis-catalog.zh.md) + ## Problem A plugin author needs two reference surfaces that no single document gave them: every cordis **event** they can listen to (with its exact signature and dispatch mode) and every `ctx.<key>` **service** they can call (with its exact interface). The pieces existed but were scattered — a hand-maintained event-taxonomy *table* in `docs/architecture.md` (names + prose Mode/Purpose, name-set-checked by `verify-event-taxonomy`), a Service-map table (8 rows of role prose), and the `interface Events` / `interface Context` declarations themselves. The taxonomy table also could not catch a brand-new *undocumented* event: a name-set verifier only checks the names that are already in the table on both sides. diff --git a/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.zh.md b/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.zh.md new file mode 100644 index 0000000000..35ed06c4a8 --- /dev/null +++ b/.agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.zh.md @@ -0,0 +1,41 @@ +# Agent Note: 生成式 Cordis 事件与服务目录 + +Status: implemented + +[English](2026-06-20-generated-cordis-catalog.md) | 中文 + +## 问题 + +插件作者需要两个参考面,而此前没有任何单一文档能提供:他们可以监听的每一个 Cordis **事件**(含精确签名与分发模式),以及他们可以调用的每一个 `ctx.<key>` **服务**(含精确接口)。相关信息虽然存在,但散落各处:`docs/architecture.md` 中一张手工维护的事件分类*表格*(名称 + 行文描述的 Mode/Purpose,由 `verify-event-taxonomy` 做名称集合校验)、一张服务映射表(8 行角色描述),以及 `interface Events` / `interface Context` 声明本身。分类表格还有一个盲区:它无法捕获全新的*未记录*事件——名称集合校验器只检查两侧已有的名称。 + +这是对[核心数据结构目录](../../../../docs/core-data-structures/core.md)([其 Agent Note(agent 决策记录)](2026-06-20-core-data-structures-catalog.md))在接线维度上的补充:前者对循环传递的*数据结构*编目(经验证的手工粘贴),本文则对传递它们的*事件和服务*编目。 + +## 决策 + +从源码生成目录,取代手工维护表格并校验子集的方式。 + +`scripts/gen-cordis-catalog.ts` 使用 TypeScript 编译器 API,根据声明和源码 JSDoc 分别生成事件与服务参考。事件包含分派模式及其原始成员 JSDoc;服务包含公共签名及各方法的原始 JSDoc。确定性的 `--write` 和 `--check` 模式使两个页面成为生成产物,并由 `doc-sync` 强制检查新鲜度。 + +纯生成在此处是正确的,因为代码库足够规范,AST 就是全部事实:每个事件/服务名称都是字符串字面量,可以往返映射到静态声明——不存在动态命名的事件,也不存在仅运行时的服务。因此生成的文档不可能出错,且从结构上消除了未记录事件的缺口(生成器枚举源码,而非校验手写子集)。 + +具体选择: + +- **`@mode` 标签,交叉校验。** 每个 harness 事件的 JSDoc 携带一个显式的 `@mode emit|waterfall|parallel|serial` 标签;缺少标签时生成器直接报错。当签名形状具有决定性时——尾部参数为 `next: () => …` 在结构上即为 waterfall(瀑布式事件)——生成器断言标签与之一致,矛盾时直接报错。emit/parallel/serial 的区别在结构上不可见(`session/flush` 返回 `Promise<void> | void` 且无 `next`,有序的 `agent/pre-step` 检查点亦然),因此信任标签。编写规则见 [AGENTS.md](../../../../AGENTS.md)。 +- **分层范围。** harness 层(8 个 `@deepseek-ai/dsh-*` 服务及其事件)从源码完整渲染。继承层(cordis-core 的 `ctx.on/emit/effect/provide/…` + `internal/*` 事件 + loader/hmr/timer)是插件同样可见的固定 vendor 源码;它从生成器中一张人工维护的表格简洁渲染(名称 + 一行描述 + 源码指针),而非遍历 vendor AST。原因是 cordis-core 的 `Context` 混合了真正的 ctx 成员与非服务字段(`root`、`baseUrl`、`logger`),且 vendor 接口面仅在有意的 vendor 同步时才变化。 +- **指向数据结构目录的交叉链接。** 签名中由仓库拥有的每个类型名(`GenerateOptions`、`StreamChunk`、`ToolDefinition`……)都会通过人工维护的映射链接到其主要核心数据结构页面。AST 遍历采用失败关闭策略:每个参数、泛型约束/默认值和返回类型引用都必须已映射、是签名自身的类型参数、是点名的 TypeScript/Cordis 基础类型,或带有点名的例外及其非目录文档归属。违规会连同源码位置汇总报告,并点明相应的归属列表。该映射不会复用 `type-equiv.manifest.json`,因为后者记录 `…Map` 符号,而签名引用派生的联合类型名,并且会在多个页面列出某些符号。 +- **专用围栏。** 签名块使用 ` ```ts cordis-catalog ` 信息字符串,并把原始事件或公共方法 JSDoc 直接放在其声明之前。`doc-typecheck` 会识别并跳过这些裸片段,将其排除在 opt-out 比例之外——与 `type-equiv` 块的处理相同。 + +本决策**取代** [doc-sync 强制](2026-06-11-doc-sync-enforcement.md)中事件分类的那一半:`verify-event-taxonomy` 及其 `docs/architecture.md` 表格退役(architecture.md 的标题保留,正文改为指向目录;服务映射的角色表格作为人工行文保留)。doc-typecheck、verify-md-wrap、verify-md-links 和 verify-type-equiv 不受影响。 + +## 曾考虑的替代方案 + +- **校验而非生成(退役的分类检查所做的事)**:*仅对本参考面*反转了这一策略。此处的数据可以机械地完整获取,因此生成严格强于对手工表格做名称集合校验(完整签名、不会漂移、能捕获未记录事件)。 +- **遍历 vendor AST 以获取继承层**:否决,改用人工维护表格。cordis-core 的 `Context` 混合了真正的 ctx 成员与非服务字段,且固定的 vendor 接口面仅在有意同步时才变化。 +- **复用 `type-equiv.manifest.json` 作为签名交叉链接映射**:否决,改用完整的人工维护常量和失败关闭覆盖。清单记录 `…Map` 符号,而签名引用派生的联合类型名,并且会在多个页面列出某些符号。显式映射让每个渲染目标和每个非目录例外都成为可评审的决策。 + +## 后果 + +- 目录不会发生漂移:提交文件未反映的源码变化会使 `doc-sync` 和 CI 中的 `verify-cordis-catalog` 失败。新事件缺少 `@mode` 标签、标签与其签名冲突,或签名类型未分类,都会直接使生成器失败。 +- 事件与服务方法契约只有一个归属——声明处的 JSDoc。目录会在生成的签名块中重复该原始 JSDoc,并使用其描述部分作为条目正文,因此单薄的源码文档只会生成单薄的目录条目。 +- 继承层是手工摘要,因此 vendor 同步若新增或重命名了 cordis-core 事件或 `ctx` 成员,需要同步编辑 `gen-cordis-catalog.ts` 中的人工维护表格。这是不遍历固定 vendor 源码的有意代价;它很少变化,且在生成器中有明确标注。 +- `verify-event-taxonomy.ts` 被删除,`docs/architecture.md` 的事件表格也已移除;之前链接到特定表格行的人现在会落在生成目录上。 diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml index a1d901ad15..3bfc8414e7 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.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 -2026-07-02-bilingual-docs-and-pairing-gate.md: 3be1d5d8fd9dba20cfca34c79cb01d89fad8097a -2026-07-02-bilingual-docs-and-pairing-gate.zh.md: a8aa8812934e755fe0175c8f3f20d194e4d24b4a +2026-07-02-bilingual-docs-and-pairing-gate.md: 4bc02878a0ea3f998e411ecc2b064c1626eacf3c +2026-07-02-bilingual-docs-and-pairing-gate.zh.md: 90a0c2f07f68b0fb4e26cd1c4b537a30a829b10f diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md index 3be1d5d8fd..4bc02878a0 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md @@ -13,8 +13,14 @@ This repo's README and docs tree are read by people and agents inside and outsid - **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md). - **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR. - **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: required pairs exist, every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical), excluded (generated or bilingual-by-construction) files stay unpaired, and date-named documents on or after the manifest's `requiredSince` cutoff have complete pairs. The `required` list in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) is a ratchet: each merged translation batch adds its files, so coverage only grows. +- **The enforcement frontier advances in coherent review batches.** A related set enters `required` only when reviewers can evaluate it as a unit. The core frontier groups [architecture](../../../../docs/architecture.md), the [Cordis primer](../../../../docs/cordis-primer.md), [defensive patterns](../../../../docs/defensive-patterns.md), the [glossary](../../../../docs/glossary.md), and [testing](../../../../docs/testing.md) because their terminology, links, and contributor contracts inform one another; admitting only part would leave the enforced corpus internally inconsistent. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it. +- **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration. - **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent. +## Verification + +The verification contract covers each boundary independently. `verify-translation-pairing` pins pair completeness, hashes, switchers, and structure; [`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) pins locale-specific source selection for published pairs; [`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) pins discovery of Loader YAML and exclusion of translation records; and the [translation-prompt runnable snapshot](../../../../scripts/translation-prompt.snapshot.ts) pins the rendered system message, five reviewed example pairs, source request, and consumed response. Together these checks make pair drift, publication drift, configuration misclassification, and model-visible prompt drift review-visible. + ## Alternatives considered - **English as the canonical source with a fingerprint inside the translation** — the design first proposed for this Agent Note: `.zh.md` files carried an HTML comment recording the English source's blob hash, and translation flowed EN → ZH only. Revised in review: the team wants Chinese-first authoring (write and review a Chinese Agent Note, then translate to English) with the two languages holding equal authority, which a one-directional canonical model cannot express. The sidecar record covering BOTH sides replaced the in-file one-directional fingerprint; the blob-hash mechanics survived unchanged. diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md index a8aa881293..90a0c2f07f 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md @@ -13,8 +13,14 @@ Status: implemented - **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。 - **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。 - **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:required 的配对必须存在;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的文件(生成物或本身即双语的)不得配对;凡文件名以日期开头且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,也必须有完整配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `required` 清单只进不退:每个合并的翻译批次将自己的文件加入其中,覆盖面只增不减。 +- **执行红线按连贯的评审批次推进。** 一组相关文档只有在评审者能够将其作为整体评估时,才进入 `required`。核心红线将[架构](../../../../docs/architecture.md)、[Cordis 入门](../../../../docs/cordis-primer.md)、[防御性模式](../../../../docs/defensive-patterns.md)、[术语表](../../../../docs/glossary.md)和[测试](../../../../docs/testing.md)归为一组,因为它们的术语、链接和贡献者契约相互关联;只纳入其中一部分会使受门禁约束的文档集合内部不一致。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。 +- **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。 - **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。 +## 验证 + +验证契约分别覆盖每个边界。`verify-translation-pairing` 固定配对完整性、hash、切换行和结构;[`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) 固定已发布配对按 locale 选择对应源文件;[`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) 固定 Loader YAML 的发现以及翻译记录的排除;[翻译提示词可运行快照](../../../../scripts/translation-prompt.snapshot.ts)则固定渲染后的系统消息、五对经评审的示例、源请求和响应消费结果。这些检查共同使配对漂移、发布漂移、配置误分类和模型可见提示词漂移都可在评审中看见。 + ## 曾考虑的替代方案 - **英文为正典源、指纹放在译文内**:本 Agent Note 最初提出的设计:`.zh.md` 文件携带一条 HTML 注释记录英文源的 blob hash,翻译只沿 EN → ZH 单向流动。评审中修订:团队需要中文先行的撰写方式(先写、先审中文 Agent Note,再译英文),两种语言同权,而单向正典模型无法表达这一点。覆盖**两侧**的伴随记录取代了文件内的单向指纹;blob hash 的机制本身保持不变。 diff --git a/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.i18n.yaml b/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.i18n.yaml new file mode 100644 index 0000000000..65a2b2da28 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-02-tool-schema-catalog.md: c8cc69df428f6eee0f66ed976865afe2a0702448 +2026-07-02-tool-schema-catalog.zh.md: f08cb5b5312dd07f91037a4382bf5e416cae552d diff --git a/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.md b/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.md index 814331af8b..c8cc69df42 100644 --- a/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.md +++ b/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-02-tool-schema-catalog.zh.md) + ## Problem The repository had no single reference for the names, descriptions, and JSON Schemas actually exposed to the model. Source declarations are scattered and runtime-composed, while the existing Cordis and data-structure catalogs cover wiring and vocabulary rather than tools. diff --git a/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.zh.md b/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.zh.md new file mode 100644 index 0000000000..f08cb5b531 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.zh.md @@ -0,0 +1,55 @@ +# Agent Note: 生成式工具 schema 目录(启动并采集) + +Status: implemented + +[English](2026-07-02-tool-schema-catalog.md) | 中文 + +## 问题 + +仓库此前没有一份统一的参考文档来记录实际暴露给模型的工具名称、描述与 JSON Schema。源码声明分散各处且在运行时组合,而既有的 Cordis 目录和数据结构目录覆盖的是接线与词汇,而非工具。 + +## 决策 + +目录通过**启动每个工具插件并读取其已注册 schema** 来生成,而不是解析源码。`scripts/gen-tool-catalog.ts` 在全新的 Cordis `Context` 上挂载每个已发布工具包(package);该上下文还提供 `SystemPrompt`、`ToolRegistry` 以及插件 `apply` 所读取的注入 seam。生成器调用 `ctx.tools.schemas()`——也就是发送给模型的确切 `ToolSchema[]`——随后释放上下文,并为每个包渲染一个 `## <package>` 章节,每个工具附带一个 ` ```json ` `parameters` 块。它与 `gen-cordis-catalog` / `gen-module-graph` 的 CLI 形状一致:默认 `--write` 重新生成;提交副本陈旧时 `--check` 失败;输出具有确定性(按清单排序,工具按名称排序)。`verify-tool-catalog`(即 `--check`)在 `doc-sync` 内运行,因此相关文档变更和 CI 会执行同一项新鲜度检查。 + +### 为何启动而非解析(核心要点) + +Cordis 目录是纯 TypeScript AST 遍历,因为每个事件/服务名都是字符串字面量,可以往返映射到静态声明——AST 即全部事实。**工具 schema 在静态层面不可知**,因此同样的技术会产出一份说谎的文档: + +- `tool-todo` 写了 `enum: [...STATUSES]`——对一个运行时 `const` 的展开。AST 看到的是展开表达式,而非 `["pending","in_progress","completed"]`。 +- 每条 description 都通过字符串**拼接**构建(`'…' + '…'`)。AST 看到的是拼接节点,而非模型实际读到的最终文本。 +- `tool-subagent` 的工具名是 `config.toolName ?? 'subagent'`——加载时选定,并非字面量。 +- MCP 插件可以通过 `ctx.tools.register()` 直接注册**原始 JSON Schema**,完全不经过 `defineTool`,因此结构化枚举 `defineTool(` 调用点会遗漏。 + +唯一准确的真源,是插件加载后注册表实际持有的 schema。启动插件是把[测试策略](../../../../docs/testing.md)中“验证现实,而非自我报告”的准则应用到文档生成器:读取已发布产物,而非重新推导一份。 + +### 恢复「不会静默遗漏」的保证 + +启动有一项 AST 遍历不存在的代价:没有源码声明集合可供枚举,新工具包可能被遗忘。一个**完整性守卫**恢复了这项保证——`assertManifestComplete` 对 `packages/` 下所有 `tool-*` 包进行 glob,若有任何一个不在生成器的启动 manifest 中则直接报错。新工具包在注册之前会导致生成器失败,进而导致 `doc-sync` 失败。这与 Cordis 生成器通过枚举源码免费获得的结构性属性相同,只是为基于启动的生成器重新实现了一遍。 + +### 手动维护的启动 manifest 是不可化约的策略 + +文件系统负责发现工具包清单,完整性守卫负责拒绝遗漏。`TOOL_PACKAGES` 仍然为每个包持有一份显式的启动配方,因为所需的 seam 实现和配置属于策略,不是能从目录布局或注入名称安全推断的事实。 + +### 范围 + +`packages/*/tool-*` 下已发布的产品工具包,每个都使用默认配置启动,包括 `dsh-tool-bash`(`bash`)、`dsh-tool-tasks`(`task_output`、`task_list`、`task_kill`)和 `dsh-tool-subagent`(`subagent`)。仅供示例使用的工具不在范围内。 + +目录的单位是包,而非每个配置化的工具实例。每个包以默认配置启动一次;加载时的别名(如 `subagent_fork`)会注明,但不枚举所有部署排列。部署清单是一个独立的、无界的接口。 + +### 使用普通 `json` 围栏 + +schema 块使用 ` ```json `,而非自定义的 `ts` 系围栏。`doc-typecheck` 只提取 `ts*` 围栏,因此 JSON 块对它不可见——无需 `BlockKind` 接线(不同于 Cordis 目录的 `ts cordis-catalog` 围栏,后者需要加入白名单以避免裸签名片段被编译)。 + +## 曾考虑的替代方案 + +- **纯 TypeScript AST 遍历,如 Cordis 目录**:工具 schema 在静态层面不可知(见上文核心要点):运行时展开、字符串拼接、配置选定的名称,以及原始 `ctx.tools.register()` 注册,都会让 AST 推导出的文档说谎。 +- **从各包的 inject 推断启动配方**:属于[发现包清单提案](../../proposed/process/2026-06-20-discover-package-inventory.md)所警告的「过度聪明」路径;配方保持为手写策略,清单由文件系统发现并由完整性守卫把关。 +- **为 schema 块使用自定义 `ts` 系围栏**:不必要。普通 ` ```json ` 围栏对 `doc-typecheck` 不可见,无需 `BlockKind` 白名单。 + +## 后果 + +- 目录不会发生漂移:提交文件未反映的工具 schema 变化会使 `doc-sync` 和 CI 中的 `verify-tool-catalog` 失败。新增的 `tool-*` 包若未加入清单,会直接使完整性守卫失败。 +- 工具描述文本有唯一归属——源码中 `defineTool` 的 `description`——生成的条目质量取决于它,与 Cordis 目录对事件 JSDoc 施加的强制力相同。 +- 生成器导入并执行工作区包(这是仓库中第一个这样做的脚本;其他脚本只读文本)。它通过根 `tsconfig` 的 `paths` 映射在 `tsx` 下运行,使用与演示和测试相同的未构建源码路径,因此不需要构建步骤。 +- 未来某个工具背后新增一个能力 seam,意味着 manifest 中需要新增一条配方条目(声明要挂载哪些 seam)。这正是上文指出的有意为之的手写成本;仅在新增工具包时才需变更。 diff --git a/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.i18n.yaml b/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.i18n.yaml new file mode 100644 index 0000000000..d3cd78a06b --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-03-documentation-graph-atlas.md: 8b532fdd6f600eba05411588f8277b7cc43b3613 +2026-07-03-documentation-graph-atlas.zh.md: d426735407c0395fd96aed65a49aea0f0fdf6a90 diff --git a/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.md b/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.md index 7969f0e80c..8b532fdd6f 100644 --- a/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.md +++ b/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-03-documentation-graph-atlas.zh.md) + ## Problem The repo already had several high-trust documentation surfaces, each on a different axis: [module-graph.md](../../../../docs/module-graph.md) is generated from package `peerDependencies`, the generated [Cordis events](../../../../docs/cordis-catalog/events.md) and [services](../../../../docs/cordis-catalog/services.md) catalogs are generated from Cordis `Events` and `Context` declarations, [tool-catalog.md](../../../../docs/tool-catalog.md) is generated by booting shipped tool plugins, and [core-data-structures/](../../../../docs/core-data-structures/core.md) uses `ts type-equiv` blocks to keep pasted type definitions synchronized with source. @@ -26,7 +28,7 @@ Every graph page declares one maintenance mode: ### First shipped index -The index links eleven relationship surfaces. Package topology and tool-package affordances live in the existing generated catalogs that already own those facts; the remaining focused diagrams are generated by `scripts/gen-doc-graphs.ts`. +The index links ten relationship surfaces. Package topology and tool-package affordances live in the existing generated catalogs that already own those facts; the remaining focused diagrams are generated by `scripts/gen-doc-graphs.ts`. | Graph | Maintenance mode | Source of truth | |---|---|---| @@ -40,7 +42,6 @@ The index links eleven relationship surfaces. Package topology and tool-package | [event producer/consumer matrix](../../../../docs/event-producer-consumer.md) | hybrid generated | Cordis event declarations, AST-scanned `ctx.on/emit/parallel/serial/waterfall` sites, and explicit dynamic dispatch overrides | | [agent turn and step lifecycle](../../../../docs/agent-lifecycle.md) | curated | architecture.md loop lifecycle, Cordis catalog links, and session event semantics | | [tool execution pipeline](../../../../docs/tool-execution-pipeline.md) | curated | tool pipeline semantics and the `tools/execute` waterfall | -| [ACP snapshot replay](../../../../packages/ui/acp/snapshot-replay.md) | curated | snapshot harness behavior | ### Why generators own the docs @@ -62,7 +63,7 @@ Committed diagrams use Mermaid because GitHub renders it in Markdown and it adds ## Consequences -- Maintainers get visual entry points for topology, seams, event flow, lifecycle, app composition, and snapshot behavior. +- Maintainers get visual entry points for topology, seams, event flow, lifecycle, and app composition. - SDK users get a path from use case to package composition instead of only bottom-up package references. - `doc-sync` now includes `verify-doc-graphs` and `verify-mermaid`, so graph drift and Mermaid syntax errors are caught with the other doc freshness gates. - Future fs and hooks work has a concrete place to land new complexity: fs should expand the capability docs and tool catalog, while hooks should expand the event matrix and tool execution pipeline. diff --git a/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.zh.md b/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.zh.md new file mode 100644 index 0000000000..d426735407 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.zh.md @@ -0,0 +1,69 @@ +# Agent Note: 面向维护者与 SDK 用户的文档关系图索引 + +Status: implemented + +[English](2026-07-03-documentation-graph-atlas.md) | 中文 + +## 问题 + +仓库已经有若干高可信文档表面,各自覆盖不同维度:[module-graph.md](../../../../docs/module-graph.md) 根据包(package)的 `peerDependencies` 生成;生成式 [Cordis 事件](../../../../docs/cordis-catalog/events.md)和[服务](../../../../docs/cordis-catalog/services.md)目录根据 Cordis `Events` 和 `Context` 声明生成;[tool-catalog.md](../../../../docs/tool-catalog.md) 通过启动已发布工具插件生成;[core-data-structures/](../../../../docs/core-data-structures/core.md) 则使用 `ts type-equiv` 块使粘贴的类型定义与源码保持同步。 + +这些参考文档是准确的,但大多是目录式的。维护者仍需自行综合关系:哪些包构成一个能力 seam、哪个应用组装了具体的主干、哪些事件是持久的而哪些是实时的、钩子或策略插件在哪里可以拦截工作、以及哪个面向模型的工具依赖哪个服务。SDK 用户从另一个角度面临同样的问题:「我想要某种行为,应该安装或加载哪个包?应该扩展哪个事件/服务/工具?」 + +钩子子系统使事件的生产者/消费方拓扑与拦截点变得更加重要;文件系统 seam 使能力 seam、策略否决、工具呈现与 SDK 组装路径变得更加重要。如果关系图的范围仅限于一个小的 bash/todo/subagent 表面,它们会立即陈旧。 + +## 决策 + +新增生成式关系图文档,由聚焦的生成器产出并在 [docs/graph-atlas.md](../../../../docs/graph-atlas.md) 建立索引;作为 `doc-sync` 的一部分,通过 `pnpm run verify-doc-graphs` / 现有目录新鲜度检查进行验证。 + +该索引是既有目录之上的关系层。它不取代精确的参考文档,而是链接到它们并解释各部分如何组合在一起。 + +### 维护模式 + +每个关系图页面声明一种维护模式: + +- **Generated(生成)**:所有节点和边均从源码发现;如果已提交的产物陈旧,`--check` 失败。 +- **Hybrid generated(混合生成)**:源码发现清单,一个小型 manifest 对不可约的策略进行分类,完整性守卫在发现的条目未被分类时失败。 +- **Curated(人工策划)**:图表解释设计意图、时序或归属;它由生成器输出以使关系图文档保持为可重新生成的整体,但内容是有意撰写的。 + +### 首批发布的索引 + +该索引链接十种关系表面。包拓扑和工具包所提供的功能位于已经拥有这些事实的现有生成式目录中;其余聚焦图表由 `scripts/gen-doc-graphs.ts` 生成。 + +| 关系图 | 维护模式 | 真源 | +|---|---|---| +| [模块依赖图](../../../../docs/module-graph.md) | 生成式 | `packages/*/*/package.json` 的对等依赖(peer dependency)与包分组路径 | +| [工具 schema 目录与包映射](../../../../docs/tool-catalog.md) | 生成式 | 启动后采集的工具 schema,以及工具包服务/效应元数据 | +| [能力 seam 与核心服务](../../../../docs/capability-seams.md) | 混合生成式 | Cordis 服务声明,以及 `gen-doc-graphs.ts` 中的角色清单 | +| [tui-agent 应用组合](../../../../examples/tui-agent/composition.md) | 混合生成式 | `examples/tui-agent/cordis.yml` 插件列表,以及人工维护的应用/bundle 展开 | +| [headless-agent 应用组合](../../../../examples/headless-agent/composition.md) | 混合生成式 | `examples/headless-agent/cordis.yml` 插件列表,以及人工维护的应用/bundle 展开 | +| [cordis-agent 应用组合](../../../../examples/cordis-agent/composition.md) | 混合生成式 | `examples/cordis-agent/cordis.yml` 插件列表,以及人工维护的应用/bundle 展开 | +| [acp-agent 应用组合](../../../../examples/acp-agent/composition.md) | 混合生成式 | `examples/acp-agent/cordis.yml` 插件列表加人工策划的应用/bundle 展开 | +| [事件生产者/消费方矩阵](../../../../docs/event-producer-consumer.md) | 混合生成式 | Cordis 事件声明、经 AST 扫描的 `ctx.on/emit/parallel/serial/waterfall` 位置,以及显式动态分派覆盖 | +| [agent 轮次与步骤生命周期](../../../../docs/agent-lifecycle.md) | 人工维护 | architecture.md 循环生命周期、Cordis 目录链接,以及会话事件语义 | +| [工具执行管线](../../../../docs/tool-execution-pipeline.md) | 人工维护 | 工具管线语义与 `tools/execute` waterfall(瀑布式事件)| + +### 为什么由生成器拥有文档 + +包拓扑留在 `gen-module-graph.ts`,工具-包能力映射留在 `gen-tool-catalog.ts`,因为这些生成器已经拥有权威事实和新鲜度门禁。`gen-doc-graphs.ts` 拥有其余关系页面和索引。代价是人工策划的图表需要在 TypeScript 字符串块中编辑,而非直接编辑 Markdown。对于首版来说这是可接受的,因为面向用户的产物仍然是纯 Markdown/Mermaid;未来如果撰写体验比可重新生成更重要,可以将人工策划的页面拆分出去。 + +### 完整性守卫 + +混合生成的页面在其 manifest 陈旧时必须显式报错: + +- 模块图读取每个包的 `peerDependencies`,并按 `packages/<group>/<pkg>` 路径对包进行分组。 +- 工具目录通过启动收集已发布的工具,并从同一份 manifest 渲染包/服务/副作用映射(其完整性守卫已在检查该 manifest)。 +- 能力 seam 图导入 Cordis 服务收集器,断言每个发现的 harness `ctx.<key>` 都已在 `SERVICE_ROLES` 中分类,且每个已分类的 key 仍然存在。 +- 事件生产者/消费方矩阵标记为 hybrid,因为 subagent 生命周期事件有意使用 `ctx.events.dispatch` 实现逐监听器隔离;这些动态边是显式覆盖而非无声遗漏。 +- `verify-mermaid` 使用 Mermaid 自身的解析器解析仓库中每个 ` ```mermaid ` 围栏,因此语法错误在本地和 CI 的 `doc-sync` 阶段即被捕获,而非在 GitHub 渲染时才显示为损坏的图表。 + +## 曾考虑的替代方案 + +已提交的图表使用 Mermaid,因为 GitHub 在 Markdown 中原生渲染它且不引入新的文档构建依赖;密集的多对多数据(如事件生产者/消费方关系)改用 Markdown 表格。**PlantUML、托管图表服务和生成的 SVG** 曾被考虑,但在 Mermaid 成为瓶颈之前有意不采用。 + +## 后果 + +- 维护者获得了拓扑、seam、事件流、生命周期与应用组合的可视化入口。 +- SDK 用户获得了从用例到包组合的路径,而非仅有自底向上的包参考。 +- `doc-sync` 现在包含 `verify-doc-graphs` 和 `verify-mermaid`,因此关系图漂移和 Mermaid 语法错误与其他文档新鲜度门禁一起被捕获。 +- 未来的文件系统和钩子工作有了承载新复杂度的具体位置:文件系统应扩展能力文档和工具目录,钩子应扩展事件矩阵和工具执行流水线。 diff --git a/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.i18n.yaml b/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.i18n.yaml new file mode 100644 index 0000000000..21465703e1 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-cordis-jsdoc-completeness-gate.md: c7c39986414437ce4d0d4c64f9e25f47485fdf5c +2026-07-04-cordis-jsdoc-completeness-gate.zh.md: f1e7ec824ebae119c1cb27ca4dd9f0d8330dde1a diff --git a/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.md b/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.md index 3945382217..c7c3998641 100644 --- a/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.md +++ b/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-cordis-jsdoc-completeness-gate.zh.md) + ## Problem The generated Cordis catalog enforced event dispatch modes but not complete service and event contracts. Methods could lack descriptions, and parameters or returns could be undocumented on the cross-plugin API surface where IDE guidance matters most. diff --git a/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.zh.md b/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.zh.md new file mode 100644 index 0000000000..f1e7ec824e --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.zh.md @@ -0,0 +1,41 @@ +# Agent Note: 针对 Cordis 对外服务接口的 JSDoc 完整性门禁 + +Status: implemented + +[English](2026-07-04-cordis-jsdoc-completeness-gate.md) | 中文 + +## 问题 + +生成的 Cordis 目录此前强制了事件分发模式,但未强制要求完整的服务与事件契约。方法可以缺少描述,参数或返回值可以在跨插件 API 接口上不写文档——而这恰恰是 IDE 引导最重要的地方。 + +AGENTS.md 中的规则(「每个导出都有解释语义的 JSDoc」)只能靠评审以行文形式检查;本仓库的既定偏好是将不变式编码为机械门禁。「Cordis 服务函数与事件」这一范围有精确的机器定义,只有目录生成器知道:事件是 `declare module 'cordis'` 内 `interface Events` 的成员,服务接口是每个 `interface Context` 键所指向的类的公开方法。ESLint 规则看不到这层映射;生成器在每次运行时计算它。 + +## 决策 + +扩展 `scripts/gen-cordis-catalog.ts`——复用同一次遍历和同一套 `@mode` 先例——对它编目的所有内容强制执行 JSDoc 完整性要求。`verify-cordis-catalog` 在 `doc-sync` 内运行,因此相关文档变更和 CI 会执行同一门禁,无需另行接线。 + +契约如下: + +- **事件**需要描述性文字,以及为每个**载荷参数**提供非空的 `@param`。载荷参数是携带事件数据的签名参数;`this` 接收者注解和尾部的 waterfall(瀑布式事件) `next` 免检——`next` 是分发机制,其语义已由 `@mode waterfall` 标签(及其结构交叉检查)拥有,逐事件重述只是样板代码。为免检参数写文档是允许的;只有缺失才被检查。 +- **服务类**需要类级 JSDoc,每个公开方法需要描述性文字、为每个参数提供非空的 `@param`,以及非空的 `@returns`——除非标注的返回类型是 `void`/`Promise<void>`(此时 `@returns` 可选——resolve 时机有时值得记录——但从不强制要求)。 +- **陈旧标签报错**:`@param` 命名了一个不存在的参数即为违规,与 `@mode` 与签名矛盾的检查对称。标签描述必须非空;超出此范围的语义质量由评审负责。 +- **遍历可检查的显式性**:门禁是纯 AST 遍历(不使用类型检查器),因此服务方法必须显式标注返回类型(推断的返回类型无法分类),接口参数必须是简单标识符(解构模式没有名称供 `@param` 匹配)。 +- **违规聚合**为一条错误信息,列出所有违规项——修复时一次看到完整清单。此前快速失败的 `@mode` 检查也移入同一份聚合报告,消息文本不变。 + +生成器保留同一源码注释的两种视图:`parseJsDoc` 在第一个块标签处结束条目正文,而 `ts cordis-catalog` 签名块包含原始 JSDoc,并完整保留 `@param`、`@returns` 和 `@mode`。因此,读者可以看到完整的源码契约,而块标签文本不会泄漏到周围正文中。 + +`packages/core/agent/tests/gen-cordis-catalog.spec.ts` 中的负路径测试对合成 fixture(测试前置数据)运行 `collectEvents`/`collectServices`,验证每条守卫都会触发且免检规则成立。撰写规则写在根 [AGENTS.md](../../../../AGENTS.md) 的约定条目中,与 `@mode` 规则并列。 + +## 曾考虑的替代方案 + +- **ESLint 规则**:无法看到该范围的机器定义(哪些 `interface Events` 成员、哪些 `ctx.<key>` 类构成 Cordis 对外服务接口);目录生成器在每次运行时恰好计算这层映射,因此门禁放在那里。 +- **将每个方法展开为单独的正文小节**:否决。目录保留一个服务章节和一个签名块,以维持可扫读性;附着于每个声明的 JSDoc 则在原处保留完整的方法契约。 +- **逃逸标签**:不设。该接口面小且经过策展(采纳时 12 个服务、57 个方法、27 个事件),要点在于检查不可豁免。 + +## 后果 + +- 新事件或服务方法不能带着未记录的参数或结果落地:生成器会拒绝重新生成,`verify-cordis-catalog` 也会使 `doc-sync` 和 CI 失败。采纳时发现的约 139 处缺口已在同一变更中补齐,因此门禁以绿色状态落地。 +- 服务接口必须显式标注返回类型并使用标识符参数。两项约束在采纳时均未构成限制(所有方法已有标注;不存在解构的 seam 参数);但二者现在是承重要求,违反时会被机械检测到。 +- AGENTS.md 中通用的 JSDoc 规则(「一行能说清就用一行」)在此接口上获得了更严格的特例:仅当方法无参数且返回 void 时,一行摘要才足够。 +- 为 `next` 或 `this` 写 `@param` 合法但不检查——这是有意的不对称:门禁强制载荷契约,拒绝要求样板代码。 +- 每个生成的事件或方法片段都带有其原始 JSDoc,而正文摘要不含标签。因此,源码编辑会同时刷新可读索引和签名旁展示的确切契约。 diff --git a/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.i18n.yaml b/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.i18n.yaml new file mode 100644 index 0000000000..45455444d5 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-doc-tiers-and-budgets.md: 7acdba8bfd96d183c418b3935d7b8e7f237d3607 +2026-07-04-doc-tiers-and-budgets.zh.md: 0f07a92740d31dd13cb523d73ac8a3699d666d30 diff --git a/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.md b/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.md index 68e055f0a2..7acdba8bfd 100644 --- a/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.md +++ b/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-doc-tiers-and-budgets.zh.md) + ## Problem Standing docs accumulated repeated rules, retold incidents, duplicated package maps, and stale Agent Note summaries despite existing writing guidance. Because review alone did not prevent that growth, the repository needed a mechanical budget alongside its documentation taxonomy. @@ -16,7 +18,7 @@ Standing docs accumulated repeated rules, retold incidents, duplicated package m ## Alternatives considered - **Skill and review discipline without a gate** — rejected: the accretion above happened while the current-state rule and reviewer attention already existed; a prose rule with no mechanical backstop demonstrably does not hold here, and this repo's own [quality-gates stance](2026-06-11-quality-gates.md) says invariants worth keeping are worth encoding. -- **A broad gate over every doc tier** — rejected: a blanket ceiling punishes exactly the right kind of long doc (a feature matrix or type catalog where every row is a fact, e.g. `packages/ui/acp/acp-feature-support.md`) and generates per-file override churn that trains contributors to rubber-stamp raises. +- **A broad gate over every doc tier** — rejected: a blanket ceiling punishes exactly the right kind of long doc (a feature matrix or type catalog where every row is a fact) and generates per-file override churn that trains contributors to rubber-stamp raises. - **Housing the standard inside the skill** — rejected: contracts live in docs and workflows in skills; a standard packed into SKILL.md is invisible to an agent that edits docs without invoking the skill, and `docs/AGENTS.md` already loads as subtree instructions for anyone working under `docs/`. ## Consequences diff --git a/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.zh.md b/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.zh.md new file mode 100644 index 0000000000..0f07a92740 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.zh.md @@ -0,0 +1,28 @@ +# Agent Note: 文档分层、预算与上限门禁 + +Status: implemented + +[English](2026-07-04-doc-tiers-and-budgets.md) | 中文 + +## 问题 + +尽管已有写作指导,常设文档仍不断累积重复规则、反复讲述的事件、重复的包(package)映射,以及陈旧的 Agent Note(agent 决策记录)摘要。仅靠评审无法阻止这种增长,因此仓库需要在文档分类之外再配一套机械预算。 + +## 决策 + +- **每项事实只归属一处的层级分类。**[docs/AGENTS.md](../../../../docs/AGENTS.md) 是文档标准:它为每种 Markdown 层级分配单一职责(常设指令、系统图、类型目录、决策记录、事件故事、操作指南、各包契约、生成式目录、工作流),禁止在事实归属层级之外重复陈述(应改为链接),并包含编写或评审任何文档时使用的赘余检查清单。 +- **范围窄且严格的预算门禁。**[scripts/verify-doc-budgets.ts](../../../../scripts/verify-doc-budgets.ts) 接入 `doc-sync`:[scripts/doc-budgets.manifest.json](../../../../scripts/doc-budgets.manifest.json) 列出的每份文档都必须低于其字数上限(采用 `wc -w` 语义,统计整个文件);预算内文件缺失也会使门禁失败,使重命名无法悄然遗落其预算。范围刻意只涵盖容易膨胀的常设文档——根目录和子树中的 `AGENTS.md` 文件、`architecture.md`、`packages/README.md`,以及它们将内容移入的常设策略文档(`docs/testing.md`、`docs/defensive-patterns.md`)。参考文档、Agent Note 和包 README 不设预算:只要每一行都是事实,长度在这些位置就是合理的;评审和赘余检查清单负责约束它们。 +- **上限是只进不退的执行红线。** 上限设定为文档当前字数的至少 105%(留出工作余量,使日常措辞调整能通过,而真正的膨胀仍会触发门禁),并随着文档被精简到目标预算而同步下调、保持该余量(根 `AGENTS.md` ≤ 1,500 词;`architecture.md` ≤ 1,800;子树 `AGENTS.md` ≤ 600;`packages/README.md` ≤ 600)。推进机制与[翻译配对的 `required` 清单](2026-07-02-bilingual-docs-and-pairing-gate.md)相同。门禁变红时,修复方式是按分类体系迁移或压缩内容;只有在 PR(Pull Request)描述中给出明确理由时才允许提高上限,manifest(元数据清单)的 diff 本身即为可评审的动作。 +- **精简的工作流 skill(技能),契约归文档。**[.agents/skills/dsh-doc-standards](../../../skills/dsh-doc-standards/SKILL.md) 承载放置/审计/红灯门禁工作流,并以文档标准为真源,与 [dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md) 和 i18n 契约之间的分工相同。 + +## 曾考虑的替代方案 + +- **仅靠 skill 和评审纪律,不设门禁**:否决。上述膨胀正是在现行规则和评审注意力已经存在的情况下发生的;一条没有机械后盾的行文规则在此处已被证明无法维持,而本仓库自身的[质量门禁立场](2026-06-11-quality-gates.md)认为值得保持的不变式就值得编码。 +- **对所有文档层级全面设限**:否决。一刀切的上限恰好惩罚了那些正当的长文档(如特性矩阵或类型目录,每一行都是事实),并产生逐文件的例外变更,训练贡献者机械地批准提限。 +- **将标准放在 skill 内部**:否决。契约归文档,工作流归 skill;如果标准被塞进 SKILL.md,那些不调用该 skill 而直接编辑文档的 agent(智能体)就看不到它,而 `docs/AGENTS.md` 已经作为子树指令被任何在 `docs/` 下工作的人加载。 + +## 后果 + +- 向受预算约束的文档添加内容现在需要置换:将新增内容迁移到其分类体系归属地并留下指针,或压缩现有行文来腾出空间。只增不减会导致 CI 失败。 +- 精简到目标预算的重写以堆叠的后续 PR 落地,每次合并时同步下调 manifest 中的上限;在各自落地之前,文档冻结的上限仅阻止进一步膨胀。 +- 字数是一个粗糙的代理指标,这是有意接受的:它无法判断质量,但它在内容被添加的那一刻强制触发迁移决策,而那正是作者拥有足够上下文来正确放置内容的时刻。 diff --git a/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.i18n.yaml b/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.i18n.yaml new file mode 100644 index 0000000000..00db07d233 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-persistence-log-catalog.md: 1529f41b485c1bc8ca029c0a9264574fa7a886a0 +2026-07-04-persistence-log-catalog.zh.md: f3f77bb66f8798d953fed16bc79cadadc35c036a diff --git a/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.md b/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.md index bde0f08497..1529f41b48 100644 --- a/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.md +++ b/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-persistence-log-catalog.zh.md) + ## Problem `SessionEventMap` is the on-disk vocabulary, but its declarations are split across the owning session package and declaration merges. The generated persistence catalog is the single reference for every event, its complete payload declaration and source JSDoc, and the shared `SessionEvent` envelope; hand-maintained tables drift and are removed. These records are not Cordis events—observers receive them through the single `session/event` bus event—so the Cordis catalog cannot cover them. The generator discovers all declarations and the doc-sync freshness gate rejects omissions or stale output. diff --git a/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.zh.md b/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.zh.md new file mode 100644 index 0000000000..f3f77bb66f --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-04-persistence-log-catalog.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 生成式持久化日志事件目录 + +Status: implemented + +[English](2026-07-04-persistence-log-catalog.md) | 中文 + +## 问题 + +`SessionEventMap` 是磁盘格式的词汇,但其声明分散在所属的会话包(package)和声明合并中。生成式持久化目录是所有事件、各自完整 payload 声明与源码 JSDoc,以及共享 `SessionEvent` 信封的唯一参考;手工维护的表格会发生漂移,因此被移除。这些记录不是 Cordis 事件——观察者通过唯一的 `session/event` 总线事件接收它们——所以 Cordis 目录无法覆盖。生成器会发现所有声明,文档同步新鲜度门禁会拒绝遗漏或陈旧输出。 + +## 决策 + +从源码生成 `docs/persistence-catalog.md`,配合新鲜度门禁,作为第四个参考面:持久化会话日志可以包含的*记录*,与 Cordis 目录(接线)、核心数据结构(词汇)和工具目录(工具)互补。 + +`gen-persistence-catalog.ts` 使用 TypeScript AST 扫描每个所属及声明合并的 `SessionEventMap`。它从前置 JSDoc 开始渲染每个成员,直至完整的 payload 类型,保留嵌套属性注释且只移除其容器缩进;同时粘贴构成持久化信封的所属 `SessionEventType`、`SurfaceEventType`、`SurfaceOp` 和 `SessionEvent` 声明。派生的 surface 徽章、参考链接和源码位置仍位于声明块之外。文档同步新鲜度检查会拒绝目录尚未重新生成的词汇或信封变更。 + +具体选择: + +- **强制保证 JSDoc 完整性。** 每个成员和渲染出的信封类型都必须带有描述正文,完整的源码 JSDoc 会在目录中保持附着于其声明。`@mode` 标签是硬错误:分派模式属于 Cordis 总线事件,持久化记录没有这种模式。所有违规会汇总为一条错误,列出每个违规项。 +- **surface 徽章由派生得出,而非手工列举。** `SurfaceEventType`(产生 LLM(大语言模型)消息且可能携带 `surfaceOp` 的子集)从拥有方包中的 union 声明解析;如果 union 成员命名了一个未声明的事件,则为硬错误(否则陈旧的 union 成员会静默地不标注任何内容)。其余一律渲染为 **log-only**。 +- **专用围栏。** 声明块使用 ` ```ts persistence-catalog ` 信息字符串,`doc-typecheck` 会识别并跳过这些块,将其排除在 opt-out 比例之外——处理方式与 `ts cordis-catalog` 相同(这些声明引用所属模块中的类型,无法独立编译)。 +- **仓库范围。** 目录枚举本仓库中的包,与兄弟文档的 packages-only 范围一致;下游插件可以合并更多事件类型,它们在设计上不在目录范围内。遍历过程用硬错误保护自身假设:拥有方的顶层 `interface SessionEventMap` 必须是 `@deepseek-ai/dsh-session` 中唯一的导出声明(无关的、局部的或同名重复的接口不能被当作磁盘词汇编入目录);任何声明不得携带 `extends`(继承的键会加入 `keyof SessionEventMap` 却没有对应的目录行);每个成员必须是带有显式 payload 类型的属性签名(方法形式的成员会加入 `keyof` 却在静默遍历中被漏过);跨声明的重复成员也会失败。 + +本方案取代了手工副本:session.md 的 `hook/*` 表格、精简版 README 的事件表格、hook-protocol README 的 payload 条目列表,以及会话 README 的名称列表现在链接到目录,而不再重述 payload(周围的语义说明文字保留原位)。hook-protocol 合并成员上的两个误加的 `@mode emit` 标签已被移除——新门禁将它们作为类别错误拒绝。 + +## 曾考虑的替代方案 + +- **基于启动的生成器(类似工具目录)**:日志词汇完全是静态的,AST 遍历无需启动任何东西即可读取全部真相。 +- **保留手工副本**:手工副本只能检查作者已经写下的名称;目录落地时,会话 README 的合并说明已经漂移。 + +## 后果 + +- 目录不会发生漂移:提交文件未反映的词汇或信封变化会使 `doc-sync` 和 CI 中的 `verify-persistence-catalog` 失败,而没有 JSDoc 的新增合并事件会直接使生成器失败——插件不能再添加未记录的磁盘记录类型。 +- 事件正文只有一个归属,即声明处的 JSDoc;目录会保留该 JSDoc 和所有嵌套字段注释,不会将其扁平化或复述。 +- `SurfaceEventType` union 现在对文档具有结构性承载作用:重命名事件而不更新 union(或反过来)会导致生成器失败,而不仅仅是编译器失败。 +- 徽章派生假设 union 始终是一组封闭的字符串字面量且只有一个拥有方;如果重构偏离了这一形状,必须在同一个变更中更新生成器。 diff --git a/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.i18n.yaml b/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.i18n.yaml new file mode 100644 index 0000000000..1cf70223f5 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-05-uniform-agent-note-format.md: 06082251c1b96c90ed470d84224662e00e29791b +2026-07-05-uniform-agent-note-format.zh.md: df6b0f4dfacf122f452807491680091827f69c25 diff --git a/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.md b/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.md index 1a6aa40477..06082251c1 100644 --- a/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.md +++ b/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-05-uniform-agent-note-format.zh.md) + ## Problem Agent Note paths encoded lifecycle and class, but file contents still mixed headings, status formats, ADR and proposal templates, and proposal-era sections in implemented records. Authors copied whichever neighbor they found, and lifecycle moves could skip the required rewrite because no gate enforced an in-file contract. diff --git a/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.zh.md b/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.zh.md new file mode 100644 index 0000000000..df6b0f4dfa --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.zh.md @@ -0,0 +1,30 @@ +# Agent Note: Agent Note 的统一受门禁约束的文件内格式 + +Status: implemented + +[English](2026-07-05-uniform-agent-note-format.md) | 中文 + +## 问题 + +Agent Note(agent 决策记录)的路径编码了生命周期和类别,但文件内容仍混杂着不同标题、状态格式、ADR 与提案模板,以及已实现记录中的提案阶段章节。作者会复制随手找到的相邻文件,而生命周期迁移可能跳过必要的改写,因为没有门禁强制执行文件内契约。 + +## 决策 + +[README.md § 文件格式](../../README.md#the-file-format)是文件内契约——头部块(`# Agent Note: <title>`,加上无日期且与文件夹一致的 `Status:` 枚举,其中只有拒绝原因可作为额外内容)、各生命周期的正文骨架(所有文件均以 `Problem` 开篇;`proposed/` 使用 `Proposal`/`Acceptance criteria`/`Risks`;`implemented/` 使用现在时的 `Decision`/`Consequences`,并禁止提案阶段标题;`rejected/` 冻结提案形状)、强制的 `Alternatives considered` 章节,以及规范章节词汇;定制技术章节可在这些规范章节之间保持自由形式。`pnpm run verify-agent-note-format`([scripts/verify-agent-note-format.ts](../../../../scripts/verify-agent-note-format.ts))作为 `doc-sync` 的一部分强制执行每项机械规则,因此跳过改写的生命周期迁移现在会使 CI 失败,而不再依赖评审者记忆。 + +定义该格式的同一变更规范化了整个语料库——遵循预发布立场:不设过渡期,不容忍双格式。唯一受既有条款豁免的是内容,而非格式:替代方案只能记录、不能杜撰,因此若某份格式制定前的 Agent Note 无法从记录中还原替代方案,就会携带确切的 `agent-note-format: alternatives-not-recorded` 注释;门禁只对日期早于本文的文件接受该注释。 + +## 曾考虑的替代方案 + +- **完整的刚性模板**(每个生命周期使用固定章节顺序,重构每份 Agent Note 以适配):否决。大型设计 Agent Note 包含八到十五个定制技术章节(包(package)拓扑、线协议、schema),它们是承载设计的内容,而非漂移;刚性顺序会迫使我们现在进行破坏性改写,并永远与模板较劲。 +- **仅规范化头部**(H1 和 Status,正文不动):否决。债务标记指出的是*正文*的体裁分裂,让 `Context`/`Decision` 与 `Problem`/`Proposal` 无限期并存什么也解决不了。 +- **不设 Status 行**(文件夹已经表示状态;格式制定前最新的三份 Agent Note 及其中一份的中文对应文件省略了该行):否决,保留文件的自描述性。通过门禁校验该行与文件夹一致,消除了原本促使我们删除它的漂移风险。 +- **带日期的 Status**(`Status: implemented (accepted YYYY-MM-DD)`):否决。接受日期属于叙述性历史,写作规则将其排除在文档之外;文件名承载首次提出日期,git 承载其余信息;门禁能检查日期格式,但永远无法检查其真实性。 +- **裸 `# <title>` H1**:否决。文件脱离目录树单独阅读时,`Agent Note: ` 前缀能自描述其体裁,而格式门禁可防止它漂移。 +- **以 `## What we give up` 作为已实现记录的结尾**(README 对 Agent Note 所记录内容的原有表述):否决。它只点出成本,而诚实的后果章节也会记录取舍换来了什么。 +- **只有约定没有门禁**(写下契约,靠评审强制执行):否决。slop checklist 已经通过约定禁止在 `implemented/` 中使用 spec 语气,而十九个文件展示了仅靠约定在此处能达到什么效果。 +- **独立的 `FORMAT.md` 契约文件**:否决。由一个入口同时承载布局、分类和格式,比维护两个契约文件更易发现和维护。 + +## 后果 + +现在每份 Agent Note 都需要稍多一些结构,而强制的 `Alternatives considered` 章节是有意设置的阻力:记录决策却不记录它胜过什么,会招致 Agent Note 本应防止的重新争论。无法还原替代方案的格式制定前 Agent Note 会永久保留既有条款注释——这是记录中诚实的缺口,而不是杜撰的理由。`doc-sync` 增加一道门禁;在生命周期文件夹之间移动 Agent Note 时,现在必须当场完成真正的工作(迁移本就应包含的正文改写),而不是推迟为无人跟踪的清理任务。三十九个债务标记已经消失,由它们一直等待的模板解决。 diff --git a/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.i18n.yaml b/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.i18n.yaml new file mode 100644 index 0000000000..966ac24d13 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-export-surface-jsdoc-gate.md: 93d8a41fc2ffb235de5c56ffeb5569bc95249392 +2026-07-06-export-surface-jsdoc-gate.zh.md: 64b4bcc620046f2c94a2ce3fbeb67e59ada888d4 diff --git a/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.md b/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.md index 734fbeab21..93d8a41fc2 100644 --- a/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.md +++ b/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-06-export-surface-jsdoc-gate.zh.md) + ## Problem The [cordis JSDoc completeness gate](2026-07-04-cordis-jsdoc-completeness-gate.md) made undocumented parameters and results impossible on the cordis surface — `interface Events` members and `ctx.<key>` service classes — but that surface is a fraction of what a plugin author imports. The AGENTS.md rule "every export (and non-obvious method) has a JSDoc explaining semantics" stayed prose-checkable only by review everywhere else, and nothing at all asked for `@param`/`@returns` on ordinary exported functions. A survey at adoption found 203 under-documented module-level exports across 34 packages: seam-adjacent helpers (`runBash`, `readForEdit`, `htmlToMarkdown`), format codecs, whole undocumented interfaces and type aliases — exactly the names an IDE consumer hovers. diff --git a/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.zh.md b/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.zh.md new file mode 100644 index 0000000000..64b4bcc620 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.zh.md @@ -0,0 +1,45 @@ +# Agent Note: 导出表面 JSDoc 门禁 + +Status: implemented + +[English](2026-07-06-export-surface-jsdoc-gate.md) | 中文 + +## 问题 + +[Cordis JSDoc 完整性门禁](2026-07-04-cordis-jsdoc-completeness-gate.md)使得 Cordis 表面上的参数和返回值不可能缺少文档——`interface Events` 成员和 `ctx.<key>` 服务类——但这只是插件作者所导入内容的一小部分。AGENTS.md 中的规则「每个导出(以及非显而易见的方法)都必须有解释语义的 JSDoc」在其他地方只能靠评审以行文方式检查,而且没有任何机制要求普通导出函数带 `@param`/`@returns`。采纳时的一次调查发现 34 个包(package)中有 203 个文档不完整的模块级导出:seam 相关辅助函数(`runBash`、`readForEdit`、`htmlToMarkdown`)、格式编解码器、完全无文档的接口和类型别名——恰恰是 IDE 消费方悬停查看的那些名称。 + +## 决策 + +新增门禁 `scripts/verify-export-jsdoc.ts`(`pnpm run verify-export-jsdoc`,接入 `doc-sync`(文档同步门禁),与 `verify-cordis-catalog` 并列),遍历每个 `packages/<group>/<pkg>/src/` 目录树下的所有模块级导出名称。解析与检查辅助函数从 `gen-cordis-catalog.ts` 移入共享的 `scripts/jsdoc.ts`,使得「已文档化」在两个表面上含义一致:描述性文字在第一个块标签处截止、每个可检查参数需要非空 `@param`、非 void 且有显式标注的返回值需要非空 `@returns`、过时的 `@param` 报错,违规项汇总为一份报告。 + +按声明类型划分的契约: + +- 每个导出名称都需要带有非空描述文字的 JSDoc。 +- 函数类导出(函数声明;初始化器为函数或带有内联可调用标注的 const;非标识符的函数默认导出)遵循完整的函数契约,分类前会剥离包装表达式(括号、`as`/`satisfies` 类型断言、非空断言)。如果 const 声明器标注了一个具名类型(`export const f: Handler = …`),签名契约推迟到该类型自身的声明处,`@returns` 保持可选;内联的 `(x: T) => U` 标注或单调用签名字面量本身就是表面签名,适用完整契约;而混合了调用/构造签名与其他成员的字面量则直接拒绝(没有单一签名可供标签对照——请提取具名类型)。 +- 导出类需要类级别的描述文字;公开方法(包括静态方法——可通过导出名称访问)遵循函数契约;公开属性和访问器需要描述文字(get/set 对由 getter 覆盖)。重载实现体免检——签名承载文档。 +- 导出接口、类型别名和枚举需要声明级别的描述文字;成员级别的强制有意推迟(承载关键成员契约的 seam 服务类已在 Cordis 门禁之下)。 +- 导出命名空间递归检查(在 ambient `declare` 命名空间内,每个成员隐式导出);命名空间本身仅在不与同名的已文档化声明合并时才需要描述文字(Config-namespace 惯用法只需文档化插件一次)。 +- `declare module`/`declare global` 体和 `export … from` 重导出语句被跳过:augmentation 不是包的导出,重导出的定义在其定义处检查。`export import X = N.member` 别名需要文档化自身——其目标可能是遍历不会访问的非导出命名空间成员——且门禁仅支持纯描述文字的目标类型:可调用、类或命名空间目标携带别名描述文字无法承载的签名/成员契约,门禁会拒绝并要求直接导出该声明。 +- 其余情况按封闭原则失败:`export =` 直接拒绝;基类从未命名的参数即使作为绑定模式仍需 `@param`;dispatch 不识别的导出语句类型本身就是违规——没有任何导出形式能因遗漏而免检。 + +三类豁免避免门禁要求样板代码,精神与 Cordis 门禁的 `this`/`next` 豁免一致(为已豁免的名称编写文档是允许的;只有缺失才不被检查): + +- **继承成员。** 重写从其基类声明继承文档。新增的公开表面仍需文档:新增参数、将 protected 成员公开重写、或在 void 基类之上返回具体类型。继承查找和推断返回值分类是门禁唯一需要类型检查器的工作;其他检查使用 AST。 +- **插件协议槽位。** 顶层的 `name`/`inject`/`reusable`/`Config` 常量和 `apply` 入口,以及插件类上的同名静态成员,属于框架协议:其形状由 Cordis 固定,模块文档注释加 `interface Config` 承载插件的真实语义。 +- **构造函数**,与 Cordis 门禁一致:插件类由框架构造,类文档承载全部说明。 + +`collectExportJsdocViolations()` 返回违规列表(CLI(命令行界面)在非空时以 1 退出),因此 `packages/core/agent/tests/verify-export-jsdoc.spec.ts` 中的负路径测试直接断言发现项,通过 fixture(测试前置数据)包驱动每一种拒绝和每一种豁免。 + +## 曾考虑的替代方案 + +- **eslint-plugin-jsdoc**(`require-jsdoc`/`require-param`/`require-returns`):覆盖了机械核心,但无法表达本仓库的契约。继承成员豁免需要跨包的类型解析,协议槽位和命名空间合并惯用法是 Cordis 特有的,而完整性语义(标签前描述文字、过时标签报错、汇总报告)已在 `scripts/jsdoc.ts` 中与 catalog 生成器共享。两套微妙不同的「已文档化」定义,正是本仓库「单一归属」规则所要防止的失败模式。 +- **扩展 `gen-cordis-catalog.ts`**:catalog 生成器渲染一个精选表面并守卫其新鲜度;仓库级遍历没有 catalog 可渲染。共享辅助函数、保持遍历独立,使每个门禁的职责清晰可读。 +- **强制接口/类型别名的成员文档**:推迟。这会使检查表面成倍增长,而这些成员大多是自描述的字段;承载关键成员契约的 seam 服务类已有门禁。如果评审中出现成员文档漂移再重新考虑。 + +## 后果 + +- 新导出不能在缺少文档的情况下落地:`verify-export-jsdoc` 会使 `doc-sync` 和 CI 失败。采纳时发现的 203 处缺口已在同一变更中补齐,因此门禁以绿色状态落地。 +- 导出函数必须标注返回类型(采纳时已全面满足,现在成为门禁依赖),并在 `@param` 需要命名参数时使用标识符参数。 +- seam 文档是权威的:实现从其继承链继承文档,值得保留在实现上的行为说明是补充,而非必需。 +- 门禁构建一个 `ts.Program`(约 6 秒)——唯一需要类型解析的文档门禁;在已编译文档片段的 `doc-sync` 内可以接受。 +- 协议槽位名称按约定保留在模块顶层;一个恰好命名为 `apply` 或 `Config` 的非协议导出将不被检查——已接受,记录于此。 diff --git a/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.i18n.yaml b/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.i18n.yaml new file mode 100644 index 0000000000..17473bf069 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-generated-config-catalog.md: f39f5138526d3278e839ee0053d5051bb8bc1c36 +2026-07-06-generated-config-catalog.zh.md: 825046914dad8e1a7d87340a310b252f03cbecb9 diff --git a/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.md b/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.md index f876191be4..f39f513852 100644 --- a/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.md +++ b/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-06-generated-config-catalog.zh.md) + ## Problem The repository had no source-backed reference for plugin configuration. Package READMEs documented fields inconsistently, did not enumerate which packages are loadable, and did not verify that runtime schemas agree with declared config types. diff --git a/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.zh.md b/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.zh.md new file mode 100644 index 0000000000..825046914d --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-generated-config-catalog.zh.md @@ -0,0 +1,40 @@ +# Agent Note: 生成式插件配置目录 + +Status: implemented + +[English](2026-07-06-generated-config-catalog.md) | 中文 + +## 问题 + +仓库此前没有以源码为后盾的插件配置参考。各包(package)的 README 对字段的记录方式不一致,未列举哪些包可被加载,也未校验运行时 schema 与声明的配置类型是否一致。 + +## 决策 + +`scripts/gen-config-catalog.ts` 根据各插件声明的 config 类型和 JSDoc 生成 [docs/config-catalog.md](../../../../docs/config-catalog.md),并包含注入要求、被引用类型的链接和源码位置。包内类型会以传递方式纳入;workspace 类型和外部类型则会链接或点名。确定性的 `--write` 和 `--check` 模式使提交页面成为生成产物。 + +此处采用纯 AST 生成是正确的,原因与事件/服务目录相同,而与工具目录不同:配置类型是静态声明,仓库中每个 schemastery schema 都是静态的 `z.object`/`z.intersect` 字面量,因此源码即全部真相——配置表面没有任何部分是运行时组合的。 + +具体选择: + +- **配置类型是第二参数的类型。** catalog 记录的是 `apply(ctx, config)` / 服务构造函数 `(ctx, config)` 的声明参数类型——即 Cordis 实际传入的值——而非按命名约定定位的 `Config` 导出。这使得遍历是全量的:无论接口叫 `AcpConfig` 还是 `BasicCompactConfig`,无论类型声明在兄弟文件中,还是插件完全没有验证 schema,都能正常工作。 +- **分类是全量的。** 每个 `packages/<group>/<pkg>` 条目都会被解析(镜像 Loader 的 `unwrapExports`:`exports.default ?? exports`),归入可配置插件、无配置插件、抽象 seam 类或库之一——各自渲染在独立小节中——无法归类的条目直接报错。新包不可能被悄悄遗漏。 +- **逐字段 JSDoc 强制要求。** 粘贴的声明中每个属性(包括嵌套的类型字面量)都需要非空的 JSDoc 描述,否则生成失败。粘贴本身就是文档,因此这与 events catalog 通过 `@mode` 施加的强制函数相同:源码文档过于单薄时门禁报错,而非产出单薄的 catalog。 +- **Schema 键与声明类型做比对。** 生成器通过局部和 workspace 类型解析嵌套的对象与数组路径。确定缺失的路径报错;无法枚举的外部或动态形状则跳过。比对有意设计为单向的,因为声明类型可能包含被排除在 loader 配置之外的运行时专用字段。 +- **专用围栏。** 粘贴的声明使用 ` ```ts config-catalog ` 信息字符串,`doc-typecheck` 会跳过它(引用了导入类型的孤立声明无法独立编译),并将其排除在 opt-out 比例之外——与 `cordis-catalog` 和 `persistence-catalog` 围栏的处理方式相同。 +- **单文件 `docs/config-catalog.md`**,而非一个单文件目录:该页面面向单一受众(`cordis.yml` 的编写者),只有一个维度,不同于 `cordis-catalog/`(其中包含两个并列页面)。 + +各包 README 中的 `## Config` 小节保留。重叠是有意接受的:README 是经过策划的逐包契约(在部署上下文中描述配置语义,连同限制与扩展点),catalog 则是穷举式的生成枚举。由于 catalog 是生成的,二者不一致时说明 README 有误,修复方式是编辑 README——catalog 不会漂移。 + +## 曾考虑的替代方案 + +- **合成式逐字段渲染**:为每个字段生成项目符号列表、表格或带注释的 YAML 片段,从解析的 JSDoc 加 schema 元数据组装。否决,改用逐字粘贴:接口连同其 JSDoc 本身就是以原始形式撰写的契约,合成渲染器会重新格式化它不拥有的行文,增加一个可能歪曲原意的渲染层。 +- **运行时启动 + schema 内省(如工具目录所做的那样)**:否决。此处没有任何内容是运行时组合的,且 schema 本身对配置表面的文档化不足(以行文记录的默认值、运行时专用字段、完全没有 schema 的插件)。启动只会增加脆弱性而不增加真相。 +- **双向 schema/接口等价检查**:否决,改用子集检查。声明类型合理地包含 schema 拒绝从配置接受的成员(运行时专用 seam)。 +- **在同一变更中废除 README `## Config` 小节**:否决。保留可接受的重叠使逐包契约在原处可读,而清理工作需要先把每个 README 的额外事实折入字段 JSDoc——这是可分离的工作,catalog 不依赖它。 + +## 后果 + +- 目录不会发生漂移:提交文件未反映的源码变化会使 `doc-sync` 和 CI 中的 `verify-config-catalog` 失败。config 字段未记录、被引用类型名无法解析,或 schema 键未出现在 config 类型中,都会直接使生成器失败。 +- 配置行文现在有了声明处的强制函数:编写新配置字段意味着编写其 JSDoc,而该 JSDoc 将逐字成为 catalog 条目。 +- 生成器对无法静态遍历的形状直接报错——别名化的包内配置导入、非 `object`/`intersect` 组合构建的 schema、未列入的全局类型名。引入此类形状时必须同时教会生成器(否则该形状不能进入仓库),这正是设计意图:catalog 始终是全部真相。 +- `gen-cordis-catalog.ts` 导出其 JSDoc/指针辅助函数与 `LINK_MAP` 供复用,因此两个 catalog 以相同方式交叉链接类型,新增一条 link-map 条目同时服务于两者。 diff --git a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.i18n.yaml b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.i18n.yaml new file mode 100644 index 0000000000..2cb7f1009d --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-node-engine-floor.md: f1754ea7ca32452a04c6cd8a0599568f602e47dd +2026-07-06-node-engine-floor.zh.md: 9d376a639378d3a0b9b645aa36c1a5d320d1d147 diff --git a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.md b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.md index 507641a99a..f1754ea7ca 100644 --- a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.md +++ b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-06-node-engine-floor.zh.md) + ## Problem The Node 22 branch of the root `engines.node` range is a contract for the installed workspace, not only for the runtime APIs the harness source calls directly. It must be no lower than package `engines.node` declarations for dependencies the workspace installs on that branch; otherwise `pnpm install --engine-strict` fails at an advertised LTS version, and non-strict installs run outside a dependency's supported runtime. diff --git a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.zh.md b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.zh.md new file mode 100644 index 0000000000..9d376a6393 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 将 Node LTS 引擎下限提升至 22.19 + +Status: implemented + +[English](2026-07-06-node-engine-floor.md) | 中文 + +## 问题 + +根 `engines.node` 范围中的 Node 22 分支是对已安装工作区的契约,而不仅仅是 harness 源码直接调用的运行时 API 的契约。它不得低于工作区在该分支上安装的依赖包(package)所声明的 `engines.node`;否则 `pnpm install --engine-strict` 会在一个已宣传的 LTS 版本上失败,而非严格模式的安装则会在依赖所支持的运行时范围之外运行。 + +## 决策 + +将 `engines.node` 设为 `^22.19.0 || >=24.0.0`,并在 keyless CI 兼容性矩阵中测试 `['22.19', 24, 26]`。每条矩阵分支都运行 TypeScript 类型检查加一次 keyless 的源码模式 worker 冒烟测试,因此引擎下限通过完整的源码类型检查和真实的未构建运行时路径两条路径得到验证。真实 API 的 e2e 工作流保持在 Node 24 上,因为它验证的是 API 集成而非运行时下限。 + +两个 Node 特性决定了源码运行时的门槛: + +- **`node:sqlite`**:`packages/session-persistence/session-persistence-sqlite` 在顶层执行 `import { DatabaseSync } from 'node:sqlite'`。该模块在 **22.13**(LTS)和 **23.4**(Current)取消了 `--experimental-sqlite` 标志要求;在此之前,导入它会在加载时抛出异常。 +- **原生 TypeScript 类型剥离**——构建模式的 `examples/headless-agent/tests/keyless-smoke.e2e.ts` 冒烟测试使用纯 `node`(无 tsx)启动 `dsh-cli-demo` 已发布的 `lib/bin.js`,并加载示例的 `.ts` 测试适配器(`cli-mock-llm.ts`)。类型剥离从 **22.18**(LTS)和 **23.6**(Current)起成为默认行为;更早版本需要 `--experimental-strip-types`。 + +这些源码特性在 22.x 线上于 **22.18** 全部就绪,但已安装的 Pi 适配器依赖将宣传的 LTS 下限进一步提高。`@deepseek-ai/dsh-llm-pi-ai` 依赖 `@earendil-works/pi-ai@0.79.3`,后者的包声明 `engines.node >=22.19.0`,因此 LTS 下限为 **22.19**。24.x 分支保持 `>=24.0.0`。该不相交范围完全排除了 Node 23:Node 23.0–23.5 至少还有一个源码特性需要标志,而 23 线是非 LTS/已 EOL 的,宣传 `>=23.6` 会增加一条已终止的发布线和一条 CI 分支,而没有任何部署应当使用它。 + +`@types/node` 继续固定在 22.x 线(`^22.20.0`),以匹配 LTS 支持线:使用 Node 23+/24+/25+ 的 API 会在所有机器和类型检查门禁中导致 `tsc` 失败,而不是编译通过、直到仅下限矩阵分支才能捕获的运行时错误才暴露。目前整个代码树在 Node 22 类型表面上类型检查全部通过,因此这一固定没有任何代价。 + +## 后果 + +- 宣传的 LTS 分支不再低于 Pi 适配器依赖的下限。 +- CI 通过 Node 22.19 直接验证 Node 22 LTS 下限,Node 24 分支保持 `node: 24`,Node 26 用于下一个偶数线;每条分支都对源码图执行类型检查,并实际启动未构建的工作流 worker。 +- built-bin 冒烟测试无需版本条件标志:在 22.19 上类型剥离已是默认行为,因此测试保持其文档所述的纯 `node lib/bin.js` 路径。 +- 未来若依赖或源码 API 提高运行时下限,必须在同一变更中同步调整 `engines.node`、兼容性矩阵和本 Agent Note(agent 决策记录)。 + +## 曾考虑的替代方案 + +- **保持 `^22.18.0 || >=24.0.0`。** 否决:它宣传的 LTS 版本低于 Pi 适配器依赖的下限。`@earendil-works/pi-ai@0.79.3` 要求 `>=22.19.0`。 +- **降级或固定 `@earendil-works/pi-ai` 以保留 22.18 的宣传范围。** 否决:当前 Pi 适配器依赖是预期工作区的一部分,且 22.19 仍在 Node 22 LTS 线内。 +- **下限 `>=22.13`(`node:sqlite` 边界)加上在 22.13–22.17 的 built-bin 冒烟测试中使用 `--experimental-strip-types`。** 否决:它为一个狭窄范围增加了版本条件测试标志,并将实验性标志依赖包装为正式支持。Pi 适配器依赖已经要求更高的 LTS 下限。 +- **开放式 `>=22.19`。** 否决:它宣传支持 Node 23.0–23.5,而在这些版本上 `node:sqlite`(直到 23.4)或类型剥离(直到 23.6)仍需标志。 +- **包含 Node 23.6+(`^22.19.0 || >=23.6.0`)。** 否决:23.6+ 确实能无标志运行两个源码特性,但 Node 23 已 end-of-life;宣传一条已终止的发布线会增加一个范围项和一条 CI 分支,而没有任何部署应当使用该运行时。 +- **矩阵 `[22, 24, 26]` 而非固定 `22.19`。** 否决:浮动的主版本号条目会随时间上漂,悄然不再验证所声明的 LTS 下限。 +- **保持 `@types/node` 超前于运行时下限(`^25`)。** 否决:类型定义超前于运行时下限会让仅 Node 24/25 才有的 API 编译通过,仅在 22.x 上运行时才失败。将 `@types/node` 固定在 22.x 线上可将此类问题转化为所有环境下的编译错误。 diff --git a/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.i18n.yaml b/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.i18n.yaml new file mode 100644 index 0000000000..9aa8a03c52 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-parallel-github-ci-gates.md: 5c276f6a75936021369bc5ad9494c9aa6e4e3fc3 +2026-07-06-parallel-github-ci-gates.zh.md: 7d98f842ef1d60a3a5b727f975cb1d93ea6f253c diff --git a/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.md b/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.md index fef5852153..5c276f6a75 100644 --- a/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.md +++ b/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-06-parallel-github-ci-gates.zh.md) + ## Problem The keyless GitHub CI gates are mostly orthogonal: typecheck, lint, documentation freshness, coverage, snapshot replay, build, package-publication hygiene, demo smoke, and built-bin smoke fail for different reasons and do not need each other's runtime state. Running them as one ordered command chain makes the workflow wall clock equal the sum of those gates, while splitting every short leaf into its own GitHub job repeats checkout, Node setup, pnpm restore, and install work until orchestration overhead becomes the bottleneck. diff --git a/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.zh.md b/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.zh.md new file mode 100644 index 0000000000..7d98f842ef --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.zh.md @@ -0,0 +1,50 @@ +# Agent Note: 并行 GitHub CI 门禁 + +Status: implemented + +[English](2026-07-06-parallel-github-ci-gates.md) | 中文 + +## 问题 + +无密钥 GitHub CI 门禁大多相互正交:类型检查、lint、文档新鲜度、覆盖率、快照重放、构建、包(package)的发布卫生检查、demo 冒烟和已构建二进制冒烟会因不同原因失败,也不需要彼此的运行时状态。将它们作为一条有序命令链运行,会使工作流墙钟时间等于所有门禁耗时之和;而把每个短小叶子拆成独立 GitHub job,又会反复执行 checkout、Node 设置、pnpm 恢复和安装,直到编排开销成为瓶颈。 + +随着 workspace 增长,原有的宽车道拆分不再满足这一平衡。PR(Pull Request)#404 合并时,Linux 的静态、覆盖率、快照和产物 job 分别耗时 148、195、94 和 230 秒;Windows 的静态和产物 job 分别耗时 251 和 482 秒。每个包都调用一次包管理器打包,主导了两个产物验证器的耗时;覆盖率在仅运行源码的套件前无谓地重建输出;CPU 密集型门禁则在静态与覆盖率车道内争用资源。 + +产物边界仍然承载关键约束。`publint`、`verify-node-next-types`、已编译不变量加载和已构建二进制冒烟测试都需要生成的 `lib/` 输出。分片不能让这些消费方抢在构建前运行,也不能用源码执行取代它们对已发布产物的信号。 + +## 决策 + +下述生产拓扑已经成为历史,并由[基于证据采用更大的托管 runner](2026-07-22-evidence-based-larger-hosted-runners.md) 取代。更大 runner 的决策移除了其分片选择器和工作流 job;本文保留早期拓扑为何被实现的记录。 + +[CI](../../../../.github/workflows/ci.yml) 将非 Windows job 的一分钟和 Windows job 的三分钟视为观测所得的性能目标,而非取消截止时间。托管 runner 的波动应留下完整计时证据和有用的失败日志,而不是取消本来正确的门禁。[串行跨平台 CI 参考](2026-07-21-serial-cross-platform-ci-reference.md)会在 Linux、macOS 和 Windows 上独立运行完整、未分片的主 Node 聚合,使优化后的车道清单不会成为自身完整性的唯一判据。 + +在该拓扑中,[scripts/run-gates.ts](../../../../scripts/run-gates.ts) 是通用的有界调度器,GitHub 则为昂贵的门禁族提供显式分片名称。`scripts/static-shards.ts` 将静态门禁划分为基础、文档类型、API 契约、目录、正文、文档投影和文档构建等归属,并拒绝缺失或重复的门禁分配。Linux lint 使用互不重叠的 A-C、D-M、N-S、T-Z 包源码和包测试车道,Windows 则使用完整的包源码与包测试车道;两者都包含从 `.` 开始的仓库补集,使新增顶层目标无法消失在分片之间,并负责唯一一次跨文件重复检查。`scripts/coverage-shards.ts` 把每个 workspace 包恰好分配给一个源码覆盖率车道。目录过滤器保留尾部分隔符,因为 Vitest 位置过滤器按子字符串匹配,否则会纳入具有同名前缀的相邻项。每个覆盖率车道只包含其拥有的源码文件,重复运行穷尽式伴随拓扑测试,并且不先执行构建,因为从删除了所有生成式 `lib/` 的树开始,完整覆盖率套件仍可通过。 + +快照重放使用两个显式多文件车道,以及大型 ACP(Agent Client Protocol)文件的八个场景分区。`scripts/snapshot-shards.ts` 拥有该清单,其测试会发现快照配置允许的每个文件。每个快照 job 在其 Linux runner 准备 Bubblewrap 的同时安装依赖,随后构建已发布运行时,并且只运行分配给它的重放表面。该套件保留五个子进程的有界并发,因为重放的大部分时间都在等待子进程协议 I/O。fixture(测试前置数据)守卫仍会在每个分区中检查完整 ACP 场景表。 + +冷启动的独立文档类型检查会重建完整的项目引用图,因此专用文档类型车道只构建一次,再用这些声明检查 Markdown 块。Linux 文档车道使用 VitePress 的 MPA 构建,在观测所得的非 Windows 目标内保留页面渲染与死链接验证;单独的阻塞式 Windows 构建和生产站点车道保留已生成包与已发布站点检查,同时避免把两条关键路径放进同一个 job。 + +产物使用两个车道:一个元数据车道负责 `publint`、NodeNext 声明和已编译不变量加载,另一个负责已构建二进制冒烟。每个车道都会在其消费方之前自行构建。重复短时构建会消耗 runner 分钟数,但避免了上传/下载依赖,并使每个 job 的关键路径保持有界。 + +[scripts/publint-all.ts](../../../../scripts/publint-all.ts) 在进程内针对内存发布视图调用 publint 支持的 API;该视图由每份清单声明的文件和 npm 强制元数据文件构成。这样无需生成 103 次包管理器打包命令,也能保留 workspace 文件与已发布文件之间的区别。[scripts/verify-built-package-invariants.mjs](../../../../scripts/verify-built-package-invariants.mjs) 在真实包下暂存这些经过结构验证、由清单声明的 `lib/` 文件,再通过纯 Node 和 Cordis Loader 规范化导入已编译的自引用。若伴随项触及未声明的运行时分片,仍会失败。 + +兼容性车道会在每条声明支持的 Node 版本线上运行源码 worker 和 Zstandard 运行时冒烟。TypeScript 在专用的主 Node 24 车道中只检查一次源码图;在运行时兼容性 job 中重复同一编译器分析只会增加耗时,不会提供运行时特有信号。 + +工作流缓存 pnpm store,将每个不可变 ESLint 缓存的键绑定到其所属 lint 分片,为 Windows 测量保留原生 PowerShell,并保留一个聚合的 `all checks passed` 状态用于分支保护。Windows 复用三个穷尽式 lint 分区,并在共享 runner 设置后组合基础/目录/正文门禁与文档类型/API 契约门禁;只有调度方式与 Linux 分区不同。Windows 构建和生产站点验证继续阻塞,而更广泛的 Windows 静态、lint 和产物矩阵仍为观察性检查。 + +## 曾考虑的替代方案 + +- **保留宽车道**:最大限度减少工作流 YAML,但会保留观测到的数分钟反馈周期。 +- **让每个叶子门禁分别成为 GitHub job**:最大化扇出,但短小的生成器和正文检查准备 runner 的时间会超过检查仓库的时间。 +- **向产物消费方上传一次构建**:避免重复编译,但上传/下载和依赖调度会延长墙钟时间;干净构建足够短,可以在有界车道内重复。 +- **在两个发布门禁中保留包管理器打包**:把清单选择委托给 pnpm,但会重复启动 200 多个包管理器进程。清单结构门禁加发布视图 fixture 使优化后的清单契约显式化,并会在存在磁盘上有但未发布的依赖时失败。 +- **在覆盖率前保留构建**:提供源码套件已不再消费的生成输出;干净树覆盖率证明表明这只是纯粹的延迟。 +- **在每个 Node 版本上执行类型检查**:重复编译器工作,而兼容性冒烟已经验证实际的 Node 特有加载与压缩行为。 + +## 后果 + +上述分片清单和矩阵 job 不属于当前仓库契约。取而代之的更大 runner 决策在单个进程中保留完整主清单,并以串行套件作为独立完整性判据。 + +优化后的发布验证器依赖由 `verify-package-invariants` 强制执行的清单 `files` 契约。如果发布规则超出该契约,结构门禁和两个暂存视图必须一起变化。 + +兼容性 job 不再声称 TypeScript 本身已在每个 Node 运行时下执行。它们证明 Node 22、24 和 26 上对运行时敏感的源码加载,而主运行时负责唯一一次源码图类型检查。 diff --git a/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.i18n.yaml b/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.i18n.yaml new file mode 100644 index 0000000000..0360eacf60 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-parallel-pre-push-gates.md: f2e8f0054e595be20a320ec7095f0fe674eb93c6 +2026-07-06-parallel-pre-push-gates.zh.md: 03b8773e475a9d1c82cea830cae6806a1c016f01 diff --git a/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.md b/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.md index 87b1c0847b..f2e8f0054e 100644 --- a/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.md +++ b/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-06-parallel-pre-push-gates.zh.md) + The local-hook portion of this record is superseded by [Fast local Git hooks](2026-07-22-fast-local-git-hooks.md). The bounded gate scheduler and package-level `publint` parallelism remain in force for CI, `doc-sync`, and explicit local commands. ## Problem diff --git a/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.zh.md b/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.zh.md new file mode 100644 index 0000000000..03b8773e47 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 并行 pre-push 门禁 + +Status: implemented + +[English](2026-07-06-parallel-pre-push-gates.md) | 中文 + +本记录中的本地 hook 部分已由[快速本地 Git hook](2026-07-22-fast-local-git-hooks.md) 取代。有界门禁调度器和包(package)级 `publint` 并行机制仍用于 CI、`doc-sync` 和显式本地命令。 + +## 问题 + +文档同步等聚合 job 隐藏了很长的串行链,其成员只读且相互独立。在工作流 YAML 中重复这些叶子清单,会使未来脚本变更有多个位置可以发生漂移;而串行运行包发布检查,会使一道门禁的耗时与包数量成正比。 + +## 决策 + +[scripts/run-gates.ts](../../../../scripts/run-gates.ts) 拥有 CI、`doc-sync` 和选择启用的 `check:all` 命令所使用的有界调度器。它将具名模式展开为叶子门禁,遵守产物依赖,缓冲可归因的输出,并在调用方需要不同 worker 上限时接受 `DSH_GATE_CONCURRENCY`。 + +[scripts/publint-all.ts](../../../../scripts/publint-all.ts) 从 `packages/<group>/<pkg>` 发现包,并以根据 `availableParallelism()` 确定大小的 worker 池运行 `publint`。`DSH_PUBLINT_CONCURRENCY` 可以针对资源配置不同的本地机器和 CI runner 限制或提高 worker 数量。结果按包缓冲,并按确定性的包顺序打印,因此并行执行不会打乱各包的日志块。 + +各门禁的包脚本仍是临时本地运行所用的词汇。`hygiene` 继续作为聚合 `&&` 链,而 `doc-sync` 在调度器中拥有其成员列表([通过门禁调度器运行 doc-sync](2026-07-21-doc-sync-through-gate-scheduler.md))。 + +## 曾考虑的替代方案 + +- **保持聚合 job 串行**:执行更简单,但墙钟时间等于各独立检查之和,并重复启动命令包装器。 +- **每个叶子门禁声明一个 CI job**:暴露最大工作流并行度,但会重复 checkout、设置和安装开销,并在 YAML 中复制调度器清单。 +- **在 shell 脚本内后台运行子命令**:可以并行处理,但会失去各门禁计时、确定性的失败分组和直接的信号处理。 +- **每个包声明一个 `publint` job**:暴露最大包级并行度,但会创建手工维护的包清单,包发生变化时就会漂移。 +- **以无界并发运行 `publint`**:只有通过拿进程数、内存压力、包 tarball 创建和可读日志冒险,才能最大限度缩短小型仓库的耗时。 + +## 后果 + +由调度器支持的命令耗时取最慢依赖链,而非各独立门禁之和,并会报告主导耗时的门禁。代价是维护一个具有显式模式清单的定制调度器。 + +`publint-all.ts` 采用异步执行并缓冲命令输出,而不是实时继承 stdio。换来的是具有稳定输出顺序的包级并行,以及用于资源调节的单一环境变量。 diff --git a/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.i18n.yaml b/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.i18n.yaml new file mode 100644 index 0000000000..f24a929889 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-10-readme-known-limitations-gate.md: 2ca1168d795692730d17b6ab23dd113e8be277e5 +2026-07-10-readme-known-limitations-gate.zh.md: 4e42492f501cca1a45a90694acea4ca78e920780 diff --git a/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.md b/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.md index 0d294feb0f..2ca1168d79 100644 --- a/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.md +++ b/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-10-readme-known-limitations-gate.zh.md) + ## Problem The [documentation standard](../../../../docs/AGENTS.md) assigns limitations to package READMEs. Without a shared shape, an omitted section cannot distinguish an audited absence from forgotten documentation, and variant headings prevent a repository-wide search. diff --git a/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.zh.md b/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.zh.md new file mode 100644 index 0000000000..4e42492f50 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 每个包(package)README 中受门禁保护的 Known Limitations 章节 + +Status: implemented + +[English](2026-07-10-readme-known-limitations-gate.md) | 中文 + +## 问题 + +[文档标准](../../../../docs/AGENTS.md)规定限制项归属包 README。没有共享形状时,缺少章节无法区分“经审计确认没有限制”与“忘记编写文档”,不同的标题还会妨碍全仓库搜索。 + +## 决策 + +`packages/<group>/<pkg>/package.json` 下的每份包清单都有一个同级 README,其中包含规范的 `## Known Limitations and Deferred Work` 章节。其项目符号记录由该包拥有的持久消费方缺口和不明显的维护者约束;普通清理仍留在源码 TODO 或所属 Agent Note(agent 决策记录)中。[`verify-package-readme-limitations` 门禁](../../../../scripts/verify-package-readme-limitations.ts)从清单推导包集合,拒绝缺失 README,并要求恰好一个规范 h2 且至少包含一个顶层项目符号。“Limitations”“Deferred”“What is NOT here”或“Non-goals”等近似标题都会失败。 + +如果一个包确实没有需要声明的限制事项,则将其列入 `NO_LIMITATIONS` 并省略该章节。新增限制事项时须移除该条目;重命名或移除条目会失败,因为每个条目都必须对应一个被扫描的包。 + +门禁检查存在性、形状和允许列表。按照文档与[正文](../../../skills/dsh-prose-standard/SKILL.md)标准进行的评审负责覆盖面和准确性。常设规则位于 [packages/AGENTS.md](../../../../packages/AGENTS.md)。 + +## 曾考虑的替代方案 + +- **自由格式标题**:无法统一搜索,仍需近似标题检测。 +- **要求空章节或写 "None."**:样板文字可能在包新增限制事项后仍然残留;白名单使「确无限制」这一状态显式且可评审。 +- **设置字数上限**:合理的限制事项数量因包而异,因此由评审管控这一不设预算的 README 层级。 + +## 后果 + +- 新建的包须声明符合条件的限制事项,或显式加入白名单;缺失、漂移或空的章节会在本地和 CI 的 `doc-sync` 中失败。 +- 门禁为 `doc-sync` 新增一个无外部依赖的 TypeScript 脚本。 +- 重命名受强制的标题需要同时修改脚本和所有包 README。 diff --git a/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.i18n.yaml b/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.i18n.yaml new file mode 100644 index 0000000000..ab312d8bcd --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-12-package-model-experience-contract.md: 92a8e5a1a81d00dae085e4af89456896373058e6 +2026-07-12-package-model-experience-contract.zh.md: 54b181738b8276c634f777ad3424191c8652baec diff --git a/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.md b/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.md index dd986f3661..92a8e5a1a8 100644 --- a/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.md +++ b/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-12-package-model-experience-contract.zh.md) + ## Problem A package README can explain APIs and runtime mechanics without answering the questions that dominate an agent harness's behavior and cost: what from this package reaches a model request, under which conditions, how long those tokens remain, and whether later requests preserve a reusable KV-cache prefix. The omission is especially hard to audit in a plugin architecture. A consumer may turn a backend result into a tool message, a policy plugin may replace success with an error, compaction may remove old history, and an agent-scoped registration may change one agent's prompt or schemas while leaving every other agent unchanged. Reading only the nominally model-facing packages therefore misses real context effects, while reading source across every dependency is too expensive for routine review. diff --git a/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.zh.md b/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.zh.md new file mode 100644 index 0000000000..54b181738b --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 包(package)的模型体验契约 + +Status: implemented + +[English](2026-07-12-package-model-experience-contract.md) | 中文 + +## 问题 + +包 README 可以解释 API 和运行时机制,却不回答主导 agent harness(智能体框架)行为与成本的问题:该包的哪些内容会进入模型请求、在什么条件下进入、这些 token 会保留多久,以及后续请求是否会保留可复用的 KV cache 前缀。在插件架构中,这种遗漏尤其难以审计。消费方可能把后端结果转为工具消息,策略插件可能以错误取代成功结果,压缩可能移除旧历史,而 agent 范围的注册可能改变某个 agent 的提示词或 schema,却不影响其他 agent。因此,只阅读名义上面向模型的包会遗漏真实的上下文效应,而在每次常规评审中跨所有依赖阅读源码又成本过高。 + +## 决策 + +每个具有面向模型或邻近模型契约的 workspace 包 README 都以规范的[模型体验章节](../../../../docs/cookbook/adding-a-package.md#4-write-the-package-readme)收尾,位置紧邻 `## Known Limitations and Deferred Work` 之前;位于“无限制项”允许列表中的包则以模型体验本身结尾。经审计确认与模型无关的通用包通过 `NO_MODEL_EXPERIENCE_SECTION` 省略该章节。 + +具有直接、条件式、有上限、全生命周期、多表面或辅助模型效应的包,为每个上下文表面使用一个 H3。每个表面包含三个有序 H4 字段——`What the model sees`、`Token effect` 和 `KV Cache effect`——每个字段都以一个正文段落开头。cache 字段区分仅追加增长、稳定重复前缀、替换先前 token,以及独立模型请求;它点明由包拥有、且能在新内容追加前改变请求的每项配置、范围、生命周期、压缩或路由变化。“Does not invalidate”表示该包保留一个已经可复用的前缀,并非承诺提供方一定命中 cache 或保留某段时间。由包拥有的稳定文本按原文精确引用:系统提示词正文和其他长字面量在引入它们的字段下使用带标题的 H5 加 `markdown` 围栏,通常位于 `What the model sees`;短字面量则以内联形式保留,并点名插值占位符。工具 schema 表面链接生成式[工具目录](../../../../docs/tool-catalog.md)中带锚点的章节,并且只陈述组合或配置增量;仅运行时定义解释目录为何省略它们。依赖数据和由提供方拥有的文本采用摘要。agent 范围的可见性须显式说明;当范围可隐藏提示词与 schema 中的一者而不影响另一者时,两种表面保持分离。 + +没有模型上下文效应的包,或某条路径完全由另一个包渲染的包,使用验证器审计过的短格式:一句以 `None, as ` 或 `Indirectly, through ` 开头的句子,随后是一个 `KV Cache effect` H4 和一个正文段落。纯传输包和无密钥测试支持包若不创建任何进入模型的内容,就使用 none 格式。提供方后端即使会限制或过滤数据也使用 indirect 格式;具名子项拥有全部效应时,接线 bundle 也使用该格式。这些章节定位贡献并声明不会直接使 cache 失效,同时不重复陈述消费方。结构化章节同样只记录由包拥有的输入、变换和增量。 + +`verify-package-readme-model-experience` 发现包清单,并验证三种分类、规范末尾章节顺序、确切字段标题深度与顺序、非空字段段落、逐字块的 H5 归属、具体字面量证据,以及带锚点的工具目录链接。它在 `doc-sync` 和并行门禁 runner 中运行。评审仍负责覆盖面、链接相关性和事实准确性。 + +## 曾考虑的替代方案 + +- **只记录注册提示词或工具的包**:否决。后端、策略插件、适配器、持久化、作用域和压缩都会改变 token 的内容或生命周期,却不拥有面向模型的 schema。 +- **从源码生成一份集中式上下文成本目录**:否决。AST 能找到注册点,但无法推断语义条件,如历史保留、输出截断、父子可见性或辅助模型边界。包 README 是实现本地的契约;集中副本会增加又一个漂移面。 +- **要求给出精确 token 数**:否决。精确数量取决于所选模型的 tokenizer、适配器序列化方式、配置和运行时数据。稳定的契约是增长形状:每请求固定、每调用条件性、保留、替换、有上限或零直接影响。 +- **使用表格**:否决。精确源码文本和条件式结果形状会使单元格密集而难以扫读。重复的小节在保留相同字段的同时,为每个上下文表面提供易读的纵向空间。 +- **允许所有零影响包省略该章节**:否决。无约束的缺失在「经审计的零影响」和「忘记写文档」之间有歧义。省略仅限于在验证器中以理由命名的模型无关通用包;模型相邻的零影响包保留一句显式说明。 +- **要求经审计的零效应包或简单间接包使用完整结构化格式**:否决。它会围绕一个事实重复标签。受门禁约束的句子加 cache 字段既保留显式覆盖,又没有多余仪式。 +- **只有约定而无门禁**:否决。仓库级契约必须覆盖未来的每个包;评审者的记忆无法可靠地检测到遗漏的 README 章节。 + +## 后果 + +评审者可以从任何面向模型或邻近模型的包开始,看到它对对话模型、子模型和辅助调用的贡献,无需重建完整插件图。token 预算工作可以区分重复请求开销和依赖数据的历史,而 cache 敏感工作可以识别仅追加路径,以及最早由包引起的前缀变更。agent 范围变更有明确的文档检查点。每当模型可见行为发生变化时,包作者都要维护一个或多个紧凑的上下文表面块,或一种已分类的短格式;经审计的通用包不携带无关的模型样板。结构化字段不承诺由提供方给出的精确 token 数或 cache 命中;测量仍取决于具体模型、提供方和工作负载,而所记录的增长、可见性和前缀稳定性契约保持稳定。 diff --git a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml index aa0516648b..1a6a99d648 100644 --- a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.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 -2026-07-21-serial-cross-platform-ci-reference.md: b795a0aff62c20967d2c85429c0c6115c1b9585d -2026-07-21-serial-cross-platform-ci-reference.zh.md: 223fd9cf20a1d8228cb0c6b1b2f3f95644becae6 +2026-07-21-serial-cross-platform-ci-reference.md: 3c0ae200d7dbd5b04eae6db2d6628dccc72103bf +2026-07-21-serial-cross-platform-ci-reference.zh.md: 5c159e12739d68e0baed72aaa08331072e2c3601 diff --git a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md index b795a0aff6..3c0ae200d7 100644 --- a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md +++ b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md @@ -18,6 +18,10 @@ Reviewers also need a direct answer to a simpler question: what happens when the Each reference job runs `pnpm run check:ci` without any shard selector. `DSH_GATE_CONCURRENCY=1` makes the top-level aggregate execute one ready gate at a time; coverage, snapshot replay, built-bin smoke, and publication validation also receive worker counts of one. The three operating-system jobs may run beside one another, but each host's repository gates are serial and complete. Linux installs bubblewrap before replaying snapshots, and Windows enables Developer Mode before installing the symlinked workspace. +Platform ownership remains explicit inside that complete aggregate. `pty-local` supports Linux and macOS and therefore owns its unit and per-file coverage contract on POSIX rather than loading a backend that rejects `win32`; the Windows run still executes every portable package. Portable fixtures derive native paths through `node:path`, compare canonical identities with the same native realpath implementation as production, and use filenames legal on every host. ACP snapshot runs also pass both JavaScript and native realpath spellings of their generated cwd to the normalizer, which replaces aliases longest-first so Windows short and long paths cannot churn shared fixtures. + +The macOS reference runs the ordinary Vitest project in forked processes. Node 24 on macOS arm64 has aborted in its CJS lexer from a worker thread; the process boundary contains that external runtime failure without removing any test from the aggregate, while Linux and Windows retain the lower-overhead thread pool. Repository-owned races are fixed at their observation boundaries: dev bundle polling stages each candidate table, graph, and watch-baseline map before publishing a rescan, and a missing bundle remains dirty until a successful content hash. PTY readiness retains a prompt candidate while polling checks foreground ownership; the ordinary silence bound covers inherited markers from interactive children. The live-link package-manager e2e preserves the workflow-prepared Corepack home and pnpm metadata/store caches while isolating the other managers' mutable caches, so it does not discard reusable package-manager state before the install. + Master reference jobs are diagnostic and do not participate in the pull request's required `all checks passed` result. A pull request runs only its required jobs; a master push runs only the three serial references. Performance is evaluated from completed hosted-job timestamps and reported as a measurement; it is not encoded as a `timeout-minutes` value. The portable reference uses GitHub's standard `ubuntu-latest`, `macos-latest`, and `windows-2025` labels. Required pull-request jobs use the same portable Linux and Windows capacity under the [required-CI decision](2026-07-23-portable-required-pull-request-ci.md). Higher-core hosted runners remain manual benchmarks because a correctness path must remain runnable without repository-external runner configuration. @@ -36,4 +40,6 @@ The workflow contains duplicated setup steps and a master reference run can take The reference may expose platform failures that the optimized blocking set does not yet claim to support, especially on Windows. Such a failure is evidence about current cross-platform behavior rather than a reason to weaken or silently skip the aggregate. +The explicit `pty-local` ownership boundary means Windows does not claim coverage for a backend it cannot load, and forked macOS unit workers cost more process startup time. In return, every supported surface has an honest platform oracle, a native runtime abort cannot erase the rest of the unit result, and timing-sensitive observers start from state established before callers can mutate it. + Removing strict duration timeouts means a latency regression is observed rather than automatically cancelled. Hosted measurements must therefore accompany performance changes, while the completed logs retain the information needed to optimize the slow lane. diff --git a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md index 223fd9cf20..5c159e1273 100644 --- a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md +++ b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md @@ -18,6 +18,10 @@ Status: implemented 每个参考作业均在不设置任何分片选择器的情况下运行 `pnpm run check:ci`。`DSH_GATE_CONCURRENCY=1` 使顶层聚合每次只执行一个已经就绪的门禁;覆盖率、快照回放、built-bin 冒烟测试和发布验证的并发数也设为 1。三种操作系统的作业可以彼此并行,但每台主机上的仓库门禁都串行运行且完整执行。Linux 在回放快照前安装 bubblewrap,Windows 则在安装采用符号链接的工作区前启用开发人员模式。 +该完整聚合流程仍明确划分平台归属。`pty-local` 支持 Linux 与 macOS,因此其单元测试和逐文件覆盖率契约由 POSIX 平台负责,而不会在 Windows 上加载一个明确拒绝 `win32` 的后端;Windows 仍会执行所有可移植包(package)。可移植 fixture(测试前置数据)通过 `node:path` 派生原生路径,使用与生产代码相同的原生 realpath 实现比较规范化后的路径标识,并采用所有宿主机均允许的文件名。ACP(Agent Client Protocol)快照运行还会把生成的 cwd 分别通过 realpath 的 JavaScript 实现与原生实现得到的两种表示一并传给规范化器;规范化器按长度从长到短替换这些别名,避免 Windows 的短路径与长路径表示差异导致共享 fixture 反复变化。 + +macOS 参考流程使用 fork 进程运行常规 Vitest 项目。macOS arm64 上的 Node 24 曾在工作线程中执行 CJS 词法分析器时异常终止;进程边界能够隔离这一外部运行时故障,且无需从聚合流程中删除任何测试,而 Linux 与 Windows 仍使用开销更低的线程池。仓库自身引入的竞态均在相应的观测边界修复:开发构建产物的轮询逻辑每次发布重新扫描结果前,都会先暂存候选表、候选图和候选监视基线映射;构建产物缺失后会一直保持脏状态,直到成功计算内容哈希。PTY 就绪检测会在轮询检查前台进程组归属期间保留提示符候选项;常规静默时限也适用于交互式子进程继承提示符标记的情况。实时链接场景下的包管理器 e2e 会保留由工作流预先准备的 Corepack 主目录、pnpm 元数据缓存和 store 缓存,同时隔离其他包管理器的可变缓存,因此不会在安装前丢弃可复用的包管理器状态。 + master 分支的参考作业仅用于诊断,不参与拉取请求所要求的 `all checks passed` 结果。拉取请求只运行其必需作业;向 master 推送时只运行三个串行参考作业。系统根据已完成托管作业的时间戳评估性能,并将其报告为测量结果,而不是写成 `timeout-minutes` 值。 可移植的参考流程使用 GitHub 标准的 `ubuntu-latest`、`macos-latest` 和 `windows-2025` 标签。依据[必需 CI 决策](2026-07-23-portable-required-pull-request-ci.md),拉取请求必需作业使用相同的可移植 Linux 和 Windows 容量。更高核心数的托管运行器仍仅用于手动基准测试,因为正确性路径必须无需仓库外部的运行器配置即可运行。 @@ -36,4 +40,6 @@ master 分支的参考作业仅用于诊断,不参与拉取请求所要求的 参考流程可能暴露某些平台上的故障,而优化后的阻塞门禁集合尚未声明支持这些平台,Windows 尤其如此。这类失败反映了当前的跨平台行为,不应成为削弱或静默跳过该聚合流程的理由。 +明确的 `pty-local` 归属边界意味着 Windows 不会声称覆盖一个无法加载的后端,而 macOS 采用 fork 的单元测试工作进程会增加进程启动开销。这些代价换来的是:支持范围内的每项功能都有能够如实反映对应平台行为的判据,原生运行时异常终止不会抹掉其余单元测试结果,各项对时序敏感的观测逻辑也都会以调用方有机会修改状态前已建立的状态作为起点。 + 移除严格的时长超时后,系统会观测到延迟回归,而不是在发生回归时自动取消运行。因此,性能改动必须附带托管环境测量结果,已完成的日志则保留优化最慢通道所需的信息。 diff --git a/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.i18n.yaml b/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.i18n.yaml new file mode 100644 index 0000000000..ec8fddb9f6 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-19-drop-mutable-session-summary.md: f87378a1c3737950eb536be8e3f6776586eb8a01 +2026-06-19-drop-mutable-session-summary.zh.md: 05b6711b71ef87602b46706cd4340a10453e66ad diff --git a/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.md b/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.md index f1a9c9aa3c..f87378a1c3 100644 --- a/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.md +++ b/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-19-drop-mutable-session-summary.zh.md) + ## Problem The [session-persistence seam](../architecture/2026-06-14-session-persistence.md) split a session's out-of-log metadata into two types owned by `dsh-session`: an immutable `SessionHeader` (`version`, `id`, `createdAt`, `cwd?`, `parentSession?`) written once at creation, and a mutable `SessionSummary` (`updatedAt`, `title?`, `firstPrompt?`) "updateable without touching the append-only log". Their union was `SessionMeta = SessionHeader & SessionSummary`, and the abstract `SessionPersistence` service carried a seventh method — `update(id, summary)` — for rewriting the summary. Each backend implemented the mutable store its own way: JSONL wrote a separate atomic `.summary.json` **sidecar** beside the log (temp-write + rename, best-effort), SQLite kept `updated_at`/`title`/`first_prompt` **columns** bumped inside the append transaction. @@ -10,8 +12,8 @@ The summary was designed for a future session picker (recency ordering via `upda - `SessionPersistence.update()` has **zero production callers** (every `.update(` hit is `createHash().update()` or a test). - `firstPrompt` is **never read** anywhere in production. -- `title` *is* read in the ACP bridge — but from a tool-call **presenter** (`present.title`), never from stored session metadata. -- `updatedAt` has **no consumer**: the only production caller of `list()` reads `meta.cwd` (a `SessionHeader` field) to validate a workspace on `session/load`; resume reads `createdAt`/`cwd`/`parentSession` — all header fields. +- Session titles come from durable `session/title` events, while tool-card titles come from tool presenters; neither reads mutable session metadata. +- Persistence-list consumers use immutable header identity, creation, lineage, and cwd fields. Recency and previews derive from the log rather than an `updatedAt` summary. - Decisively: the live `Session.header` was already typed `SessionHeader`, not `SessionMeta` — the summary never existed on the live session object; it lived only in the persistence layer, written and read by nothing but its own contract test. ## Decision diff --git a/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.zh.md b/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.zh.md new file mode 100644 index 0000000000..05b6711b71 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 移除可变的会话摘要 + +Status: implemented + +[English](2026-06-19-drop-mutable-session-summary.md) | 中文 + +## 问题 + +[会话持久化 seam](../architecture/2026-06-14-session-persistence.md)将会话的日志外元数据拆分为 `dsh-session` 拥有的两种类型:一个不可变的 `SessionHeader`(`version`、`id`、`createdAt`、`cwd?`、`parentSession?`),在创建时一次性写入;一个可变的 `SessionSummary`(`updatedAt`、`title?`、`firstPrompt?`),「可在不触碰仅追加日志的情况下更新」。二者的联合类型为 `SessionMeta = SessionHeader & SessionSummary`,抽象的 `SessionPersistence` 服务为此多出第七个方法 `update(id, summary)`,用于重写摘要。各后端各自实现可变存储:JSONL 在日志旁写一个独立的原子 `.summary.json` **伴随文件**(临时写入 + rename,尽力保证);SQLite 在追加事务内更新 `updated_at`/`title`/`first_prompt` **列**。 + +摘要是为未来的会话选择器设计的(通过 `updatedAt` 排序近期会话,用 `title`/`firstPrompt` 做预览)。该选择器从未实现。对整个仓库的审计表明,`SessionSummary` 的全部表面积都是**死状态**: + +- `SessionPersistence.update()` **零个生产调用方**(所有 `.update(` 匹配都是 `createHash().update()` 或测试代码)。 +- `firstPrompt` 在生产代码中**从未被读取**。 +- 会话标题来自持久的 `session/title` 事件,工具卡片标题来自工具 presenter;二者都不读取可变的会话元数据。 +- 持久化列表的消费方使用不可变 header 中的标识、创建、谱系和 cwd 字段。近期排序和预览派生自日志,而非某个 `updatedAt` 摘要。 +- 决定性的一点:活跃的 `Session.header` 类型本来就是 `SessionHeader` 而非 `SessionMeta`——摘要从未存在于活跃会话对象上;它只存在于持久化层,除了自身的契约测试外无人写入、无人读取。 + +## 决策 + +彻底删除可变的会话摘要。`SessionSummary` 与 `SessionMeta` 这个名称一并移除;后端存储和返回的元数据仅为 `SessionHeader`。`SessionPersistence.update()` 从抽象服务和所有后端中移除。JSONL 去掉整套伴随文件机制(`writeSidecar`/`readSidecar`/`touchSummary`/`removeSidecars`/`sidecarPath` 以及 load/list 的覆盖逻辑);SQLite 去掉 `updated_at`/`title`/`first_prompt` 列以及每次追加时的 `updated_at` 更新,其 `SCHEMA_VERSION` 从 `1 → 2`。 + +摘要原本要提供的一切,在消费方真正需要时都**可从仅追加日志中派生**(`firstPrompt` = 第一条 `user/message`;近期度 = 最后一个事件的 `time` 或文件 mtime),或者已经存在于不可变 header 中(`createdAt`、`cwd`)。唯一*不可*派生的是用户*手动编辑*的标题,但它从未实现,纯属 YAGNI;如果未来真有功能需要,它可以作为独立的日志事件或 header 字段回归。 + +这被记录为一项决策,因为它具有**持久性**(它同时收窄两个后端的公共服务契约和磁盘格式)、**争议性**(summary 是有意为未来设计的结果,而非意外),也具有**意外性**(未来读者在原 Agent Note(agent 决策记录)描述 `SessionMeta` 的位置发现 `SessionHeader`,否则会追问 summary 为何消失)。它还为[共享持久化写入协调器](../architecture/2026-06-18-shared-persistence-write-coordinator.md)扫清障碍:不再有可变 summary 后,协调器的钩子接口不需要 `updateSummary` 钩子,JSONL sidecar 与 SQLite 列之间的持久性分歧也随之消失,使两个后端的写入路径趋于一致。 + +## 无需迁移 + +这是未发布的软件(见[根 AGENTS.md](../../../../AGENTS.md)「Pre-release stance: foundation over blast radius」一节),因此没有需要保留的磁盘数据库或日志。SQLite 不迁移 v1 数据库:`openDatabase` 守卫现在拒绝任何非当前版本的磁盘 `user_version`(`onDisk !== 0 && onDisk !== SCHEMA_VERSION`),无论更旧*还是*更新,因此陈旧的 v1 数据库会被干净地拒绝,而非在新列集下被半读取。新建数据库写入当前版本号;这是唯一需要正常工作的路径。 + +## 后果 + +未来的会话选择器现在必须从日志派生预览/排序信息(或重新引入一个类型化字段),而不能直接读取现成的摘要行。这是正确的代价:为一个尚不存在的功能维护缓存,是每个后端都要付出维护成本、每个契约测试都要付出断言成本的死重。这一原则——**通过的测试固定的是当前行为,不一定是正确行为;行为可能是过去妥协的产物**——现已作为独立约定记录在[根 AGENTS.md](../../../../AGENTS.md) 中,本次变更即为其实例。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.i18n.yaml b/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.i18n.yaml new file mode 100644 index 0000000000..b40c734b2c --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-collapse-trace-only-session-events.md: c77062c3cd44286b43c175702c35b36f9cc31da6 +2026-06-20-collapse-trace-only-session-events.zh.md: b232b3fb60822e60b1f5767066db42b0228269a8 diff --git a/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.md b/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.md index 4e8a092989..c77062c3cd 100644 --- a/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.md +++ b/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.md @@ -2,9 +2,11 @@ Status: implemented +English | [中文](2026-06-20-collapse-trace-only-session-events.zh.md) + ## Problem -The session event vocabulary includes first-class events that are not part of replayable conversation history and have little or no production consumption. `usage` is already present as a model stream chunk before the loop also appends a separate `usage` event. `error` duplicates the `turn/end { kind: 'error', message, code }` reason for loop failures; ACP settlement reads the turn-end reason, ACP rendering ignores the `error` event, and `deriveMessages()` skips it. +The session event vocabulary includes first-class events that are not part of replayable conversation history and have little or no production consumption. `usage` is already present as a model stream chunk before the loop also appends a separate `usage` event. `error` duplicates the `turn/end { kind: 'error', message, code }` reason for loop failures; ACP settlement reads the turn-end reason, while message and UI projections skip the standalone `error` event. These events make the canonical transcript look more useful as telemetry than it currently is. They add event variants, invariants, tests, snapshots, and persistence cases, but they are not load-bearing as separate records. The facts they carry can still be useful: token usage should remain available for accounting, and an error's step number should not silently disappear. The simplification is to fold those facts into nearby events consumers already must understand, not to record less information. diff --git a/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.zh.md b/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.zh.md new file mode 100644 index 0000000000..b232b3fb60 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.zh.md @@ -0,0 +1,44 @@ +# Agent Note: 将仅用于追踪的会话事实折叠进承载性事件 + +Status: implemented + +[English](2026-06-20-collapse-trace-only-session-events.md) | 中文 + +## 问题 + +会话事件词汇中包含一些一等事件,它们不属于可回放的对话历史,在生产环境中几乎没有消费方。`usage` 已经作为模型流分片存在,之后循环又追加了一个独立的 `usage` 事件。`error` 与 `turn/end { kind: 'error', message, code }` 中的循环失败原因重复;ACP(Agent Client Protocol)结算读取轮次结束原因,而消息投影和 UI 投影都会跳过独立的 `error` 事件。 + +这些事件让规范的 transcript(文本记录)看起来比实际更像遥测数据。它们增加了事件变体、不变式、测试、快照和持久化用例,但作为独立记录并不承载实际功能。它们携带的事实仍然有用:token 用量应当保留以供计费,错误的步骤编号也不应悄然消失。简化的方式是将这些事实折叠进消费方本已必须理解的邻近事件,而非减少记录的信息量。 + +## 决策 + +仅在信息已被保留、无需并行记录的情况下,移除独立的追踪事件: + +- 成功步骤的 usage 折叠进匹配的 `assistant/message`(`assistant/message { turn, step, content, usage? }`),使组装好的模型输出与其计费信息一同传递。 +- 失败或中止的步骤如果有 usage 但没有 assistant 内容,则将 usage 放在一个空内容的 `assistant/message` 上(下方实现说明给出了无信息丢失的证明)——不会有已持久化的 usage 分片无处安放。 +- 独立 `error` 事件中的步骤编号折叠进 `turn/end.reason`(当 `kind: 'error'` 时:`{ kind: 'error', step, message, code? }`)——`turn/end` 是 ACP 和恢复机制已经消费的持久轮次结果。 +- `agent/error` 与日志保留用于实时诊断;`turn/end` 之后不再有第二条会话日志错误记录。 + +用户对话日志包含渲染、恢复、审计和计费所需的全部信息,消费方无需协调重复的追踪行。 + +## 曾考虑的替代方案 + +**保留独立行作为遥测**——这些事件让规范 transcript 看起来比实际更像遥测数据,代价是增加了事件变体、不变式、测试、快照和持久化用例,却没有任何消费方使用。如果分析需求真正出现,正确的形态是投影辅助工具或带有独立保留策略的专用遥测存储,而非对话日志中的重复追踪行。 + +## 验证 + +`SessionEventMap` 不再包含独立的 `usage` 或 `error`;agent loop(智能体循环)不再追加独立的 usage 事件,持久性失败通过 `turn/end { kind: 'error', step, message, code? }` 记录;ACP 快照和持久化测试断言不存在仅追踪行;已录制的 fixture(测试前置数据)使用新事件形状,会话格式版本固定为 `0`(后端按预发布格式策略拒绝任何非 `0` 的存储日志);文档说明了 token 用量和操作错误的观测位置。 + +## 后果 + +消费方不能再从规范日志中筛选独立的 `usage` 或步骤级 `error` 行,必须从承载它们的 assistant/failure 事件中读取这些事实。只有在实现 PR(Pull Request)证明相同事实仍然存在的前提下,这才是合理的简化;否则独立事件应予保留。 + +## 实现说明 + +按提案落地,但有一处范围细化(遵循 AGENTS.md 所述“Agent Note(agent 决策记录)是提案,而非绝对真理”): + +- **空内容 `assistant/message` 承载 usage,无数据丢失。** 提案要求的证明(不会有已持久化的 usage 分片无处安放)落在 max-tokens 路径上:一个被截断的步骤有 usage 但内容为空(例如只有一个被丢弃的工具调用),以前会发出独立的 `usage`。现在它记录一个空内容的 `assistant/message { content: [], usage }`。为防止这向提供方 transcript 注入一个无内容的虚假 assistant 轮次,`deriveMessages()` 跳过空内容的 `assistant/message` 事件。回归测试断言 usage 仍被表示,且派生历史未被破坏。 + +**格式版本。** 此变更影响已持久化的事件,但预发布会话格式仍固定为 `0`,拒绝任何其他版本且不做迁移。`dsh-session` 拥有写入方和加载校验使用的常量。单调递增的格式版本从首次正式发布开始。 + +Usage 现在通过 `assistant/message.usage` 观测;操作错误的步骤编号通过 `turn/end.reason`(当 `kind: 'error'` 时)观测。`agent/error` 与日志用于实时诊断,保持不变。 diff --git a/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.i18n.yaml b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.i18n.yaml new file mode 100644 index 0000000000..9529343206 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-drop-unconsumed-llm-adapter-change-event.md: a3c7c089d7dfa1a4cd6a891c416bf270dc7eff3d +2026-06-20-drop-unconsumed-llm-adapter-change-event.zh.md: d9129386dc95bae0716253fdf50236b25ebfdf75 diff --git a/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.md b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.md index d8d4015b0d..a3c7c089d7 100644 --- a/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.md +++ b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-drop-unconsumed-llm-adapter-change-event.zh.md) + ## Problem `LlmService.registerAdapter()` emits `llm/adapter-change` on registration and disposal ([packages/llm/llm/src/index.ts](../../../../packages/llm/llm/src/index.ts)). Grepping `llm/adapter-change` across `packages/*/src` and `examples/*/src` finds only the declaration, emit sites, docs, and tests; no production listener subscribes to it. diff --git a/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.zh.md b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.zh.md new file mode 100644 index 0000000000..d9129386dc --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 移除未被消费的 `llm/adapter-change` 事件 + +Status: implemented + +[English](2026-06-20-drop-unconsumed-llm-adapter-change-event.md) | 中文 + +## 问题 + +`LlmService.registerAdapter()` 在注册和 dispose(资源释放)时发出 `llm/adapter-change` 事件([packages/llm/llm/src/index.ts](../../../../packages/llm/llm/src/index.ts))。在 `packages/*/src` 和 `examples/*/src` 中搜索 `llm/adapter-change`,只能找到声明、emit 站点、文档和测试;没有任何生产环境的监听器订阅它。 + +这与 `tools/change` 和 `system-prompt/change` 不同。如今这两个事件同样没有消费方,但它们有望成为未来实时工具/提示词 UI 的注册表变更信号。LLM(大语言模型)适配器注册更像是启动时的实现细节:适配器不是用户可见的选项面板,真正的模型调用拦截 seam 是 `llm/stream`。保留一个没有监听器的适配器变更事件,只是在更小范围内重复[删除无用 summary](2026-06-19-drop-mutable-session-summary.md) 的模式。 + +这个事件并非零成本。`registerAdapter()` 在发出 `llm/adapter-change` 之前先 yield 回滚 disposer,这样抛出异常的监听器会回退变更而非泄漏适配器条目;包内还有针对该监听器抛出路径的测试。这种防御性排序保护的是一个只有测试才能触发的失败模式。 + +## 决策 + +只移除 `llm/adapter-change`:包括 `dsh-llm` 的 `interface Events` 中的声明、`ctx.emit('llm/adapter-change')` 调用,以及 `LlmService.registerAdapter` JSDoc 中“在注册和释放时发出 `llm/adapter-change`”的句子。`registerAdapter()` 的效应生成器为 HMR(热模块替换)/释放保留变更与回滚 disposer,但移除仅因该事件而存在的监听器抛错回滚顺序。适配器 disposer 测试断言返回的 disposer 会移除适配器,不再订阅事件;监听器抛错回滚测试则随其测试对象一起消失。[docs/architecture.md](../../../../docs/architecture.md) 和 [packages/llm/llm/README.md](../../../../packages/llm/llm/README.md) 中的事件分类也在同一变更中更新。 + +## 曾考虑的替代方案 + +### 为什么不移除所有注册表变更事件? + +由注册表通告变更的微内核是一种一致的约定。当 UI 能够实时刷新可用工具或提示词章节时,`tools/change` 和 `system-prompt/change` 可能会有用。本 Agent Note(agent 决策记录)在存在合理用户侧消费方的位置保留该约定,只删除当前及可能的未来消费方都不明确的适配器变更事件。 + +如果将来需要 LLM 适配器浏览器或动态模型选择器用到此信号,届时再连同消费方一起重新引入,并提供比「something changed」更清晰的 payload。 + +## 验证 + +`llm/adapter-change` 及其 emit 已消失,重新生成的 Cordis 目录保持新鲜;HMR 安全性仍成立(释放贡献该适配器的 fiber 会移除它);`tools/change` 和 `system-prompt/change` 仍有文档与测试;ACP(Agent Client Protocol)快照和无密钥 Headless Loader 冒烟则固定了未变的生产路径。 + +## 后果 + +- **移除一个已文档化的 emit 事件属于公开接口变更。** 它出现在分类体系表中,读起来像有意设计的 API。但「已声明且已发出」不等于「已被消费」——这与移除可变 summary 时的判断依据相同。分类体系表在同一个变更中更新,因此文档不会漂移。 +- **注册表变更约定变得不均匀。** 这是可接受的,因为 LLM 适配器注册与工具或提示词段落不是同一层面的面向用户概念。不均匀但诚实,胜过统一但无用。 + +这是一个小裁剪,但它退役了一条守护着并不存在的消费方的正确性不变式。 diff --git a/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.i18n.yaml b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.i18n.yaml new file mode 100644 index 0000000000..ad842ae732 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-drop-unconsumed-llm-assembled-surfaces.md: b6b596e822b4bd6fd1bd891c336c622ad675ad45 +2026-06-20-drop-unconsumed-llm-assembled-surfaces.zh.md: bafc5d3bc630d89c776bbcf53719b29223e1c90d diff --git a/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.md b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.md index b482a444b5..b6b596e822 100644 --- a/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.md +++ b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-drop-unconsumed-llm-assembled-surfaces.zh.md) + ## Problem `LlmService` ([packages/llm/llm/src/index.ts](../../../../packages/llm/llm/src/index.ts)) exposes three call surfaces over a model: diff --git a/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.zh.md b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.zh.md new file mode 100644 index 0000000000..bafc5d3bc6 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 移除未被消费的 LLM 组装便捷接口 + +Status: implemented + +[English](2026-06-20-drop-unconsumed-llm-assembled-surfaces.md) | 中文 + +## 问题 + +`LlmService`([packages/llm/llm/src/index.ts](../../../../packages/llm/llm/src/index.ts))在模型之上暴露了三个调用接口: + +- `stream()`:原始 `StreamChunk`,通过 `llm/stream` waterfall(瀑布式事件)分发。 +- `streamBlocks()`:一个「便捷视图」,将分片送入 `BlockAssembler` 并按流顺序产出已组装的 `ContentBlock`([index.ts:137-144](../../../../packages/llm/llm/src/index.ts))。 +- `generate()`:一个完整组装的 `GenerateResult`,通过第二条 `llm/generate` waterfall 分发([index.ts:151-157](../../../../packages/llm/llm/src/index.ts))。 + +LLM(大语言模型)服务唯一的生产消费方是 agent loop(智能体循环),它只使用 `stream()`:将原始分片送入自己的 `BlockAssembler`,以便在并行组装的同时记录分片,保证回放保真度([packages/core/agent-loop/src/loop.ts](../../../../packages/core/agent-loop/src/loop.ts),`ctx.llm.stream(req)` 步骤)。在 `packages/*/src` 和 `examples/*/src` 中 grep `streamBlocks` 与 `ctx.llm.generate`,找不到任何生产调用方。仅有的引用来自服务方法定义、文档和测试;适配器测试用 `generate()` 作为便捷驱动,但它们完全可以通过同一个 assembler 辅助函数手动消费 `stream()`,无需为此保留一个公开的生产 API。 + +这属于[删除可变会话 summary](2026-06-19-drop-mutable-session-summary.md) 的同类模式:带有受测契约的组装视图 API,由测试而非生产代码消费。它们是为不关心 token 级增量的消费方推测性构建的,但唯一的真实消费方恰恰关心增量,以便持久化高保真重放数据。 + +`streamBlocks()` 拖带了 `BlockAssembler` 的一块专用逻辑:`flushReady()` 与 `flushRemaining()`([packages/llm/llm/src/assembler.ts:138-168](../../../../packages/llm/llm/src/assembler.ts))以及 `flushed` 游标字段,仅为支持按序增量产出而存在。`generate()` 拖带了 `GenerateResult`、`BlockAssembler.result()` 以及 `llm/generate` waterfall——在同一底层流之上的第二个拦截面。agent loop 对 assembler 的使用仅限于 `push()` / `message()` / `usage` / `finish`,不涉及流式 flush 或一次性服务组装。 + +## 决策 + +`stream()` 是唯一的公开 LLM 调用接口。移除 `streamBlocks`、`generate`、其事件/结果类型,以及仅被该路径使用的 assembler 辅助方法。适配器测试通过本地辅助函数对公开流进行组装;`BlockAssembler` 仅保留有生产消费方的操作。 + +## 曾考虑的替代方案 + +**保留 `generate()` 作为仅供测试的便捷方法**:否决。适配器测试通过共享 assembler 手动消费 `stream()`,走的是与生产完全相同的流式路径;一个唯一调用方只有测试的公开方法,正是 [drop-mutable-summary 先例](2026-06-19-drop-mutable-session-summary.md)所淘汰的死接口形态。未来如果有消费方需要不带增量的组装块,届时再为该消费方引入一个聚焦的辅助方法。 + +## 验证 + +`streamBlocks`、`generate`、`llm/generate` 及仅供它们使用的 assembler 辅助函数均已移除,且未产生新的无用导出;两个真实适配器都通过 `stream()` 和共享 assembler 接受测试;循环行为保持一致(ACP(Agent Client Protocol)快照预期输出未变);README、架构文档和模块文档也不再提及已删除表面。 + +## 后果 + +- **从一个核心词汇包中移除了公开方法。** 未来如果有插件需要不带增量的组装块,它需要直接调用 `stream()` 并使用 `BlockAssembler`,或在有真实消费方时重新引入一个聚焦的辅助方法。鉴于预发布阶段「基础优先于预设未来」的立场([AGENTS.md](../../../../AGENTS.md)),现在正是裁剪仅供测试的公开接口的合适时机。 +- **适配器测试变得更显式。** 它们失去了便捷的 `generate()` 包装层,但这是有益的压力:测试走的是与生产相同的流式路径。 +- **waterfall 使用者失去 `llm/generate`。** 不存在生产监听者。未来的缓存/重试/日志插件应包装 `llm/stream`,它仍然是唯一的提供方调用路径。 + +改动规模不大,但它从 LLM 包中干净地移除了预设的接口面积,为生产和测试留下唯一一份模型调用契约。 diff --git a/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.i18n.yaml b/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.i18n.yaml new file mode 100644 index 0000000000..872b3fc588 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-prune-dead-seam-methods.md: 91a18b4c327d2f3cb636d6d9e0c26e4246a6ffd2 +2026-06-20-prune-dead-seam-methods.zh.md: b962bc45052b723eefa533b98fe85f4508d6b6a7 diff --git a/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.md b/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.md index f74de250ef..91a18b4c32 100644 --- a/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.md +++ b/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-prune-dead-seam-methods.zh.md) + > **Implementation note:** Only `SessionPersistence.has()` and `.delete()` were removed. `BashExecutor.get()` and `.list()` remain because removing their one-line lookup surface required substantially more completion-tracking machinery in consumers. Their id branding is covered by the [branded-ids Agent Note](../architecture/2026-06-20-branded-ids.md). ## Problem @@ -10,7 +12,7 @@ A capability seam ([interface / implementation / consumer](../architecture/2026- ### `SessionPersistence.has()` and `.delete()` -The abstract service declared its operations beyond create/append: `load`, `list`, `has`, `delete`. Production consumers of `ctx.sessionPersistence` use only two: the agent-loop resume path calls `load()` ([packages/core/agent-loop/src/index.ts:176](../../../../packages/core/agent-loop/src/index.ts)), and the ACP bridge calls `list()` for `session/list` ([packages/ui/acp/src/index.ts:494](../../../../packages/ui/acp/src/index.ts)). Grepping every `sessionPersistence.*` / `persistence.*` use across `packages/*/src` and `examples/` finds no `has(` and no `delete(` on the service. The `.has(`/`.delete(` calls in `packages/ui/acp/src/index.ts` are on the in-memory `SessionStore` and a local `Set` of loading ids, not persistence. The only callers of `has`/`delete` were the contract suites and per-backend specs. +The abstract service declared its operations beyond create/append: `load`, `list`, `has`, `delete`. Production consumers use `load()` and `list()` for resume and session discovery, while no production caller uses persistence `has()` or `delete()`. The similarly named in-memory collection calls in protocol and UI code are unrelated. The only callers of persistence `has`/`delete` were the contract suites and per-backend specs. `has()` was not just unused: it added a tracked-vs-untracked coordinator probe and a contract branch even though `loadStored(id)` already owns durable existence checks. `delete()` dragged the `deleteStored` backend hook that every backend had to implement. This is the [drop-mutable-session-summary](2026-06-19-drop-mutable-session-summary.md) pattern: a contract test exercised both, but no shipping code asks "is this session persisted?" or removes one. @@ -31,7 +33,7 @@ Re-adding a seam method with a live consumer is cheap and better-designed than t ## Verification -`has`/`delete`/`deleteStored` are gone from the persistence seam, impl, and contract suites with no new dead exports; the remaining operations (`create`/`append`/`load`/`list`) are untouched, with ACP `session/list` and crash-recovery behaving identically; and the seam README and `docs/architecture.md` list only the surviving methods. +`has`/`delete`/`deleteStored` are gone from the persistence seam, impl, and contract suites with no new dead exports; the remaining operations (`create`/`append`/`load`/`list`) are untouched, with persistence-backed session queries and crash recovery behaving identically; and the seam README and `docs/architecture.md` list only the surviving methods. ## Consequences diff --git a/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.zh.md b/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.zh.md new file mode 100644 index 0000000000..b962bc4505 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.zh.md @@ -0,0 +1,43 @@ +# Agent Note: 从持久化 seam 中移除无用方法 + +Status: implemented + +[English](2026-06-20-prune-dead-seam-methods.md) | 中文 + +> **实现说明:** 仅移除了 `SessionPersistence.has()` 和 `.delete()`。`BashExecutor.get()` 和 `.list()` 仍然保留,因为删除它们的单行查找表面会要求消费方增加显著更多的完成跟踪机制。其 id 品牌化由[品牌化 id Agent Note(agent 决策记录)](../architecture/2026-06-20-branded-ids.md)负责。 + +## 问题 + +能力 seam([接口 / 实现 / 消费方](../architecture/2026-06-13-capability-seams.md))承载了没有消费方调用的抽象方法。seam 的存在是为了让实现和消费方独立演进——但没有消费方以之编程的方法不是 seam,而是每个实现仍必须实现和测试的推测性表面。 + +### `SessionPersistence.has()` 与 `.delete()` + +该抽象服务在 create/append 之外声明了更多操作:`load`、`list`、`has`、`delete`。生产消费方用 `load()` 和 `list()` 完成恢复与会话发现,而没有任何生产调用方使用持久化的 `has()` 或 `delete()`。协议和 UI 代码中名称相似的内存集合调用与此无关。持久化 `has`/`delete` 的唯一调用者是契约测试套件和各后端的 spec。 + +`has()` 不仅未被使用:在 `loadStored(id)` 已负责持久化存在性检查的情况下,它仍增加了协调器的已跟踪/未跟踪探测和一个契约分支。`delete()` 则拖入每个后端都必须实现的 `deleteStored` 后端钩子。这属于[删除可变会话 summary](2026-06-19-drop-mutable-session-summary.md) 的同类模式:契约测试覆盖了两者,但已发布代码从不会询问“这个会话是否已持久化?”或删除某个会话。 + +## 决策 + +没有消费方使用的方法被移除——从抽象 seam、实现,以及仅为覆盖它们而存在的契约/spec 测试套件中移除: + +- `SessionPersistence.has()` / `.delete()` 已移除:抽象声明、协调器的 `has`/`delete`/`deleteCore`,以及 `PersistenceBackend.deleteStored` 钩子均消失(jsonl 和 sqlite 都只是为了满足该钩子才实现 `deleteStored`,这些实现也一并移除)。后端属于[双后端](../architecture/2026-06-14-session-persistence.md)设计,其他方面不在范围内;删除它们为没有消费方的钩子所做的实现,是删除钩子的一部分,而非重新设计后端。 +- 所有文档和源码注释引用都已更新为保留下来的四方法、仅含 `list()` 的契约——不仅包括字面上的 `has(`/`delete(`/`deleteStored` 拼写,还包括 `{@link has}`/`{@link delete}` JSDoc 链接和“六个公共方法”的计数——涉及 seam 和后端 README、[docs/architecture.md](../../../../docs/architecture.md)、[会话持久化](../architecture/2026-06-14-session-persistence.md)与[写入协调器](../architecture/2026-06-18-shared-persistence-write-coordinator.md) Agent Note,以及协调器/后端 JSDoc。 + +## 曾考虑的替代方案 + +### 为什么不以「seam 应当完整」为由保留? + +「持久化 seam 理应提供 delete」这种直觉是真实的——但它恰恰是预发布阶段所警惕的投机性完整([AGENTS.md](../../../../AGENTS.md):为正确的基础优化,而非为你并不拥有的假想调用者优化)。`delete()` 是一个方法,等消费方真正需要时再加回来即可:一个删除旧会话的会话管理 UI 会需要它——到那时再加,基于该 UI 的真实需求来设计(软删除?级联?确认?),而非现在猜测。 + +在有活跃消费方的情况下重新添加一个 seam 方法,成本低且设计更优,因为消费方锚定了契约。在无人使用的情况下保留它,意味着每个实现(以及未来的每个后端)都必须实现和测试一个无实际作用的方法。 + +## 验证 + +`has`/`delete`/`deleteStored` 已从持久化 seam、实现和契约测试套件中移除,没有新增无用导出;剩余操作(`create`/`append`/`load`/`list`)未受影响,基于持久化的会话查询和崩溃恢复行为完全一致;seam README 和 `docs/architecture.md` 仅列出存留的方法。 + +## 后果 + +- **`delete()` 是产品最终会需要的操作。** 确实如此,但「最终」正是关键。现在删除、将来基于真实消费方重新添加,严格优于发布一份猜测的契约。两个后端各自减少了一个 `deleteStored` 实现,这是在本次范围之外的包中的有限改动。 +- **低耦合。** 移除局限于持久化 seam + 实现 + 测试;没有跨包消费方引用被移除的方法,因此除文档外没有涟漪效应。 + +规模不大,但它将 seam 从「实现必须为无人提供什么」恢复为「恰好是消费方使用的东西」。 diff --git a/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.i18n.yaml b/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.i18n.yaml new file mode 100644 index 0000000000..f6cc14538d --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-public-agent-stop-surface.md: e22c4389df18f3c9ca96763fc097eabefcc5b761 +2026-06-20-public-agent-stop-surface.zh.md: e2647b498a8c906579b4fd2b50f94d1c326fe784 diff --git a/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.md b/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.md index 824efc804c..e22c4389df 100644 --- a/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.md +++ b/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-public-agent-stop-surface.zh.md) + > **Implementation note:** Only `abort()` was removed. `whenIdle()` remains because it is the public quiescence signal and safely handles waiter settlement and replacement-turn races; consumers should not reconstruct that behavior from status transitions. ## Problem @@ -16,7 +18,7 @@ The extra surface area made the loop carry a public verb that is mostly a teardo `cancel()` is the only public *stop* primitive on `Agent`. Lifecycle owners use `AgentHandle.dispose()` to stop and unregister an agent; non-owners use `cancel()` to abandon current and queued work. The implementation keeps a private turn cancellation holder, but it is not part of the plugin-facing `Agent` contract. -`whenIdle()` is **retained** as the public quiescence-observation primitive (resolve once the agent settles out of `running`, resolve immediately when already idle, await the loop exit when disposed). It is not a stop verb; it is how a non-owner observes the stop *completing* without disposing the agent. Its live consumers are ACP and agent tests that await settlement through this public seam (`packages/ui/acp/tests`, `packages/core/agent-loop/tests`); the production ACP bridge owns its agents and tears them down through `AgentHandle.dispose()`, so `packages/ui/acp/src` itself has no `whenIdle()` call. +`whenIdle()` is **retained** as the public quiescence-observation primitive (resolve once the agent settles out of `running`, resolve immediately when already idle, await the loop exit when disposed). It is not a stop verb; it is how a non-owner observes the stop *completing* without disposing the agent. Its live consumers are ACP and agent tests that await settlement through this public seam (`packages/acp/acp/tests`, `packages/core/agent-loop/tests`); the production ACP bridge owns its agents and tears them down through `AgentHandle.dispose()`, so `packages/acp/acp/src` itself has no `whenIdle()` call. Public `abort()` is absent, and the disposer remains async and waits for the loop to stop. Tests exercise cancellation through the public typed cause and explicit signal seams rather than reaching into the holder. diff --git a/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.zh.md b/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.zh.md new file mode 100644 index 0000000000..e2647b498a --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 保留单一公开停止原语 + +Status: implemented + +[English](2026-06-20-public-agent-stop-surface.md) | 中文 + +> **实现说明:** 仅移除了 `abort()`。`whenIdle()` 予以保留,因为它是公开的完全停稳信号,能安全处理等待者结算与替换轮次竞态;消费方不应从状态转换中自行重建该行为。 + +## 问题 + +公共 `Agent` handle 暴露了两种相互重叠的在途工作停止方式:仅针对步骤的 `abort()` 和感知队列的 `cancel()`。前者保留已排队输入,后者则清除已排队和 steering(中途引导)工作,并中止活动轮次。在生产中,ACP(Agent Client Protocol)对 `session/cancel` 使用 `cancel()`,生命周期拥有者则通过 `AgentHandle.dispose()` 拆除 agent(智能体)。没有生产调用方需要一个裸的、仅针对步骤的 abort。 + +行为差异确实存在,但已发布代码不需要较窄的操作。AgentLoop 改为为整个轮次拥有一个私有取消 holder。`cancel(cause?)` 携带类型化的 `user` 或 `parent` 原因,默认为 `user`,并丢弃待处理输入;释放仍是单独的生命周期中断。完整的归属与传播契约位于[显式轮次取消 Agent Note(agent 决策记录)](../architecture/2026-07-16-explicit-turn-cancellation.md)。 + +多余的公开接口使得循环不得不承载一个本质上属于内部拆卸的公开动词:`abort()` 必须被文档描述为有别于队列感知的取消,尽管 UI 取消几乎总是需要更广泛的操作。 + +## 决策 + +`cancel()` 是 `Agent` 上唯一的公共*停止*原语。生命周期拥有者使用 `AgentHandle.dispose()` 停止并注销 agent;非拥有者使用 `cancel()` 放弃当前和已排队工作。实现保留一个私有轮次取消 holder,但它不属于面向插件的 `Agent` 契约。 + +`whenIdle()` **保留**为公开的完全停稳观测原语(agent 从 `running` 状态稳定后 resolve,已处于 idle 时立即 resolve,dispose 后等待循环退出)。它不是停止动词;它是非所有者在不 dispose agent 的前提下观测停止*完成*的方式。它的活跃消费方是 ACP 和通过此公开 seam 等待结算的 agent 测试(`packages/acp/acp/tests`、`packages/core/agent-loop/tests`);生产环境的 ACP 桥接层拥有其 agent 并通过 `AgentHandle.dispose()` 销毁它们,因此 `packages/acp/acp/src` 本身没有 `whenIdle()` 调用。 + +公共 `abort()` 已不存在,disposer 仍为异步并等待循环停止。测试通过公共类型化原因和显式 signal seam 验证取消,而不会伸入 holder 内部。 + +## 曾考虑的替代方案 + +**同时移除 `whenIdle()`**:最初提案的形态,在对照代码验证前提后被推翻(上方的实现说明记录了完整过程):它是承重的完全停稳原语,迫使消费方手动观测 `running`→`idle` 转换正是防御性模式所警告的脆弱路径。 + +## 验证 + +`Agent` 不再暴露公开的 `abort()`,而 `cancel()`、`whenIdle()` 和 `steer()` 保留;ACP 取消调用 `cancel()`;拆卸通过 handle disposal 等待完全停稳,`whenIdle()` 在完全停稳时为非所有者观测者 resolve;测试套件覆盖取消和 disposal 作为两条受支持的停止路径。 + +## 后果 + +未来的插件无法通过公开接口仅中止当前模型/工具步骤而保留队列中的提示词。如果该用例变为现实需求,它应当带着一个具名消费方和更窄的契约回归。目前它是将私有循环机制保持公开的潜在泛化。 + +## 相关 + +本 Agent Note 只移除冗余的停止动词。轮次中途 steering 仍是一条有意保留的消息路径;完全停稳观察仍通过 `whenIdle()` 完成。最终公共表面包括 `send()`、`steer()`、`inject()`、`cancel()`、`whenIdle()`、status、options、会话和 identity。 diff --git a/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.i18n.yaml b/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.i18n.yaml new file mode 100644 index 0000000000..cfed1ac086 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-remove-agent-boundary-mirror-events.md: 31acbb122cf56adfdcfcbce602d09a35f7f13e17 +2026-06-20-remove-agent-boundary-mirror-events.zh.md: f386e8d1ccfc2df094645a3cf9ae9524091d2a4e diff --git a/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.md b/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.md index 910eb46e92..31acbb122c 100644 --- a/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.md +++ b/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-remove-agent-boundary-mirror-events.zh.md) + <!-- Shipped in AMENDED, narrowed form: the four turn/step BOUNDARY mirrors are removed; `agent/steering` and `agent/stream-chunk` were RETAINED here (they are not durable-boundary mirrors — see "Scope: what is and isn't removed"). @@ -13,7 +15,7 @@ Status: implemented ## Problem -The loop records the canonical transcript in `SessionEvent` and also emitted a parallel set of live `agent/*` boundary mirror events: `agent/turn-start`, `agent/turn-end`, `agent/step-start`, and `agent/step-end`. The mirrors made consumers choose between two sources of truth for the SAME durable fact. ACP already chose the session log for the editor-facing transcript because it is the one durable, replayable record; consuming a live mirror would require reconciling its timing with the boundary already stored in that log. The stdio UI was the only production consumer that still rendered turn boundaries from the mirror events; it already rendered tool calls and results from `session/event`. +The loop records the canonical transcript in `SessionEvent` and also emitted a parallel set of live `agent/*` boundary mirror events: `agent/turn-start`, `agent/turn-end`, `agent/step-start`, and `agent/step-end`. The mirrors made consumers choose between two sources of truth for the SAME durable fact. ACP already chose the session log for prompt settlement and committed output because it is the one durable, replayable record; consuming a live mirror would require reconciling its timing with the boundary already stored in that log. The stdio UI was the only production consumer that still rendered turn boundaries from the mirror events; it already rendered tool calls and results from `session/event`. This duplication is not free. Every lifecycle change had to update the session event, the mirror event, docs, invariants, tests, and snapshot expectations. The duplicate boundary events also made failure ordering subtle: a turn can be durably closed before a live `agent/turn-end` listener runs, so a post-boundary listener failure has no valid in-log position left and must be reported out of band. diff --git a/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.zh.md b/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.zh.md new file mode 100644 index 0000000000..f386e8d1cc --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.zh.md @@ -0,0 +1,47 @@ +# Agent Note: 停止将持久化边界镜像为 agent 事件 + +Status: implemented + +[English](2026-06-20-remove-agent-boundary-mirror-events.md) | 中文 + +<!-- 以修订、收窄后的形式落地: + 移除了四个轮次/步骤边界镜像;此处保留了 `agent/steering` 和 + `agent/stream-chunk`(它们不是持久边界镜像——参见 + “范围:移除什么、不移除什么”)。原始提案将 `agent/steering` 与其他项一并 + 移除;把它排除在外,使本 Agent Note 的范围保持在边界上。后来每个保留事件 + 都由各自的决策移除——参见 + [停止将 token 流镜像为 agent 事件](2026-07-02-remove-stream-chunk-mirror.md) + 和[移除 `agent/steering` 镜像 emit](2026-07-04-remove-agent-steering-mirror.md)。 --> + +## 问题 + +循环在 `SessionEvent` 中记录规范 transcript(文本记录),同时还发出一组并行的实时 `agent/*` 边界镜像事件:`agent/turn-start`、`agent/turn-end`、`agent/step-start` 和 `agent/step-end`。这些镜像迫使消费方在同一持久事实的两个真源之间做选择。ACP(Agent Client Protocol)已经为提示词结算和已提交输出选择会话日志,因为它是唯一持久、可重放的记录;消费实时镜像需要把它的时序与日志中已经存储的边界进行调和。stdio UI 是唯一仍从镜像事件渲染轮次边界的生产消费方;它已经从 `session/event` 渲染工具调用和结果。 + +这种重复并非零成本。每次生命周期变更都需要同时更新会话事件、镜像事件、文档、不变式、测试和快照预期。重复的边界事件还使失败排序变得微妙:一个轮次可能在实时 `agent/turn-end` 监听器运行之前就已被持久化关闭,因此边界之后的监听器失败在日志中已没有合法位置可以插入,只能带外上报。 + +## 决策 + +将 `session/event` 作为唯一的实时边界/transcript(文本记录)流。需要渲染轮次、工具调用、工具结果、助手消息和持久化边界的消费方统一订阅 `session/event`,从持久化层使用的同一套事件词汇中派生 UI。 + +四个持久边界镜像——`agent/turn-start`、`agent/turn-end`、`agent/step-start`、`agent/step-end`——已从 agent(智能体)事件分类中移除。希望在边界处取得 agent handle 的 UI 会保留来自 `agent/created`/`agent/disposed` 的实时目标对象,并直接比较其会话;`dsh-ui-stdio` 据此为应用拥有的 agent 标记 `[main turn N]` 头部,其他会话则渲染其持久 id。规范记录仍是事件溯源会话日志。 + +步骤镜像(完全没有消费方)最先在[事件域语义 Agent Note(agent 决策记录)](../architecture/2026-06-30-event-domain-semantics.md) 中移除;该 Agent Note 当时以 stdio UI 需要在轮次边界取得 `Agent` handle 为由,保留了轮次镜像。本 Agent Note 完成余下工作:`dsh-ui-stdio` 是可随时丢弃的测试 REPL,其渲染可以自由变化,因此“ui-stdio 需要它”并不是保留镜像的理由——它读取 `session/event`,只保留自己的实时目标对象。 + +## 范围:移除什么、不移除什么 + +已移除(持久边界镜像——每项都以会话日志为权威):`agent/turn-start`、`agent/turn-end`、`agent/step-start`、`agent/step-end`。 + +保留——不是持久边界镜像,因此不在本决策范围内: + +- `agent/steering`——不是边界,因此不在本决策范围内(原始提案将其一并移除;在此会造成范围蔓延)。它镜像持久的 `steering/message` 控制记录,而非边界,后来由自己的后续决策移除:[移除 `agent/steering` 镜像 emit](2026-07-04-remove-agent-steering-mirror.md)。 +- `agent/stream-chunk`——实时 token 流。不在本决策范围内(它镜像持久的 `assistant/chunk`,而非边界),后来由自己的后续决策移除:[停止将 token 流镜像为 agent 事件](2026-07-02-remove-stream-chunk-mirror.md)。 +- `agent/created`、`agent/disposed`、`agent/status`、`agent/error`、`agent/queued`——不属于 transcript 数据的生命周期/控制事件。尤其是 `agent/queued`,它是在任何持久事件存在之前触发的 inbox 确认(取消的排队工作可能永远不会进入日志),所以有意只保留为实时事件。 + +## 曾考虑的替代方案 + +- **将 `agent/steering` 一并移除**——原始提案的形状;作为范围蔓延被排除:它镜像持久的 `steering/message` 控制记录,而非边界,后来由[自己的决策](2026-07-04-remove-agent-steering-mirror.md)移除(`agent/stream-chunk` 也由[流分片镜像 Agent Note](2026-07-02-remove-stream-chunk-mirror.md)移除)。 +- **为 stdio UI 保留轮次镜像**——[事件域语义 Agent Note](../architecture/2026-06-30-event-domain-semantics.md) 的原始立场;在此否决,因为 `dsh-ui-stdio` 是可随时丢弃的测试 REPL,而非承载关键约束的消费方,并且它改为根据 `session/event` 加自己的实时目标对象渲染边界。 + +## 后果 + +插件不能再从便捷的 `Agent` 优先事件观察轮次/步骤边界。它需要订阅 `session/event`;如果需要实时对象,则通过 `ctx.agents` 解析共享 id,或保留自己已经拥有的对象。这是可以接受的取舍:边界消费方不应依赖可能与持久日志发生漂移的第二条事件 feed。 diff --git a/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.i18n.yaml b/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.i18n.yaml new file mode 100644 index 0000000000..291dd7d009 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-unify-agent-and-session-id.md: c55152f4f13fe0acb530503e84f465799007cff7 +2026-06-20-unify-agent-and-session-id.zh.md: 1fa2fe1fd64478bfe17c590e45abd0cf8281cbe4 diff --git a/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.md b/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.md index a8a2c375b5..c55152f4f1 100644 --- a/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.md +++ b/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-unify-agent-and-session-id.zh.md) + ## Problem A live agent/session pair needs one identity for registry routing, event sourcing, and persistence. Giving the factory independent `agentId` and `sessionId` inputs would permit pairings no production path can use, while forcing every consumer to choose or translate between two names for the same lifecycle. diff --git a/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.zh.md b/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.zh.md new file mode 100644 index 0000000000..1fa2fe1fd6 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.zh.md @@ -0,0 +1,40 @@ +# Agent Note: 统一 agent id 与会话 id + +Status: implemented + +[English](2026-06-20-unify-agent-and-session-id.md) | 中文 + +## 问题 + +一个实时 agent(智能体)/会话对需要使用同一 identity 完成注册表路由、事件溯源和持久化。让 factory 接受相互独立的 `agentId` 和 `sessionId` 输入,会允许任何生产路径都无法使用的配对,同时迫使每个消费方为同一生命周期在两个名称之间选择或转换。 + +ACP(Agent Client Protocol)对两种 identity 使用相同值。Stdio 和钩子也在会话事件流上工作,并且直接需要对应的实时 agent;没有生产路径会把一个实时 agent 对象重新附着到多个会话,或通过多个 agent id 驱动一个会话。 + +[agent 范围运行时](../architecture/2026-07-12-agent-scope-runtime-design.md)使用同一个 `AgentCreationTransaction` 执行创建和恢复,agent/会话条目共享相同的最终条目冲突规则。第二个 identity 并不代表单独的存活性、回滚或完全停稳;它只会围绕同一事务增加 API 与转换状态。 + +会话 identity 同样只有一个归属,即 `Session.header.id`;`Session.id` 是派生访问器,而非需要重复验证的独立状态。 + +## 决策 + +agent 的注册表 id 等于其会话 id。`CreateAgentOptions` 接受一个 `sessionId`,同时用于两个最终注册表条目;恢复时以 `resumeSessionId` 注册 agent;进程内 subagent 创建使用子会话 id;`Session.id` 则派生自 `header.id`。远程 ACP 运行没有本地 agent/会话对:它保留一个由父项铸造的生命周期 id,而子服务器线协议内的会话 id 仅用于 ACP 调用。现有创建事务、最终条目冲突检查和精确条目分离语义保持不变;唯一职责是在本地 id 之间转换的 map 与字段已经消失。 + +配置驱动路径保留 `agents[].id` 作为稳定配置标签,而非实时路由 identity。普通的全新启动会铸造组合 id `${label}-session-${randomUUID()}`,使持久重启不会冲突。耦合应用可以预先铸造并传入精确的 `sessionId`:首次使用时创建它,而当持久化服务已经存在时,AgentLoop 重新挂载会在同一 identity 下恢复已物化历史。`resumeSessionId` 则要求已有的持久化 identity。两个精确 id 输入互斥。Stdio 使用“恢复或创建”形式,使配置创建的 agent 和 UI 在循环重载之间共享一个不透明 identity,而不是根据前缀猜测。日志可以使用稳定标签,而所有实时与持久查找都使用同一个 `SessionId`。 + +`agent/created` 和 `agent/disposed` 保留。它们是成对的发布生命周期事件,而非 identity 别名;以后若发现没有消费方并要移除,必须先重新搜索,再提出独立提案。 + +## 曾考虑的替代方案 + +**保持路由与日志 identity 分离。** 稳定的配置标签加全新的持久对话确实有用,但不需要两个实时 identity:标签可以继续作为配置/显示元数据,而每次运行的组合 `SessionId` 负责路由和持久化。保留两个 id 会让转换 map 持续存在,允许不可能的配对,却不会增加生命周期功能。 + +## 验证 + +- Agent 创建/恢复和 subagent 创建只携带一个 identity,`Session` 也只在一个位置存储它。 +- 创建事务继续覆盖最终条目冲突、精确条目分离、回滚和完全停稳,无需 identity 特有的生命周期状态。 +- ACP、stdio、钩子、bash 归属、持久化和 lineage 直接使用共享 `SessionId`。ACP subagent 后端在父命名空间中铸造其生命周期 id,因为子服务器返回的会话 id 仅在服务器本地有效;ACP bridge 根据正向会话 map 验证精确的 `Agent` 归属;JSON-RPC 只转发生命周期事件中由服务快照保存的 `local` 标记为 true 的事件,从带范围的事件 carrier 取得委托父项,并且不保留子 identity 或 lineage cache。 +- 配置驱动的恢复还是创建策略是显式的,并在持久化重启场景下得到覆盖。 +- 生产监听器搜索确认保留 `agent/created`/`agent/disposed` 及其发布语义。 +- 类型检查、覆盖率、快照、doc-sync、module-graph 校验、构建与 hygiene 全部通过。 + +## 后果 + +这排除了潜在的多会话 actor 和会话交接设计,并使由客户端选择、已持久化的会话 identity 成为注册表 identity。如果独立路由 identity 成为真实需求,就需要显式的生命周期设计,而不是由调用方提供一对不受约束的值。 diff --git a/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.i18n.yaml b/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.i18n.yaml new file mode 100644 index 0000000000..6e428fa348 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-26-fsspec-style-fs-seam.md: d496f273e2635624e0ab8e70e06c8729563c5466 +2026-06-26-fsspec-style-fs-seam.zh.md: 18e4be5177f593253dc100a864b6c741904a90b2 diff --git a/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.md b/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.md index 3753fb803a..d496f273e2 100644 --- a/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.md +++ b/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-26-fsspec-style-fs-seam.zh.md) + ## Problem The filesystem capability from [filesystem-capability-seam](../architecture/2026-06-17-filesystem-capability-seam.md) currently makes one abstract `FileSystem` service own two different jobs: diff --git a/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.zh.md b/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.zh.md new file mode 100644 index 0000000000..18e4be5177 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.zh.md @@ -0,0 +1,130 @@ +# Agent Note: 拆分文件系统 seam——提供方文本变更操作与 `dsh-fs-policy` 插件 + +Status: implemented + +[English](2026-06-26-fsspec-style-fs-seam.md) | 中文 + +## 问题 + +[文件系统能力 seam](../architecture/2026-06-17-filesystem-capability-seam.md)中的文件系统能力目前让一个抽象 `FileSystem` 服务同时负责两项不同工作: + +1. **提供方操作**——解析目标、stat/版本元数据、文本读取/流式读取、原子写入,以及受保护的字面编辑。 +2. **面向 agent(智能体)的策略**——行窗口、字面编辑语义,以及读后写/编辑的观测状态。 + +这导致每个未来的后端都要重新实现面向模型的读取语义和观测策略。`readPage` 返回带行号的行和视图元数据;基础服务按 owner 存储文件状态,并区分 `full` 与 `partial` 读取。这些是有用的策略,但它们不是文件系统提供方的原语。字面文本变更则不同:版本守卫、字面匹配、歧义检测与原子重写必须留在提供方的变更边界内,但当前的 `applyEdit` 命名及其周围的 seam 将这一提供方操作绑定到了旧的读后编辑策略形状上。 + +这还造成了一个真实的用户体验死胡同:窗口化读取记录 `view: partial`,而 partial 视图无法授权 `edit`。一个模型读取了大文件的第 100-150 行,如果想编辑第 120 行,就必须先获取一次 `full` 读取,而对于超过读取上限的文件这可能做不到。字面编辑实际上只需要新鲜度:被匹配的字节仍然来自模型所读取的那个版本即可。 + +旧 Agent Note(agent 决策记录)已经推迟了独立的 `@deepseek-ai/dsh-fs-policy` 包。本 Agent Note 构建该层,使 `ctx.fs` 保持接近 fsspec 风格的存储原语(`info`/`cat`/`open`),但不把它变成完整的 fsspec。 + +## 决策 + +将栈拆为四层: + +```text +tool dsh-tool-fs model-facing schemas + read windowing + text rendering; the EXECUTOR (reads/writes/edits via ctx.fs, dispatches the fs/* events) +policy dsh-fs-policy observed-state + read-before-edit + write/edit freshness, contributed through the fs/* event gate (no service) +provider seam dsh-fs ctx.fs: text IO + atomic mutation primitives (optional version guard) +provider dsh-fs-local local implementation of ctx.fs +``` + +`dsh-tool-fs` 保持相同的面向模型的 `read`/`write`/`edit` schema。它是执行器:注入 `fs`(不是策略服务)并直接访问 `ctx.fs`,拥有读取窗口化逻辑,并分发 `fs/*` 事件以便 `dsh-fs-policy` 进行门控和记录。 + +本 Agent Note 决定了四层拆分、提供方契约和新鲜度策略。随后,[事件门禁 Agent Note](../architecture/2026-06-26-file-context-as-event-gate.md) 细化了工具↔策略耦合:`dsh-fs-policy` 是通过 `fs/*` 事件参与的门禁插件,而非 `ctx.fileContext` 方法服务,因此工具不会在方法层与其耦合;读取窗口和 fs I/O 位于 `dsh-tool-fs`。本文描述已经落地的事件门禁形状;提供方的版本守卫可选(省略即无条件裸提供方)。 + +## 提供方契约 + +`@deepseek-ai/dsh-fs` 收缩为提供方文本 IO 加受保护的文本变更: + +```ts ignore-check +abstract resolve(path: string, opts?: { cwd?: string; signal?: AbortSignal }): Promise<FsTarget> +abstract stat(target: FsTarget, signal?: AbortSignal): Promise<FsInfo | undefined> +abstract readText(target: FsTarget, signal?: AbortSignal): Promise<string> +abstract streamText(target: FsTarget, signal?: AbortSignal): Promise<AsyncIterable<string>> +abstract writeText(target: FsTarget, content: string, expected: FsWriteIntent, signal?: AbortSignal): Promise<FsWriteOutcome> +abstract editText(target: FsTarget, edit: FsEditRequest, expected: { version: FsVersion }, signal?: AbortSignal): Promise<FsEditOutcome> + +interface FsInfo { + version: FsVersion + type: 'file' | 'directory' | 'other' + size?: number +} + +type FsWriteIntent = + | { kind: 'createIfAbsent' } + | { kind: 'replaceIfVersion'; version: FsVersion } +``` + +`stat` 返回元数据而非内容。`version` 是新鲜度令牌;`type` 让执行器在读取前拒绝目录/特殊文件;`size` 让 `read` 工具无需通过失败探测即可选择 `readText` 还是 `streamText`。`undefined` 表示目标不存在。 + +`readText` 读取整个常规文本文件。`streamText` 以相同的文本语义流式读取大文件。两个提供方原语负责常规文件检查、UTF-8 解码、二进制/NUL 拒绝以及 `FS_NOT_TEXT`;策略层从不处理原始字节,也不重新实现跨分片解码。`readText` 是小文件/直接全文件原语,而面向模型的大文件读取使用 `streamText`。 + +`writeText` 是原子的临时文件 + rename,带有显式的写入期望。`createIfAbsent` 创建不存在的目标,对已存在的目标以 `FS_NOT_OBSERVED` 拒绝;这是 owner 没有先前读取时使用的路径。`replaceIfVersion` 仅在目标以观测到的版本存在时替换;目标不存在或版本不匹配时抛出 `FS_STALE_VERSION`。 + +`editText` 是提供方级别的受保护文本变更。启用守卫时,它首先验证目标仍以 `expected.version` 存在,然后读取当前文本、应用字面替换并原子写入。陈旧检查必须在字面匹配之前发生,这样基于旧读取的编辑会报告 `FS_STALE_VERSION`,而不是对更新内容进行匹配后报告 `FS_EDIT_NOT_FOUND` 或 `FS_AMBIGUOUS_EDIT`。将此原语保留在提供方 seam 上,保持了后端本地锁定的能力,也让未来的远程后端能够实现原生的 compare-and-edit,而无需策略层拉取整个文件。 + +这是一个*文本存储* seam,刻意比字节级 fsspec(`cat`/`open` 返回原始字节)高半个层次。UTF-8 解码、二进制/NUL 拒绝、受保护的全文件写入和受保护的字面文本编辑都在提供方内完成,因此策略层从不接触原始字节、不重新实现跨分片解码、也不将陈旧检查与变更临界区分离。面向模型的概念仍然不下沉到提供方:行窗口、带行号的行、渲染的页脚、观测状态存储都不会泄漏下去。 + +从 `dsh-fs` 删除:`readPage`、`FsExpectation`、`FsView`、`FsStateSource`、`FsReadRequest`、`FsTextLine`、行/窗口常量、`formatReadBody` 和 observed-state `WeakMap`。`applyEdit` 由更窄的提供方原语 `editText` 取代,其契约是带版本守卫的字面文本变更,而非策略层读取授权。`FS_PARTIAL_OBSERVATION` code 也从 `FsErrorCode` 分类中移除:新鲜度授权没有部分/完整之分,因此没有任何路径会抛出它。`FsTargetKey` 和 `FsVersion` 按现有[品牌化 id Agent Note](../architecture/2026-06-20-branded-ids.md) 成为品牌化不透明 id。 + +## 策略契约 + +`@deepseek-ai/dsh-fs-policy` 是插件,而非服务:它不注册任何 `ctx.*` 键,也不注入任何内容。它拥有不应位于 `FileSystem` 提供方基类上的写入/编辑新鲜度策略和 observed state(否则沙箱/远程后端会继承不该由其承载的面向模型观察策略)。它通过执行器分派的 `fs/*` 事件门禁贡献该策略。(本 Agent Note 最初提议带有 `read`/`write`/`edit` 方法的具体 `ctx.fileContext` 服务;[事件门禁 Agent Note](../architecture/2026-06-26-file-context-as-event-gate.md) 将其细化为本文所述插件,使工具永远不会在方法层与策略耦合。) + +观测状态以 `WeakMap<owner, Map<targetKey, FsVersion>>` 的形式存放于此。当且仅当 owner 读取、写入或编辑过该目标时,条目才存在(每次成功都会发出 `fs/observed`),因此条目的存在*本身就是*先前观测的记录——没有单独的 `hasRead` 标志。owner 从不透明的事件 actor(`{ agent?: { session? } }`)结构化派生,该形状定义在 `dsh-fs-policy` 中而非 `dsh-fs` 中。 + +该插件决定三个 `fs/*` 事件: + +- `fs/write-intent`——无先前观测 ⇒ `{ kind: 'createIfAbsent' }`(只有新文件可以盲创建);有先前观测 ⇒ `{ kind: 'replaceIfVersion', version: vObserved }`(已有文件仅在自观测以来未变时才替换)。单槽决策;不调用 `next()`。 +- `fs/edit-intent`——要求 owner 有先前观测(否则 `FS_NOT_OBSERVED`);返回 `{ version: vObserved }` 作为 CAS 基础。它不实现字面替换——它授权并提供版本,提供方的变更临界区负责应用守卫,因此基于同一观测版本的并发编辑仍然是一赢一陈旧。 +- `fs/observed`——在成功的读取/写入/编辑后,为该 owner+target 记录 `{ version }`。同步、仅副作用的 `WeakMap.set`。 + +该插件不做任何文件系统 I/O:「你是否观测过此文件?」是一次 `WeakMap` 查找,而「你读取的版本是否仍然是当前版本?」在 `ctx.fs.editText`/`writeText` 内部、与执行变更相同的原子锁中决定——插件只提供 `vObserved` 作为基础。 + +## 工具契约 + +`dsh-tool-fs` 保持相同的 schema 和提示词表面。`read` 仍然暴露 `file_path`、`offset` 和 `limit`;`write` 和 `edit` 不变。它是执行器:验证模型参数,通过 `ctx.fs` 直接读取/写入/编辑,拥有行窗口化和结果渲染(`N: text`、页脚、`<path>/<content>` 信封),并分发 `fs/*` 事件。 + +每个变更操作先分发其 intent waterfall(瀑布式事件),带有 `undefined` 裸提供方默认值,然后调用 `ctx.fs`,再发出 `fs/observed`。例如 `write` 执行 `ctx.waterfall('fs/write-intent', target, exec, () => undefined)` → `ctx.fs.writeText(target, content, intent)` → `ctx.emit('fs/observed', …)`。`read` 先 stat 一次,然后读取/流式读取,构建窗口,最后发出 `fs/observed`。将 `exec` 作为 actor 传递,让 `dsh-fs-policy` 无需工具深入策略即可派生 owner。 + +由于策略通过带有 `undefined` 默认值的事件贡献,`dsh-tool-fs` 不与 `dsh-fs-policy` 产生方法耦合:在插件缺席时,每个 intent waterfall 都落到 `undefined`(无条件裸提供方写入/编辑),`fs/observed` 没有监听器。加载插件后即可叠加读后写/编辑策略。 + +## 并发边界 + +进程内更新是安全的:本地后端保持既有的按目标变更锁,因此版本检查-然后-rename 是串行化的,失败的更新会看到 `FS_STALE_VERSION`。 + +进程内创建由同一个按目标变更锁保护:两个调用者以 `createIfAbsent` 竞争时串行化,一个创建成功,另一个看到目标已存在并收到 `FS_NOT_OBSERVED`。跨进程创建仅为尽力而为;本地的 stat-then-rename 守卫无法在所有未来后端上提供可移植的排他创建保证。 + +跨进程写入是尽力而为的新鲜度加原子替换:`mtime:size` 通常能捕获编辑器保存,但同一 tick 相同大小的写入可能遗漏;原子的 temp+rename 防止文件撕裂但不能防止所有丢失更新。 + +## 取代 + +本 Agent Note 推翻[文件系统能力 seam](../architecture/2026-06-17-filesystem-capability-seam.md)中的两项决策,并收窄第三项: + +- 读后写/编辑策略从 `ctx.fs` 移出,进入 `dsh-fs-policy` 插件(通过 `fs/*` 事件门控)。 +- 文本读取不再返回后端编号的行记录或 `full`/`partial` 视图;授权基于版本新鲜度,因此窗口化读取在文件未变时即可授权编辑。 +- 字面编辑不再位于旧的 `applyEdit` API 之后(该 API 混合了后端变更与 seam 拥有的观测策略)。它作为 `editText` 保留为提供方原语,因为版本守卫 + 字面匹配 + 原子重写必须留在提供方的变更临界区内。 + +保留的内容:接口/实现/消费方纪律、消费方不导入后端规则、后端定义的 target/version/display 元数据、原子本地写入,以及共享的 `FsError` 分类体系。 + +## 验证 + +`dsh-fs` 精确暴露 `resolve`/`stat`/`readText`/`streamText`/`writeText`/`editText`(`stat` 返回 `FsInfo | undefined`,`writeText` 接受 `FsWriteIntent`),已删除的类型/原语不再存在;`dsh-fs-local` 不包含行、视图或 `formatReadBody` 逻辑;面向模型的 schema 保持逐字节不变。测试固定了以下行为:窗口化读取授权对未变文件的后续编辑;基于陈旧读取的编辑在尝试字面匹配之前报告 `FS_STALE_VERSION`;版本 CAS 行为得以保留;观测契约成立(`read` 工具的读取记录观测状态;直接 `ctx.fs` 读取不记录);`dsh-fs-policy` 具有 HMR(热模块替换)/dispose(资源释放)覆盖率。 + +## 后续扩展 + +后来,[为文件系统 seam 添加直接目录列表](../architecture/2026-07-03-filesystem-directory-listing-seam.md)进一步扩展了该 seam。该后续工作单独跟踪,使本 Agent Note 的验收标准继续描述最初落地的 fsspec 风格改造。 + +## 曾考虑的替代方案 + +- **字节级 fsspec(`cat`/`open` 返回原始字节)**:否决。该 seam 刻意定位为文本存储,比字节级高半个层次,这样 UTF-8 解码、二进制/NUL 拒绝和受保护的文本变更只在提供方实现一次,策略层从不接触原始字节,也不将陈旧检查与变更临界区分离。 +- **具体的 `ctx.fileContext` 方法服务**——本 Agent Note 最初的策略形状;[事件门禁 Agent Note](../architecture/2026-06-26-file-context-as-event-gate.md) 将其重做为门禁插件,使工具永远不会在方法层与策略耦合。 +- **在提供方保留 `readPage` 和 `full`/`partial` 视图授权**:「取代」一节所逆转的重构前形态。视图完整性不是编辑安全所需的,版本新鲜度才是;而视图规则使超过读取上限的大文件无法编辑。 + +## 后果 + +- 新增第四个 fs 包和一个新的插件层。这是有意为之:它是此前推迟的策略层,而非第二个抽象后端 seam。 +- 直接使用 `ctx.fs` 会绕过策略:直接 `ctx.fs.readText` 不发出 `fs/observed`,因此在默认策略下,后续 `edit` 会以 `FS_NOT_OBSERVED` 拒绝,直到通过 `read` 工具读取该文件。这一失败是显式且有文档记录的。 +- 大文件行窗口化从后端移至 `dsh-tool-fs` 中的 `read` 工具;文本解码和二进制拒绝留在 `ctx.fs.streamText` 中,因此这只是窗口化逻辑的迁移,而非第二套文本 IO 实现。 +- 将 `editText` 保留在提供方 seam 上意味着每个后端都必须实现字面替换契约。这是有意为之:该操作不是纯存储,但陈旧守卫 + 字面匹配 + 原子重写是必须保持在一起的单元,以确保正确的错误归因和并发行为。该契约应保持窄且仅限文本,以便未来后端可以原生实现或通过全文件重写实现。 +- 新鲜度允许在窗口化读取后进行全文件 `write`。这比旧的视图检查更弱,但避免了大文件无法编辑的问题;提示词引导仍然不鼓励盲目的全文件替换。 diff --git a/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.i18n.yaml new file mode 100644 index 0000000000..3a0fde3d06 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-02-remove-stream-chunk-mirror.md: 8b26589a9e89f83d631fa98e801a8d3e08e105d0 +2026-07-02-remove-stream-chunk-mirror.zh.md: fcd8c53b8b1b2a5b81f9f929ffd9e06ff6128e45 diff --git a/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.md b/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.md index c79202b95a..8b26589a9e 100644 --- a/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.md +++ b/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-02-remove-stream-chunk-mirror.zh.md) + ## Problem The loop records every model token delta as a durable `assistant/chunk` session event AND emitted a parallel live `agent/stream-chunk` Cordis event carrying the identical data. In `packages/core/agent-loop/src/loop.ts` the two sat one line apart: @@ -25,7 +27,7 @@ The premise the deferral hinged on is settled: chunk persistence is authoritativ Remove `agent/stream-chunk` from the agent event taxonomy. The token stream is read off `session/event` as `assistant/chunk`, the same feed persistence and replay already use — `session/event` is the single live transcript stream (assistant chunks, turn/step boundaries, tool activity, todos). -**Consumers.** The only production consumer that mattered — the ACP bridge (`dsh-acp`), the real editor-facing streaming surface — already renders `assistant/chunk` off `session/event`, never `agent/stream-chunk`, so it is unaffected. The stdio UI (`dsh-ui-stdio`, a disposable test REPL) was the sole live consumer; it already had a `session/event` listener (from the boundary migration), so its chunk rendering folded into that listener as an `assistant/chunk` case. Consolidating to one listener also removed a latent hazard: the `inReasoning` dim-SGR flag was previously shared across two separate listeners (`agent/stream-chunk` and `session/event`), so a chunk and a boundary racing on it had no defined order; a single listener over the append order makes the interleaving deterministic. +**Consumers.** Persistence, replay, and interactive renderers consume the authoritative session stream directly. The [automation-only ACP bridge](2026-07-23-acp-automation-only-protocol.md) emits committed `assistant/message` text rather than raw chunks, so it needs neither event. No production consumer requires an `Agent`-first token mirror. ## Scope diff --git a/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.zh.md b/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.zh.md new file mode 100644 index 0000000000..fcd8c53b8b --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.zh.md @@ -0,0 +1,47 @@ +# Agent Note: 停止将 token 流镜像为 agent 事件 + +Status: implemented + +[English](2026-07-02-remove-stream-chunk-mirror.md) | 中文 + +## 问题 + +agent loop(智能体循环)将模型的每个 token delta 同时记录为持久的 `assistant/chunk` 会话事件,并发射一个携带相同数据的并行实时 `agent/stream-chunk` Cordis 事件。在 `packages/core/agent-loop/src/loop.ts` 中,二者仅相隔一行: + +```ts ignore-check +const chunkEvent = session.append('assistant/chunk', { turn, step, chunk }) +chunkSeqs.push(chunkEvent.seq) +ctx.emit('agent/stream-chunk', agent, turn, step, chunk) // ← the mirror +``` + +- 持久事件:`assistant/chunk: { turn, step, chunk }`。 +- 实时发射:`agent/stream-chunk(agent, turn, step, chunk)`——相同的 `StreamChunk`,相同的 `turn`/`step`。 + +实时发射相比会话事件唯一多出的东西是实时的 `Agent` 句柄,而唯一的消费方直接丢弃了它(其处理函数签名为 `(_agent, _turn, _step, chunk)`)。 + +这与[移除边界镜像](2026-06-20-remove-agent-boundary-mirror-events.md)为轮次/步骤边界消除的重复相同:消费方面对同一持久事实的两个真源,每次变更都必须同时触及两者。该 Agent Note(agent 决策记录)没有把分片流一并纳入,而是推迟处理(“`assistant/chunk` 持久化仍承载关键约束,所以以后可以将分片流作为镜像评估,但那是一项独立决策”)。本 Agent Note 就是那项独立决策。 + +推迟所依赖的前提已经明确:分片持久化是权威的,且将保留。停止持久化分片、仅保留瞬态实时流事件的提案已被[否决](../../rejected/simplification/2026-06-20-assembled-assistant-messages-only.md)——高保真回放、部分失败的流以及快照回放都依赖持久化的 `assistant/chunk` 序列。因此 `session/event` 上的 `assistant/chunk` 是持久的、承重的 token 流,而 `agent/stream-chunk` 是它的纯冗余镜像。 + +## 决策 + +从 agent 事件分类体系中移除 `agent/stream-chunk`。token 流通过 `session/event` 以 `assistant/chunk` 的形式读取——持久化与回放已经使用的正是同一个序列。`session/event` 是唯一的实时 transcript(文本记录)流(assistant 分片、轮次/步骤边界、工具活动、todo)。 + +**消费方。** 持久化、回放和交互式渲染器直接消费权威的会话流。[仅面向自动化的 ACP(Agent Client Protocol)桥接层](2026-07-23-acp-automation-only-protocol.md)发出已提交的 `assistant/message` 文本而非原始分片,因此两种事件它都不需要。没有生产消费方需要一个 `Agent` 优先的 token 镜像。 + +## 范围 + +移除:`agent/stream-chunk`。 + +未触及: +- `assistant/chunk`(持久会话事件)——权威 token 流,原样保留。本 Agent Note 移除的是实时镜像,而非持久化(移除持久化的提案已单独遭到拒绝——见上文)。 +- `agent/steering`——本决策未触及(它是控制信号,不是 token 流)。其持久孪生事件是 `steering/message`,镜像发射由其自身的后续 Agent Note 移除:[移除 `agent/steering` 镜像发射](2026-07-04-remove-agent-steering-mirror.md)。 +- `agent/status`、`agent/error`、`agent/created`/`agent/disposed`、`agent/queued`、`agent/session-start`——生命周期/控制事件,不是 transcript 数据,也没有持久副本。 + +## 曾考虑的替代方案 + +**移除持久化、仅保留瞬态实时流**——反向裁剪,已被[单独否决](../../rejected/simplification/2026-06-20-assembled-assistant-messages-only.md):高保真回放、部分失败的流以及快照回放都依赖持久化的 `assistant/chunk` 序列。在此前提确定后,实时发射才是配对中冗余的那一半。 + +## 后果 + +插件不能再从 `Agent` 优先事件观察 token 增量。它需要订阅 `session/event`、过滤 `assistant/chunk`,并在需要时通过 `ctx.agents.get(session.id)` 直接查找对应的实时 handle。没有生产消费方需要在分片时刻取得实时 `Agent`;这与移除边界镜像所作的取舍相同,均可接受。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.i18n.yaml new file mode 100644 index 0000000000..8947371a42 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-drop-image-content-block.md: cdedf4bd5dfe60c72cea185d88b83d3b93928ff0 +2026-07-04-drop-image-content-block.zh.md: 683fd1cdb47e3fcd68ff601c0b0ce4b46f8b06d2 diff --git a/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.md b/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.md index df63f2a78f..cdedf4bd5d 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.md +++ b/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.md @@ -2,19 +2,21 @@ Status: implemented +English | [中文](2026-07-04-drop-image-content-block.zh.md) + ## Problem -`ImageBlock` (`packages/llm/llm/src/types.ts`) had no production producer, and every consumer on every path DROPPED it: the deepseek adapter's serializer skipped image blocks (a documented MVP limitation), the pi-ai converter skipped them as unrepresentable, the ACP codec neither advertises image prompt capability nor forwarded image blocks outbound and REJECTS image prompt content inbound, and the compaction estimator charged a flat token constant and rendered `[image]`. An `ImageBlock` constructed then would silently vanish from the wire — the vocabulary advertised a capability no path honored, which is the silent-data-loss shape AGENTS.md's defensive patterns warn against. The only constructors anywhere were tests pinning the skip/drop/estimate branches. +`ImageBlock` (`packages/llm/llm/src/types.ts`) had no production producer, and every consumer on every path DROPPED it: the DeepSeek adapter's serializer skipped image blocks (a documented MVP limitation), the pi-ai converter skipped them as unrepresentable, and the compaction estimator charged a flat token constant and rendered `[image]`. ACP independently rejected image prompt content. An `ImageBlock` constructed then would silently vanish from the provider wire — the vocabulary advertised a capability no path honored, which is the silent-data-loss shape AGENTS.md's defensive patterns warn against. The only constructors anywhere were tests pinning the skip/drop/estimate branches. ## Decision -Remove `ImageBlock`, its map entry, and image-specific branches from adapters, ACP rendering, and compaction. Update the owning vocabulary docs and generated references in the same change. Unknown extension blocks still exercise default branches, and ACP continues to reject inbound image prompt content independently of the harness vocabulary. +Remove `ImageBlock`, its map entry, and image-specific branches from adapters and compaction. Update the owning vocabulary docs and generated references in the same change. Unknown extension blocks still exercise default branches, and ACP continues to reject inbound image prompt content independently of the harness vocabulary. ## Alternatives considered ### Why not keep it? -`ContentBlockMap` can reintroduce images when adapters, ACP, and compaction all support them. Keeping a core type whose only implementation is rejection would advertise an unusable surface; absence gives producers an immediate compile-time failure instead. +`ContentBlockMap` can reintroduce images when adapters and compaction support them. ACP may remain a text-only automation protocol. Keeping a core type whose only implementation is rejection would advertise an unusable surface; absence gives producers an immediate compile-time failure instead. The recorded fallback, had review landed on keeping the slot: keep `ImageBlock` but replace every silent skip with a loud rejection, and document that policy in the vocabulary — the silent drop was the one state with no defender. Review landed on removal; the fallback stands as the documented alternative should the slot ever return ahead of a full feature. @@ -24,4 +26,4 @@ No harness `ImageBlock` is constructed outside Agent Note records. ACP's indepen ## Consequences -Re-adding a core vocabulary type later touches several packages at once — but that coordinated change is the shape a real multimodal feature needs anyway (adapter mapping, ACP advertisement, compaction pricing), and none of it existed to preserve. +Re-adding a core vocabulary type later touches several packages at once — but that coordinated change is the shape a real multimodal feature needs anyway (adapter mapping and compaction pricing), and none of it existed to preserve. diff --git a/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.zh.md b/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.zh.md new file mode 100644 index 0000000000..683fd1cdb4 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 移除 `image` 内容块,直到有路径能真正处理它 + +Status: implemented + +[English](2026-07-04-drop-image-content-block.md) | 中文 + +## 问题 + +`ImageBlock`(`packages/llm/llm/src/types.ts`)没有任何生产环境的生产者,而每条路径上的每个消费方都将其丢弃:DeepSeek 适配器的序列化器跳过 image 块(这是文档中注明的 MVP 限制);pi-ai 转换器因无法表示而跳过;压缩(compaction)估算器对其收取一个固定 token 常量并渲染为 `[image]`。ACP(Agent Client Protocol)独立地拒绝图像提示词内容。此时构造的 `ImageBlock` 会在提供方协议格式(wire format)上静默消失——词汇宣告了一种没有任何路径兑现的能力,这正是 AGENTS.md 防御性模式所警告的静默数据丢失形态。唯一的构造调用出现在测试中,用于覆盖 skip/drop/estimate 分支。 + +## 决策 + +移除 `ImageBlock`、其 map 条目,以及适配器和压缩中的 image 专用分支。在同一个变更中更新所属的词汇文档与生成的引用。未知扩展块仍然覆盖默认分支,ACP 继续独立于 harness 词汇拒绝入站的图像提示词内容。 + +## 曾考虑的替代方案 + +### 为什么不保留? + +当适配器和压缩支持 image 时,`ContentBlockMap` 可以重新引入。ACP 可以继续作为纯文本的自动化协议。保留一个唯一实现就是拒绝的核心类型,等于宣告一个不可用的对外服务接口;移除后,生产者会立即得到编译期错误。 + +评审中记录的回退方案(假如评审决定保留该槽位):保留 `ImageBlock`,但将所有静默跳过替换为显式拒绝,并在词汇文档中记录该策略——静默丢弃是唯一没有辩护者的状态。评审最终决定移除;此回退方案作为文档化的替代方案保留,以备该槽位在完整功能就绪之前回归。 + +## 验证 + +除 Agent Note(agent 决策记录)之外,没有任何地方构造 harness `ImageBlock`。ACP 独立的入站图像拒绝路径仍有测试;适配器、codec 和压缩的默认分支则使用插件定义的块类型覆盖。 + +## 后果 + +日后重新添加核心词汇类型需要同时改动多个包(package)——但这种协调变更本就是真正的多模态功能所需的形态(适配器映射与压缩定价),而当前并不存在需要保留的实现。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.i18n.yaml new file mode 100644 index 0000000000..4d018139c5 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-drop-inert-request-knobs.md: 06fa6c1c539f9ff0cfabf76bc41c53800bd46c8c +2026-07-04-drop-inert-request-knobs.zh.md: 42aadde2b279a453fac9444060b8ac34bf9e3c8b diff --git a/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.md b/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.md index dadab43f76..06fa6c1c53 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.md +++ b/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-drop-inert-request-knobs.zh.md) + ## Problem Two request-contract knobs rode the whole request pipeline, yet neither could do anything: diff --git a/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.zh.md b/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.zh.md new file mode 100644 index 0000000000..42aadde2b2 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 移除 `GenerateOptions.prefill` 与 `ToolSchema.strict`——无端到端可用路径的请求旋钮 + +Status: implemented + +[English](2026-07-04-drop-inert-request-knobs.md) | 中文 + +## 问题 + +两个请求契约旋钮贯穿了整条请求流水线,却都无法产生任何效果: + +- **`prefill`**(`packages/llm/llm/src/types.ts`)没有生产级的 setter:agent loop(智能体循环)组装的是 `model`/`system`/`tools`/`messages` 加 `sessionId`/`signal`,上下文压缩(context compaction)后端只追加 `maxTokens`;而且两个适配器都拒绝它:`packages/llm/llm-deepseek/src/serialize.ts` 和 `packages/llm/llm-pi-ai/src/adapter.ts` 各自在 `prefill` 非 undefined 时抛出 `LlmError('UNSUPPORTED')`。该字段的全部可观测行为就是两个 throw,各由一条适配器测试固定。DeepSeek 的 chat-prefix completion 是一个 Beta 功能,运行在两个适配器都未指向的 base URL 上。 +- **`strict`**(`ToolSchema`,同一文件)穿过了 `DefineToolOptions`/`defineTool`(`packages/core/tools/src/schema.ts`)、注册表的 `schemas()` 允许列表(`packages/core/tools/src/index.ts`)、deepseek 协议格式(wire format)映射(`packages/llm/llm-deepseek/src/serialize.ts`,其 wire-type 注释记录了 strict 模式需要适配器未使用的 `/beta` base URL)、`packages/llm/llm-pi-ai/src/adapter.ts` 中的逐工具 payload 修补逻辑,以及 tool-catalog 渲染器(`scripts/gen-tool-catalog.ts`)中的条件 `Strict:` 行。没有任何已发布的工具设置过它——在所有 `tool-*` 包的 src 和 `examples/` 中执行 `rg` 搜索,`strict:` 的生产者为零;唯一的 setter 出现在 dsh-tools 单元测试中。 + +两个旋钮在适配器间是对称的,因此移除操作将它们从两个孪生适配器中一并剥离——[孪生适配器设计](../architecture/2026-06-13-twin-llm-adapters.md)不受影响。 + +## 决策 + +- 从 `GenerateOptions` 中移除 `prefill`,同时移除两个适配器的 UNSUPPORTED 守卫、固定抛错行为的测试、[core.md](../../../../docs/core-data-structures/core.md) 中的粘贴行,以及记录该拒绝行为的适配器 README 表格行。实操手册中的 UNSUPPORTED 指导([adding-an-llm-adapter.md](../../../../docs/cookbook/adding-an-llm-adapter.md))改为通用表述规则——提供方无法遵守的 `GenerateOptions` 字段应抛出 `LlmError(..., 'UNSUPPORTED')`——而不再以 prefill 为例。[内容块词汇 Agent Note(agent 决策记录)](../architecture/2026-06-11-content-block-vocabulary.md)的后果按照 [implemented/AGENTS.md](../AGENTS.md),将 prefill 记录为由生产者门控,而不是已有归属。 +- 从 `ToolSchema`、`DefineToolOptions`、`defineTool`、`schemas()` 允许列表、deepseek 序列化分支及其 wire-type 字段,以及工具目录渲染器的 `Strict:` 行中移除 `strict`。pi-ai 的 payload 修补逻辑简化为对 pi-ai 自身逐工具 strict 默认值的无条件清除(pi-ai 在每个序列化的工具上打 `strict: false`;手写的孪生适配器不发送此字段,因此清除逻辑为保持协议格式对等而保留,由其序列化器测试固定)。setter 测试和 core.md 粘贴行已移除;`GenerateOptions` 与 `ToolSchema` 在 `scripts/type-equiv.manifest.json` 中保留各自的行,因为两个类型只是少了一个字段,本身仍然存在。 + +本 Agent Note 刻意不触及 `temperature`、`stop` 或 `maxTokens`:两个适配器都会端到端遵守它们,而且它们自然是 `agent/request` 上修改请求的钩子插件首批目标。 + +## 曾考虑的替代方案 + +### 为什么不保留? + +「显式的 UNSUPPORTED throw 是诚实的契约行为」——但一个在两个孪生适配器中唯一的实现就是拒绝的旋钮,什么也没承诺;删除它反而升级了失败模式:意外的 setter 变成编译错误而非运行时 throw。「Strict schema 遵循是官方文档记载的提供方功能,且管道完整」——但一个旋钮在有已发布的工具设置它并且有端点兑现它之前,不构成产品表面;今天两者都不成立。它们各自随首个真实 producer 回归:`prefill` 随实现了 chat-prefix completion 的适配器(以及对不支持该功能的适配器的明确策略)一起回来;`strict` 随需要它的工具和 beta 端点方案一起回来。 + +## 验证 + +`rg prefill` 只返回 Agent Note 记录(本文及[内容块词汇 Agent Note](../architecture/2026-06-11-content-block-vocabulary.md)中由生产者门控的后果);限定在工具 schema 范围内的 `rg strict` 只返回本 Agent Note、保留下来的 pi-ai 清理逻辑,以及 `strictEqual` 等无关正文。两个适配器的契约测试都能在没有守卫的情况下通过,pi-ai 修正仍会清理库的 strict 默认值——其 serializer 测试固定了线协议一致性。 + +## 后果 + +已发布的钩子桥接不设置任何请求字段,而请求变更插件(`agent/request` waterfall(瀑布式事件)监听器)使用的是 `temperature`/`stop`(保留且可用),而非适配器拒绝的字段。如果 chat-prefix completion 或 strict 模式成为产品功能,重新添加将随适配器/端点工作一起落地,届时契约能说明实际发生了什么,而不是「所有人都 throw」。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.i18n.yaml new file mode 100644 index 0000000000..2845b37a05 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-drop-unconsumed-web-observation-surface.md: 5b1cb1307c63ef7c298200ee1655119026b9ebf5 +2026-07-04-drop-unconsumed-web-observation-surface.zh.md: c4351c7e66d00f47e1bf9ed117c5f7b043045808 diff --git a/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md b/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md index 80faa2ac07..5b1cb1307c 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md +++ b/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-drop-unconsumed-web-observation-surface.zh.md) + ## Problem `WebService` exposes an observation surface no production code observes: diff --git a/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.zh.md b/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.zh.md new file mode 100644 index 0000000000..c4351c7e66 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.zh.md @@ -0,0 +1,34 @@ +# Agent Note: 移除未被消费的 web 观测接口——`providers-change` 事件与 status 方法 + +Status: implemented + +[English](2026-07-04-drop-unconsumed-web-observation-surface.md) | 中文 + +## 问题 + +`WebService` 暴露了一组没有任何生产代码观测的观测接口: + +- **`web/providers-change`**(`packages/web/web/src/index.ts`)在每次提供方注册和 dispose(资源释放)时声明并发出,且每个注册 effect 的回滚 yield 被刻意排在 emit 之前,唯一目的是让抛出异常的 change listener 能回退注册。在该包自身的两个单元测试之外没有任何 listener(其中一个测试的存在仅仅是为了固定那个回滚顺序)。 +- **`searchStatus()` / `fetchStatus()` 与 `WebCapabilityStatus` 联合类型**(同一包)没有生产调用方:`dsh-tool-web` 直接通过 `ctx.web.search()`/`fetch()` 执行,并把不可用性呈现为 seam 在执行时抛出的结构化 `WebError` code(`packages/web/tool-web/src/search.ts`、`packages/web/tool-web/src/fetch.ts`);唯一的 status 调用方是 web 包自己的测试。`packages/web/tool-web/README.md` 和 [architecture.md](../../../../docs/architecture.md) 中的正文声称工具“只读取聚合的 `searchStatus()`/`fetchStatus()`”——这种漂移之所以存续,只是因为没有机制对照调用位置检查正文。 + +seam 自身的设计使这两个接口天然没有消费方:工具注册跟随产品 ENABLEMENT 而非提供方可用性(`packages/web/tool-web/src/index.ts`),提供方选择在执行时解析且从不缓存——因此没有需要失效的缓存、没有需要重算的注册集合、也没有调用方需要一个有别于「执行并路由结构化错误」的可用性探测。HMR(热模块替换)清理由 effect disposer 自身承载。 + +这与[删除无人消费的 `llm/adapter-change` 事件](2026-06-20-drop-unconsumed-llm-adapter-change-event.md)相呼应;后者从 `LlmService` 移除了相同的通知形状、相同的 emit 前回滚机制和相同的监听器抛错测试。该 Agent Note(agent 决策记录)的保留/删除标准是:为可能面向用户的工具列表消费方保留 `tools/change`,删除启动时后端注册表信号。按这一标准,web 提供方注册表明确属于删除一侧;status 方法则是把同一判断应用于拉取表面,而非推送表面。 + +## 决策 + +移除注册表变更事件、聚合 status 方法与类型,以及它们的专属测试。提供方私有的 status 保留用于执行时选择。面向调用方的覆盖率现在断言成功执行或结构化的选择错误,web 文档描述该按需调用契约。 + +## 曾考虑的替代方案 + +### 为什么不保留? + +web seam Agent Note 刻意规定了两者——事件作为最小 HMR 可见性信号,status 方法作为工具的聚合诊断——未来也可以设想提供方状态面板。但同一 Agent Note 的其他选择让它们失去了生存条件:调用时派生选择和基于启用状态的注册,使任何消费方都不可能需要其中任一项;已发布工具展示了真实模式(执行并路由结构化错误);发生漂移的 README 句子则表明承诺中的消费方从未出现。按照 AGENTS.md 所述“Agent Note 是提案,而非绝对真理”,代码后来证明提案中的这些部分超出了需要;未来的观察者应根据真实消费方的形状,重新引入它实际消费的最小信号或查询。 + +## 验证 + +除 Agent Note 历史外,不再存在 `providers-change`、`searchStatus`、`fetchStatus` 或 `WebCapabilityStatus` 拼写;目录保持新鲜(`verify-cordis-catalog` 为绿色);注册/释放 HMR 安全性测试通过执行行为证明清理;tool-web README 和架构段落也描述了工具实际拥有的执行时错误路由契约。 + +## 后果 + +未来若有提供方选择器 UI 或诊断面板需要变更通知或 status 查询,它将重新添加自身所消费的最小接口;相同的判断及其反转条件已记录在 LLM(大语言模型)先例中。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.i18n.yaml new file mode 100644 index 0000000000..12abdeaada --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-fold-stdio-ui-helper.md: b9c4c6cfb7643890a7cf4dcdeb9014d7c7158818 +2026-07-04-fold-stdio-ui-helper.zh.md: d71fc878c603757f7da20aab3e7e219e368e7745 diff --git a/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.md b/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.md index b05dd22357..b9c4c6cfb7 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.md +++ b/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-fold-stdio-ui-helper.zh.md) + The later [redundant-agent removal](2026-07-20-remove-stdio-and-echo-agents.md) supersedes this package-placement decision and removes the folded package, app, and line-oriented surface entirely. ## Problem @@ -20,7 +22,7 @@ The earlier support helper package was removed: its manifest, tsconfig reference ### Why not promote it to `ui/` instead? -Promotion would have resolved the support-vs-product mismatch while keeping the boundary — the right call only if the readline UI were an independently swappable integration or had a second composer, and the consumer census said neither. The structured ACP bridge stays its own package because it is the product protocol surface with its own contract and snapshot tiers; the readline helper is scaffolding for one app's front door. Re-extraction stays cheap pre-release: if a second product app wants the readline UI, split it back out then, with that consumer shaping the package contract. +Promotion would have resolved the support-vs-product mismatch while keeping the boundary — the right call only if the readline UI were an independently swappable integration or had a second composer, and the consumer census said neither. The structured ACP bridge stays its own package because it is an automation protocol surface with its own contract and snapshot tiers; the readline helper is scaffolding for one app's front door. Re-extraction stays cheap pre-release: if a second product app wants the readline UI, split it back out then, with that consumer shaping the package contract. ## Consequences diff --git a/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.zh.md b/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.zh.md new file mode 100644 index 0000000000..d71fc878c6 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.zh.md @@ -0,0 +1,30 @@ +# Agent Note: 将 stdio UI 辅助模块折入 stdio 应用 + +Status: implemented + +[English](2026-07-04-fold-stdio-ui-helper.md) | 中文 + +后来的[冗余 agent(智能体)移除](2026-07-20-remove-stdio-and-echo-agents.md)取代了这项包放置决策,并完整移除合并后的包、应用和面向行的表面。 + +## 问题 + +readline UI 曾是一个完整的包(`packages/support/` 下的 `@deepseek-ai/dsh-ui-stdio`),其唯一的运行时导入方是应用包 `@deepseek-ai/dsh-stdio-demo`。示例通过加载应用来使用 readline UI,从不自行组合该辅助模块;仓库中所有其他引用都是因为包边界存在而存在的机械性或描述性表面:manifest(元数据清单)与 tsconfig 条目、生成的 module-graph 行、依赖图与 README 行,以及命名该包的文档注释。ui 组 README 记录了 support 放置的理由("主要为示例和覆盖率门禁而存在,`ui/` 保留给作为产品交付的界面"),这留下了一个持续的张力:一个已交付的产品应用依赖一个被明确标注为非产品表面的 support 包。 + +这条边界换来的是:包元数据、workspace 与 tsconfig 引用、module-graph 行、README 条目,以及 publint 表面——服务于一个并不可独立替换的辅助模块:stdio 应用的前门集群始终包含 readline UI,且没有其他消费方能有意义地使用它。 + +## 决策 + +当时,该辅助函数移入 `@deepseek-ai/dsh-stdio`,成为终端通道插件。`createStdioChat`、其 `StdioRuntime` 测试 seam 和单元测试随之一同迁移,使 EOF 处理、渲染、释放以及管道/TTY 行为继续受逐文件覆盖率门禁约束,而不会劫持进程全局量。该模块保留应用挂载所消费的具名 `name`/`inject`/`Config`/`apply` 导出形状;当时的 Echo 和 REPL Loader 冒烟证明组合树,插件形状套件则固定显式 `unwrapExports` 行为。上方取代本文的移除记录负责当前包和示例状态。 + +早期的支持辅助包已移除:其清单、tsconfig 引用、模块图行和 README 行均已消失,其余文档改为描述包内模块。 + +## 曾考虑的替代方案 + +### 为什么不将其提升到 `ui/` 而是折入? + +提升可以解决 support 与 product 之间的错位,同时保留边界——只有在 readline UI 是一个可独立替换的集成或有第二个组合方时才是正确选择,而消费方普查表明两者皆非。结构化的 ACP(Agent Client Protocol)桥接保留为独立包,因为它是具有自身契约和快照层级的自动化协议表面;readline 辅助模块只是一个应用前门的脚手架。在发布前重新拆分成本很低:如果将来有第二个产品应用需要 readline UI,届时再拆出来,由那个消费方来塑造包契约。 + +## 后果 + +- stdio 应用完整拥有自己的前门;叶子 `cordis.yml` 仍然只加载一个应用包,演示的形态没有变化。 +- 未来如果有独立的终端 UI 需要将该辅助模块作为包使用,届时由那个第二消费方驱动重新引入,而非仓库为假设性的复用保留一条边界。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.i18n.yaml new file mode 100644 index 0000000000..c343b6ff92 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-prune-producerless-vocabulary-variants.md: 34492e6906cd2d795f880310b1bcd120e3953fcf +2026-07-04-prune-producerless-vocabulary-variants.zh.md: a68a8b04fedefed8a2ab92f08baf5e8b3ea90222 diff --git a/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.md b/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.md index aa61e859d2..34492e6906 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.md +++ b/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-prune-producerless-vocabulary-variants.zh.md) + ## Problem The merge-extensible vocabulary maps are designed to grow by declaration merging, and the codebase already states the admission policy on `TurnEndReasonMap` (`packages/core/session/src/types.ts`): a variant like `refusal` is "deliberately omitted until" an adapter or loop first emits it. Three declared vocabulary items violated that policy — each had no producer and no consumer, and two had not even a test: diff --git a/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.zh.md b/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.zh.md new file mode 100644 index 0000000000..a68a8b04fe --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 裁剪无生产者的词汇变体(块缓存提示、`agent` 消息来源、`continuation` 轮次触发器) + +Status: implemented + +[English](2026-07-04-prune-producerless-vocabulary-variants.md) | 中文 + +## 问题 + +可合并扩展的词汇映射表设计上通过声明合并来增长,代码库已在 `TurnEndReasonMap`(`packages/core/session/src/types.ts`)上明确了准入策略:像 `refusal` 这样的变体「在适配器或循环首次发出它之前,有意不纳入」。三个已声明的词汇项违反了该策略——每个都既无生产者也无消费方,其中两个甚至没有测试: + +- **`TextBlock`/`ToolResultBlock` 上的 `CacheHint` 及其 `cache?: CacheHint` 块字段**(`packages/llm/llm/src/types.ts`;图像块曾有第三个此类字段,已随图像块一同移除——参见[删除图像 Agent Note(agent 决策记录)](2026-07-04-drop-image-content-block.md))。任何地方都没有构造带 `cache:` 的块——src、测试和文档粘贴均为空——两个适配器也都不读取 `.cache`:DeepSeek 的提示词缓存是自动的,因此适配器会从响应中映射出 `prompt_cache_hit_tokens`,却从不向请求中发送 hint。这是没有任何提供方能够遵守的 Anthropic 风格 `cache_control` 表面。 +- **`MessageSourceMap.agent`**(`{ kind: 'agent'; agentId: string }`,同一文件)。零个构造点,包括测试在内。它预期的生产者在实现时并未使用它:subagent 后端将父级的提示词发送给子级时不带 `source`,因此记录为 `{ kind: 'user' }`,通用信封渲染器在插值 `source.kind` 时也从未对其做路由。 +- **`TurnTriggerMap.continuation`**(`packages/core/session/src/types.ts`)。agent loop(智能体循环)在结构上不可能发出它——continuation 发生在一个轮次*内部*作为后续步骤,而非作为新轮次——循环只构造 `message` 和 `injection` 触发器。唯一的写入者是一个手工构建的测试 fixture(测试前置数据),它只需要一个任意的非消息触发器(`packages/support/llm-replay/tests/llm-replay.spec.ts`),`injection` 触发器同样满足需求;唯一的生产环境触发器读取方 ACP(Agent Client Protocol)桥接层只过滤 `kind === 'message'`。 + +## 决策 + +`CacheHint`、其 `cache?` 块字段、`agent` 消息来源变体和 `continuation` 轮次触发器变体均已删除:已发布词汇不再携带它们。llm-replay fixture 使用 `injection` 触发器(任何非 `message` 触发器都能满足其用途)。[core.md](../../../../docs/core-data-structures/core.md) 和 [session.md](../../../../docs/core-data-structures/session.md) 中的 type-equiv 粘贴与裁剪后的 map 匹配——两个符号仍保留在 `scripts/type-equiv.manifest.json` 中的行,因为每个 map 都只是少了一个成员而继续存在——并且[内容块词汇 Agent Note](../architecture/2026-06-11-content-block-vocabulary.md)的后果按照 [implemented/AGENTS.md](../AGENTS.md),将 cache hint 记录为由生产者门控,而不是已有归属。 + +每个变体在获得真正的生产者之日回归,这正是映射表设计的增长方式:缓存功能连同传输它的适配器一起重新添加 `cache`;subagent 归属连同打标的后端和路由它的消费方一起重新添加 `agent`;真正启动新轮次的自动续行功能连同发出它的插件一起重新添加 `continuation`。 + +## 曾考虑的替代方案 + +### 为什么不保留它们? + +[内容块词汇 Agent Note](../architecture/2026-06-11-content-block-vocabulary.md)曾把“cache hint……有了归属”列为设计后果,预留槽位也确实能表明意图。但空槽位是每个实现和消费方都必须考虑的契约表面(我的适配器是否必须遵守 `cache`?我的 renderer 是否必须路由 `agent` 来源?),而相邻 map 自身的 JSDoc 已经拒绝“无 emitter 先预留”——`refusal` 和 `max_turn_requests` 被点名为*首次有内容发出它们时*再添加的变体,而不是提前声明。让已经声明但无用的变体遵守同一标准,才能使词汇真正有意义:只要它位于 map 中,就必须有内容生产它。 + +## 验证 + +对 `CacheHint`、`agent` 消息来源拼写和 `continuation` 触发器拼写运行 `rg`,只会返回 Agent Note 记录(本文,以及[删除图像 Agent Note](2026-07-04-drop-image-content-block.md)对图像块自身 `cache` 字段的说明);llm-replay fixture 使用 `injection` 触发器断言相同的重放行为;核心数据结构粘贴和 type-equiv 清单保持同步。 + +## 后果 + +操作行为没有变化——原本就没有内容能够构造这些值。镜像事件移除([边界镜像 Agent Note](2026-06-20-remove-agent-boundary-mirror-events.md)、[流分片 Agent Note](2026-07-02-remove-stream-chunk-mirror.md))只触及瞬态 `agent/*` 事件,从不触及持久词汇,因此不存在冲突。其他位置已经遵守准入策略:`rejected`、`prompt/blocked` 和 `hook/invoked`/`hook/result` 都有实时生产者——本 Agent Note 将同一门槛扩展到缺少生产者的三个变体。图像块自身的 `cache?` 字段归属[删除图像 Agent Note](2026-07-04-drop-image-content-block.md),后者将其与该块一同移除;本 Agent Note 覆盖剩余块类型上的两个字段。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.i18n.yaml new file mode 100644 index 0000000000..e7aabd9dc2 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-prune-write-only-fs-surface.md: 6cfd5d9ab8a2fc6322814d384fba735c06681976 +2026-07-04-prune-write-only-fs-surface.zh.md: cb7494b5e958c8ed86ffa3ba8ffbe82748d1db03 diff --git a/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.md b/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.md index 97652ef50c..6cfd5d9ab8 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.md +++ b/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-prune-write-only-fs-surface.zh.md) + ## Problem The [fs seam split](2026-06-26-fsspec-style-fs-seam.md) moved read routing and policy out of the backend into `dsh-tool-fs` and `dsh-fs-policy`. Four pieces of surface kept the pre-split shape — populated on every call, read by nobody: diff --git a/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.zh.md b/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.zh.md new file mode 100644 index 0000000000..cb7494b5e9 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.zh.md @@ -0,0 +1,32 @@ +# Agent Note: 从 fs seam 中移除只写字段与一个无效的路由旋钮 + +Status: implemented + +[English](2026-07-04-prune-write-only-fs-surface.md) | 中文 + +## 问题 + +[fs seam 拆分](2026-06-26-fsspec-style-fs-seam.md)将读取路由与策略从后端移至 `dsh-tool-fs` 和 `dsh-fs-policy`。有四处接口保留了拆分前的形态——每次调用都填充,却无人读取: + +1. **`dsh-fs-local` 中的 `STREAM_MIN_SIZE` + `FsIoInternals.streamMinSize`**——*在本次变更之前已被「禁止硬编码可调参数」审计移除,该审计将路由阈值改为 `dsh-tool-fs` 的 `readStreamMinSize` 配置;此处记录是为了完整呈现整次清理。* 原始位置(`packages/fs/fs-local/src/fsio.ts`,从 `packages/fs/fs-local/src/index.ts` 重导出):包括 fs-local 自身源码和测试在内,全仓库零读取者。后端没有读取路由——`readWholeText`/`streamWholeText` 是调用方自行选择的两个独立原语——真正的路由常量位于消费方(`packages/fs/tool-fs/src/read.ts`,与 `info.size` 比较)。同一个 10 MiB 事实的两份镜像;后端那份是死代码,且该旋钮的 JSDoc 声称提供一个实际不存在的「read routing」覆盖。 +2. **`FsTarget.inputPath`**(`packages/fs/fs/src/types.ts`):每个后端和每个测试 mock 都必须为这个「仅供诊断」的字段编造一个值,而生产环境零读取者——策略插件和所有错误消息使用的是 `targetKey`/`displayPath`。`listDir` 的生产者暴露了语义上的摇摆:目录子项得到的是裸条目名,这不是任何人的「input」。 +3. **`FsEditOutcome.replacements` + `.replaceAll`**(`packages/fs/fs/src/types.ts`):`replacements` 生产环境零读取者(单匹配策略本身保留——它由后端内部 `FS_AMBIGUOUS_EDIT`/`FS_EDIT_NOT_FOUND` 抛出来强制执行,错误消息保留了内部计数);`replaceAll` 仅被 `packages/fs/tool-fs/src/edit.ts` 中的 `formatEditOutput` 读取——作为工具本身已持有的 `replace_all` 参数的回声。精简后,`FsEditOutcome` 变为 `{ version, before, after }`,与 `FsWriteOutcome` 中真正由后端发现的字段对齐。 +4. **`FileReadOutcome.limit` + `.version`**(`packages/fs/tool-fs/src/read-render.ts`):由读取工具填充,但 `formatReadOutput` 只渲染 `offset`/`lines`/`totalLines`/`truncatedByBytes`,且 `fs/observed` 事件发射直接使用 `info.version` 而非 outcome 的副本。 + +## 决策 + +删除 fs-local 常量、其再导出和 `streamMinSize` 配置项(其余 `FsIoInternals` 配置项确实由原子写入测试使用);从 `FsTarget` 删除 `inputPath`;将 `FsEditOutcome` 收窄为 `{ version, before, after }`,并把解析参数中的 `replaceAll` 传给 `formatEditOutput`;从 `FileReadOutcome` 删除 `limit`/`version`。[filesystem.md](../../../../docs/core-data-structures/filesystem.md) 中的粘贴、`packages/fs/fs/README.md`,以及不得不虚构已删除字段的测试 fake 都随类型一同收窄。 + +## 曾考虑的替代方案 + +### 为什么不保留? + +未来的权限/隔离层可能需要解析前的路径来生成错误文本——但它需要的是*请求*,每个调用点仍然持有请求。「替换了 N 处」可能成为面向模型的文本——这是一个需要时再设计的行为变更,且后端内部的计数为其错误消息而保留。读取页脚可能展示 `limit`——但页脚展示的一切已经可以从 `lines`/`totalLines` 推导。与此同时,每个现有和未来的后端(远程、原生)都必须编造无人消费的协议字段,每个测试 mock 都必须满足它们。 + +## 验证 + +已删除表面不复存在——`dsh-fs-local` 中的 `STREAM_MIN_SIZE`/`streamMinSize`、`FsTarget.inputPath`、`FsEditOutcome.replacements`/`.replaceAll`,以及 `FileReadOutcome.limit`/`.version`——而请求侧 `replaceAll`(`FsEditRequest`)和其他 outcome 类型上的版本字段保持不变;测试 fake 随类型一同收窄。`formatEditOutput` 在两个 `replace_all` 分支中生成的文本都没有变化,因此没有快照预期输出发生改动。 + +## 后果 + +后端不增加新义务,反而卸下了四个无人消费的字段。fs 发现功能(glob/grep 工具)涉及相同的 `dsh-fs` 类型文件——这是文本层面而非设计层面的重叠,可以机械地合并解决。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.i18n.yaml new file mode 100644 index 0000000000..8b6bb07da2 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-remove-agent-steering-mirror.md: 9f7cd5abe968ff216cbd7012163ea1c04dc00599 +2026-07-04-remove-agent-steering-mirror.zh.md: 63f575347d989f288b3129e0a53e5690b85bb4e8 diff --git a/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.md b/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.md index ebfc774792..9f7cd5abe9 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.md +++ b/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-remove-agent-steering-mirror.zh.md) + ## Problem `agent/steering` was the last remaining transient mirror of a durable session event. The loop's steering drain appends the durable `steering/message { turn, content, source }` and, on the very next line, emitted `agent/steering(agent, turn, content, source)` — the identical fact as a fire-and-forget event (`packages/core/agent-loop/src/loop.ts`, `drainSteering`). It had zero production listeners: the only subscriber anywhere was a loop regression test asserting the emit carried `source` — the same fact the durable event already records one line above. diff --git a/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.zh.md b/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.zh.md new file mode 100644 index 0000000000..63f575347d --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 移除 `agent/steering` 镜像 emit + +Status: implemented + +[English](2026-07-04-remove-agent-steering-mirror.md) | 中文 + +## 问题 + +`agent/steering` 是最后一个仍存在的、对持久会话事件的瞬态镜像。agent loop(智能体循环)的 steering(中途引导)drain 逻辑先追加持久事件 `steering/message { turn, content, source }`,紧接着下一行就 emit `agent/steering(agent, turn, content, source)`——同一个事实以 fire-and-forget 事件的形式重复发出(`packages/core/agent-loop/src/loop.ts`,`drainSteering`)。它在生产环境中没有任何监听者:唯一的订阅方是一个 agent loop 回归测试,断言 emit 携带了 `source`——而这同一个事实已经由上一行的持久事件记录。 + +`agent/steering` 以相同的 payload 重复了紧接其前的持久事件 `steering/message`。`agent/queued` 仍保留为纯瞬态信号,因为它在持久化之前触发,覆盖了可能在进入日志前被取消的工作。 + +Steering 承载真实生产流量——钩子 bridge 的轮次延续决策通过 `inbox.steer()` 注入其理由,最终成为由钩子矩阵预期输出固定的持久 `steering/message` 事件——而这些消费方无一例外都观察持久事件。没有任何内容观察镜像。 + +## 决策 + +`agent/steering` 已从 agent 事件分类中移除:包括 `packages/core/agent/src/types.ts` 中的声明(以及其中实时事件 JSDoc 列表对它的提及)、`drainSteering` 中的 emit(当时已无用的 `ctx` 参数也随之移除)、`packages/core/agent/README.md` 中的表格行,以及循环伪代码块(`packages/core/agent-loop/src/loop.ts` 模块文档和 [architecture.md](../../../../docs/architecture.md))中的 emit 行;Cordis 目录重新生成后不再包含它。唯一的回归测试改为在持久 `steering/message` 事件上固定来源保留行为——所固定的事实存在于日志上。 + +三份已实现 Agent Note(agent 决策记录)曾说明保留该事件;按照 [implemented/AGENTS.md](../AGENTS.md),每份记录都已修改并指向本文作为移除记录:包括[边界 Agent Note](2026-06-20-remove-agent-boundary-mirror-events.md) 的保留列表条目、[流分片 Agent Note](2026-07-02-remove-stream-chunk-mirror.md) 的范围条款,以及[事件域语义 Agent Note](../architecture/2026-06-30-event-domain-semantics.md) 的瞬态 emit 枚举。 + +## 曾考虑的替代方案 + +### 为什么不保留? + +“它是控制信号,不是边界”——但该分类的实际区分是镜像/仅实时,而非控制/边界,并且该事件确实是镜像。希望在入队时收到通知的消费方可以使用 `agent/queued`(及其 steering 标记);希望在排空时收到通知的消费方,本质上是在要求获知 `steering/message` 被追加的时刻,而 `session/event` 会交付相同 payload 并附带持久性。遭拒绝的[退役轮次中途 steering Agent Note](../../rejected/simplification/2026-06-20-retire-mid-turn-steering.md)所捍卫的是 steering *功能*——`steer()`、持久事件、强制延续——本次移除不会触及其中任何一项。 + +## 验证 + +`agent/steering` 拼写只存在于 Agent Note 正文中(本 Agent Note、上方三份已修改 Agent Note,以及已冻结的[遭拒绝 steering 功能 Agent Note](../../rejected/simplification/2026-06-20-retire-mid-turn-steering.md),其正文记录了它所否决的提案);目录已重新生成;重新定向的测试在 `steering/message` 上固定来源保留行为。 + +## 后果 + +生产环境中没有需要迁移的监听者,两种瞬态通知需求各有归宿:入队时由 `agent/queued`(带 `steering` flag)承载,drain 时由 `session/event` 在持久事件 `steering/message` 落地时承载。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.i18n.yaml new file mode 100644 index 0000000000..32517c2c50 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-share-app-bin-boot-glue.md: 7a763eba8a229ec5017387edb54657a5c367105b +2026-07-04-share-app-bin-boot-glue.zh.md: d65a6613f7b05cdea0f99529808c992aff4256e9 diff --git a/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.md b/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.md index f054f168a2..7a763eba8a 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.md +++ b/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-share-app-bin-boot-glue.zh.md) + ## Problem The stdio and ACP bins duplicated environment loading, fail-loud handling, entry validation, and boot logic, including subtle Loader failure behavior. Their copies had already drifted and lived in self-executing files excluded from unit coverage, making their helper exports unusable. diff --git a/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.zh.md b/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.zh.md new file mode 100644 index 0000000000..d65a6613f7 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.zh.md @@ -0,0 +1,27 @@ +# Agent Note: 共享应用 bin 的启动胶水代码,而非维护两份副本 + +Status: implemented + +[English](2026-07-04-share-app-bin-boot-glue.md) | 中文 + +## 问题 + +stdio 和 ACP(Agent Client Protocol)两个 bin 各自重复了环境加载、fail-loud 处理、入口校验与启动逻辑,包括微妙的 Loader 失败行为。两份副本已经发生漂移,且位于自执行文件中、被排除在单元测试覆盖率之外,导致其导出的辅助函数无法被复用。 + +## 决策 + +辅助函数只存在一处:[`@deepseek-ai/dsh-app-boot`](../../../../packages/ui/app-boot)(`packages/ui/app-boot`,归入 `ui` 分组,因为 bin 是已发布产物,其运行时依赖本身也必须是已发布的包,而非 `support/`)。包含:`resolveConfigPath`(快照感知,两个 bin 共用的唯一路径解析器)、`loadEnv`、`installFailLoud`、`assertEntriesLoaded` 与 `boot`,每个函数都通过 bin 的诊断前缀参数化,并在其副作用 seam(warn sink、process slice)处支持注入,使单元测试套件能覆盖每个分支——包括 `boot()` 在进程内驱动真实 Loader、使用相对路径 specifier 配置的场景,既覆盖已稳定树的正常路径,也覆盖无 fiber 入口的拒绝路径。该包启用逐文件 100% 覆盖率门禁;Loader 失败的相关知识只有一个归属地。 + +每个 `bin.ts` 都是在共享辅助函数之上加应用特有生命周期的精简自执行组合(ACP bin:重放模式环境变量跳过和 stdin EOF 释放;stdio bin:没有额外逻辑)。这些 bin 仍排除在覆盖率之外且不导出任何内容;已发布产物守卫保持不变——按照“真实入口路径即已发布产物”的防御模式,已构建 bin 冒烟仍在具有 node_modules 形状的临时目录中用纯 node 运行每个 bin(现在也会符号链接 `ui/app-boot`),并继续断言缺失配置时以非零状态退出。[提取示例应用包 Agent Note(agent 决策记录)](../architecture/2026-06-20-extract-example-app-packages.md)中的 bin 归属事实已据此修改。 + +## 曾考虑的替代方案 + +### 为何不保留重复? + +这些 bin 当时被定位为归属相互独立的已发布产物,而新包会带来固定开销(清单、README、tsconfig 引用、publint 表面),与去重的行数相当。但创建 bin 的 Agent Note 从未权衡应用间共享——它把三份示例 `start.ts` 副本合并进 bin 后便止步于此;漂移是已经观察到的事实;覆盖率缺口的理由也独立于去重理由:这是仓库中唯一免受逐文件 100% 门禁约束的非平凡运行时逻辑。记录的后备方案(只将纯逻辑提取到各应用模块)会结束豁免,但会继续让相关知识拥有两个归属。 + +## 后果 + +- 启动胶水代码的变更(新增守卫、修复路径解析)只需落地一次,两个已发布 bin 自动继承;bin 之间不会再次漂移。 +- `dsh-app-boot` 保持轻量依赖(cordis + loader/include 对)——它是启动机制,不是应用表面积。 +- bin 自身的文件几乎是平凡的组合;所有含分支的逻辑都在覆盖率门禁之下。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.i18n.yaml new file mode 100644 index 0000000000..b2c35d276c --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-tighten-hook-protocol-contract.md: a1972ee8ef486982268ba8886b2413f3557061b4 +2026-07-04-tighten-hook-protocol-contract.zh.md: 4917a8f551672f51b0ebc27b1267c7e8e8eb2178 diff --git a/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.md b/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.md index 82830b1366..a1972ee8ef 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.md +++ b/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-tighten-hook-protocol-contract.zh.md) + ## Problem Four pieces of the `dsh-hook-protocol`/bridge contract missed the discipline the [subagent-observe-enrich Agent Note](../feature/2026-06-30-subagent-observe-enrich.md) records — it dropped an `agentType` lifecycle field for lacking a consumer, and these failed the same test: diff --git a/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.zh.md b/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.zh.md new file mode 100644 index 0000000000..4917a8f551 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.zh.md @@ -0,0 +1,32 @@ +# Agent Note: 收紧 hook-protocol 契约——dialect、废弃字段、双重默认值与 lib 拥有的 `hook/result` 语义 + +Status: implemented + +[English](2026-07-04-tighten-hook-protocol-contract.md) | 中文 + +## 问题 + +`dsh-hook-protocol`/bridge 契约中有四部分没有遵守 [subagent observe/enrich Agent Note(agent 决策记录)](../feature/2026-06-30-subagent-observe-enrich.md)记下的准则——后者因缺少消费方而删除 `agentType` 生命周期字段,以下各项没有通过同一检验: + +1. **`HookDialect` 的 `'native'` 变体**(`packages/hooks/hook-protocol/src/types.ts`)没有生产者——bridge 会标记 `'claude'` 和 `'codex'`;所有位置中唯一构造 `'native'` 的是该库自己的单元测试。字段自身的 JSDoc 将 `dialect` 定义为“运行它的 bridge”,而 native 不是 bridge:[拦截 seam Agent Note](../feature/2026-06-30-interception-seams.md) 记载 native 钩子不是一个包,并且“native 插件无需持久钩子日志即可使用类型化 Decision”;旗舰 native 插件实践示例恰好断言了这一点(完全没有 `hook/*` 事件)。 +2. **`HookOutput.suppressOutput`**(同一文件)被 codec 解析后在所有路径上均被丢弃:没有 bridge 分支处理它、没有合并 fold、没有 warn、没有 deferred-list 行——在所有「被解析但未兑现」的同类字段中它是唯一没有明确延期声明的(`updatedInput` → 一条 warn 日志加 [pre-tool-input-rewrite 提案](../../proposed/feature/2026-06-30-pre-tool-input-rewrite.md);`systemMessage` → 一条 warn 日志加 README deferred 行;`continue`/`stopReason` → 一个 `TODO(hook-continue-false)` 锚点加 `'stop'` decision 记录)。从结构上看根本无物可抑制:钩子 stdout 从不进入任何 transcript(文本记录)(上下文仅通过 `additionalContext` 流入;日志只记录 `decision`/`stderrSummary`),因此钩子作者设置 `suppressOutput: true` 得到的是无声的空操作,且无任何警告。 +3. **`defaultTimeoutMs` 在两个 bridge 配置中以浮动字面量双重默认**——schema 的 `.default(600_000)` 加上一个 `?? 600_000` 回退(`packages/hooks/hooks-claude/src/index.ts`、`packages/hooks/hooks-codex/src/index.ts`),一个协议级常量在每个 bridge 中有两个归属地,两个 bridge 可能在共享默认值上悄然分歧。*提案最初的补救措施是彻底删除该旋钮,但被 no-hardcoded-tunables 审计所取代:审计保留了该旋钮作为 bridge 拥有的显式配置(并在旁边新增了 `stderrSummaryMaxChars`);剩下要修的是字面量的归属地。* +4. **`hook/result` 的语义存在于两个 bridge 中(各一份),而非拥有该事件的 lib。** `summarize()`——stderr 截断规则——在 `packages/hooks/hooks-claude/src/index.ts` 与 `packages/hooks/hooks-codex/src/index.ts` 中逐字节相同;decision 字符串规则 `output.decision ?? (output.continue === false ? 'stop' : 'pass')` 同样如此。然而 `dsh-hook-protocol` 声明了 `hook/result`、在文档中将 `stderrSummary` 描述为「已截断」却不拥有截断逻辑,记录了 decision 值却不拥有映射逻辑。如果某个 bridge 漂移(不同的上限、不同的回退),共享持久化事件的语义就会悄然分叉。 + +## 决策 + +`HookDialect` 是封闭的 bridge 集合:`'claude' | 'codex'`;`HookOutput` 移除了不受支持的 `suppressOutput`。`hook/result.durationMs` 保留为持久化的审计计时,仅在快照中做归一化。参考默认值各只存在一处:`DEFAULT_HOOK_TIMEOUT_MS` 与 `DEFAULT_STDERR_SUMMARY_MAX_CHARS`。`HookResultRecord` 与 `appendHookResult` 为两个 bridge 统一拥有 stderr 摘要化和 decision 推导逻辑。`BLOCKING_EXIT_CODE` 为 codec 内部常量。 + +## 曾考虑的替代方案 + +### 为什么不保留它们? + +不受支持的词汇可以在真正有消费方时回归。`durationMs` 保留,因为持久化的审计计时独立于当前是否有读取方而有价值。Bridge 特有的 payload 构造留在各自 bridge 中,而共享持久化事件的归一化属于协议库。 + +## 验证 + +`HookDialect` 仅包含 Claude 和 Codex,`suppressOutput` 在源码、已解析字段文档和归一化逻辑中均不存在。`durationMs` 保留在事件和 fixture(测试前置数据)中,回放时做清洗。`600_000` 和 `500` 两个默认值各只在协议库中出现一次;每个钩子的超时覆盖仍然生效;两个 bridge 的测试套件均验证了由库拥有的 stderr 截断和 decision 规则。 + +## 后果 + +`dialect`、`suppressOutput`、可调参数和语义变更在线协议和预期输出中均不可见。代价是 `dsh-hook-protocol` 和两个 bridge 中的改动——在预发布立场下成本很低,也比让一项持久事件语义的两个副本各自老化更便宜。 diff --git a/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.i18n.yaml new file mode 100644 index 0000000000..08ee0f1c29 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-trim-acp-bridge-unreachable-surface.md: 959cad37f279888fda79b1632c3553ea122803c5 +2026-07-04-trim-acp-bridge-unreachable-surface.zh.md: 9127b7f167c3e5c74cdb99266828c20e79f3cb90 diff --git a/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.md b/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.md index 7d1065d250..959cad37f2 100644 --- a/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.md +++ b/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.md @@ -2,16 +2,20 @@ Status: implemented +English | [中文](2026-07-04-trim-acp-bridge-unreachable-surface.zh.md) + +> The handshake-identity simplification remains current. The generic-card fallback was removed when [ACP became automation-only](2026-07-23-acp-automation-only-protocol.md); UI transports retain the provider-neutral presentation contract. + ## Problem Two pieces of `dsh-acp` surface were unreachable from any shipped configuration: -1. **`AcpConfig.agentName` / `agentVersion`** (`packages/ui/acp/src/index.ts`). The shipped app package hands the bridge only `{ model }` (`packages/examples/acp-demo/src/index.ts`), so no leaf `cordis.yml` — the only production config surface — could set the knobs at all; they were settable solely by direct-mounting the bridge, which only a unit test did. Every snapshot expected output — the hook-matrix scenarios included — pins the schema defaults (`deepseek-harness-acp` / `0.0.1`). The pair also carried a live `TODO(double-default)`: the literals existed twice (schema `.default(...)` plus `??` fallbacks), with the TODO asking to pick one home. +1. **`AcpConfig.agentName` / `agentVersion`** (`packages/acp/acp/src/index.ts`). The shipped app package hands the bridge only its agent target (`packages/examples/acp-demo/src/index.ts`), so no leaf `cordis.yml` — the only production config surface — could set the knobs at all; they were settable solely by direct-mounting the bridge, which only a unit test did. Every snapshot expected output — the hook-matrix scenarios included — pins the schema defaults (`deepseek-harness-acp` / `0.0.1`). The pair also carried a live `TODO(double-default)`: the literals existed twice (schema `.default(...)` plus `??` fallbacks), with the TODO asking to pick one home. 2. **The `toolKindFor` name heuristic** (same file) special-cased `bash*`/`read*`/`write`/`edit*` tool names in the generic-fallback path. Since the [render-intent union](../architecture/2026-07-02-tool-render-intent-union.md), every first-party tool those arms matched ships its own `presentCall` carrying its kind, and the presenter-less production tools (`subagent`, `subagent_fork`) fell through to `other` anyway. The arms were production-reachable only when a tool declined to present its own call — a `presentCall` that THROWS (the containment fallback), or model arguments that fail the tool's schema so `defineTool`'s `presentCall` wrapper returns `undefined` (e.g. a `bash` call missing the required `description`) — and the bridge's own module doc states the design rule the heuristic violated: "the bridge never special-cases tool names". ## Decision -Hardcode the existing handshake identity `{ name: 'deepseek-harness-acp', version: '0.0.1' }` at initialization and remove the unreachable config fields and duplicate defaults. Replace `toolKindFor` with neutral `'other'` at both presenter fallbacks. Normal first-party presentations are unchanged; malformed or failed presentations now render an honest generic card instead of inferring a kind from the tool name. Initialize tests and snapshots pin the handshake; only the malformed calls in `hook-codex-posttool-block` change fallback card kind. +Hardcode the existing handshake identity `{ name: 'deepseek-harness-acp', version: '0.0.1' }` at initialization and remove the unreachable config fields and duplicate defaults. The original implementation also replaced `toolKindFor` with neutral `'other'` at both presenter fallbacks; ACP no longer projects tool cards, so that fallback has left the transport entirely. Initialize tests and snapshots pin the handshake. ## Alternatives considered @@ -21,4 +25,4 @@ Branding can return when the app package exposes it to deployments. Inferring pr ## Consequences -Nothing beyond the fallback rendering trade described above — degenerate paths whose neutral card is more diagnosable than an inferred first-party one. +The bridge exposes no branding knobs. UI transports own generic presentation fallback without tool-name inference, while ACP carries no tool-card surface. diff --git a/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.zh.md b/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.zh.md new file mode 100644 index 0000000000..9127b7f167 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.zh.md @@ -0,0 +1,28 @@ +# Agent Note: 裁剪不可达的 ACP 桥接层表面——品牌配置项与 kind 嗅探回退 + +Status: implemented + +[English](2026-07-04-trim-acp-bridge-unreachable-surface.md) | 中文 + +> 握手标识简化仍然有效。通用卡片回退已随 [ACP 转为仅面向自动化](2026-07-23-acp-automation-only-protocol.md)一并移除;UI 传输层保留提供方无关的展示契约。 + +## 问题 + +`dsh-acp` 有两处对外表面在任何已交付的配置中都不可达: + +1. **`AcpConfig.agentName` / `agentVersion`**(`packages/acp/acp/src/index.ts`)。已发布应用包只向 bridge 传递其 agent 的提供方/模型目标(`packages/examples/acp-demo/src/index.ts`),因此没有任何叶子 `cordis.yml`——唯一的生产配置表面——能够设置这些配置项;只有直接挂载 bridge 才能设置它们,而这种做法只存在于一个单元测试中。每份快照预期输出——包括钩子矩阵场景——都固定 schema 默认值(`deepseek-harness-acp` / `0.0.1`)。这对配置项还带有一个尚未解决的 `TODO(double-default)`:字面量存在两次(schema `.default(...)` 加 `??` 后备值),TODO 要求为它们选择一个归属。 +2. **`toolKindFor` 名称启发式**(同一文件)在通用回退路径中对 `bash*`/`read*`/`write`/`edit*` 工具名做了特殊处理。自[render-intent 联合类型](../architecture/2026-07-02-tool-render-intent-union.md)以来,这些分支匹配到的每个第一方工具都自带 `presentCall` 并携带其 kind,而没有 presenter 的生产工具(`subagent`、`subagent_fork`)本来就落入 `other`。这些分支只有在工具拒绝自行呈现调用时才在生产中可达:`presentCall` 抛出异常(容错回退),或模型参数未通过工具 schema 导致 `defineTool` 的 `presentCall` 包装层返回 `undefined`(例如 `bash` 调用缺少必需的 `description`)。而桥接层自身的模块文档明确声明了该启发式所违反的设计规则:"桥接层绝不对工具名做特殊处理"。 + +## 决策 + +在初始化时硬编码现有的握手标识 `{ name: 'deepseek-harness-acp', version: '0.0.1' }`,移除不可达的配置字段与重复默认值。最初的实现还在两个 presenter 回退处将 `toolKindFor` 替换为中性的 `'other'`;ACP 不再投影工具卡片,因此该回退已完全离开传输层。初始化测试和快照固定握手标识。 + +## 曾考虑的替代方案 + +### 为什么不保留? + +品牌配置可以在 app 包将其暴露给部署环境时再回来。从未知工具名推断呈现方式违反了 render-intent 契约;中性回退卡片还能为格式错误的调用和损坏的 presenter 保留原始输入。 + +## 后果 + +桥接层不暴露品牌配置项。UI 传输层拥有不做工具名推断的通用展示回退,而 ACP 不承载任何工具卡片表面。 diff --git a/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.i18n.yaml new file mode 100644 index 0000000000..6c3e5859e7 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-12-drop-unconsumed-skill-provider-events.md: b0ed7585882328b6abdcf57974200053d9c26048 +2026-07-12-drop-unconsumed-skill-provider-events.zh.md: fd380b2c0421abfc3032b88b550b4a3e8b88bf38 diff --git a/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.md b/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.md index a719e20f1e..b0ed758588 100644 --- a/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.md +++ b/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-12-drop-unconsumed-skill-provider-events.zh.md) + ## Problem Two skill-registry notifications are produced but have no production listener. The generated producer/consumer matrix and exact event-name searches find only declarations, emit sites, tests, generated catalogs, and prose for `skill/provider-added` and `skill/provider-removed`. diff --git a/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.zh.md b/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.zh.md new file mode 100644 index 0000000000..fd380b2c04 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 移除无消费方的 skill 提供方事件 + +Status: implemented + +[English](2026-07-12-drop-unconsumed-skill-provider-events.md) | 中文 + +## 问题 + +skill(技能)注册表产出两个通知事件,但没有生产环境的监听方。生成的生产者/消费方矩阵以及对事件名的精确搜索表明,`skill/provider-added` 与 `skill/provider-removed` 仅出现在声明、emit 站点、测试、生成的 catalog 和行文中。 + +skill 发现按需读取当前的提供方映射表,提供方注册时同步清除已完成的 catalog,而 await 后的版本检查阻止了陈旧的发现结果进入缓存。没有兄弟插件通过这些事件等待 skill 提供方——与之形成对比的是活跃的 `subagent/provider-added` 消费方,它容忍兄弟并发加载。 + +`tools/change` 与 `system-prompt/change` 明确不在本提案范围内。既有的简化决策将它们保留为面向实时工具和提示词 UI 的有意观测点,且自引用的已挂载插件已在使用 `tools/change`。本提案同样不改动 `subagent/provider-added`/`removed`,因为 `tool-subagent` 有生产环境的生命周期消费方。 + +## 决策 + +skill 注册表不再声明和 emit 提供方成员变更事件。提供方的注册与 dispose(资源释放)仍为 effect 所有的直接状态变更,同步使已完成的 catalog 失效;查找与发现按需读取当前提供方映射表。测试通过提供方查找和收集到的输出来观察清理行为,而非依赖生命周期通知。 + +生成式事件目录、API 目录和生产者/消费方矩阵均不再包含已删除通知。skill system Agent Note(agent 决策记录)和包文档改为通过其由 effect 直接拥有的状态与 cache 失效契约描述注册。 + +## 曾考虑的替代方案 + +**为未来插件保留 skill 提供方通知。** 第三方插件可能想观察提供方的可用性,但直接提供方注册与按需查找才是扩展契约;当前没有消费方需要推送信号。如果将来出现兄弟加载竞态,可以像 subagent 注册表那样,引入一个带有该消费方实际所需的身份与就绪语义的通知。 + +## 后果 + +生成的事件矩阵中不再有 `skill/provider-added` 或 `skill/provider-removed` 的行。skill 发现、直接运行时注册、提供方 effect 回滚/dispose、缓存失效与注册表查找清理保持不变;监听方触发的回滚随事件一起消失。`tools/change`、`system-prompt/change` 以及已被消费的 subagent 提供方生命周期事件不受影响。 + +预发布消费方失去 skill 提供方观测点,但仍保留两种贡献 skill 的方式:直接运行时注册与提供方注册。未来若有消费方需要实时的提供方可用性信息,必须新增一个带有其实际所需的身份与就绪语义的专用通知。 diff --git a/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.i18n.yaml new file mode 100644 index 0000000000..1f8a055362 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-12-prune-unused-web-seam-fields.md: c50bf44161579a44b09113fc501f3d67fb5d6855 +2026-07-12-prune-unused-web-seam-fields.zh.md: 401bdd0c812175cffc572e722141d2829a3fc2d5 diff --git a/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.md b/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.md index 68ced83876..c50bf44161 100644 --- a/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.md +++ b/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-12-prune-unused-web-seam-fields.zh.md) + ## Problem The web capability carries request/result/status values that every shipped implementation populates but no production consumer reads. `WebSearchResult.providerId` and `query` and `WebFetchResult.providerId` are result echoes; `tool-web` formats only content/sources/truncation or final URL/status/body/truncation, and no other runtime reads them. Search providers return `WebProviderStatus.reason`, but resolution checks only `available` and intentionally emits a generic unavailable diagnostic. diff --git a/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.zh.md b/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.zh.md new file mode 100644 index 0000000000..401bdd0c81 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.zh.md @@ -0,0 +1,27 @@ +# Agent Note: 裁剪 web seam 中未使用的字段 + +Status: implemented + +[English](2026-07-12-prune-unused-web-seam-fields.md) | 中文 + +## 问题 + +web 能力携带的 request/result/status 值,虽然每个已交付的实现都会填充,但没有任何生产环境的消费方读取它们。`WebSearchResult.providerId`、`query` 与 `WebFetchResult.providerId` 是结果回显;`tool-web` 只格式化 content/sources/truncation 或最终 URL/status/body/truncation,没有其他运行时读取这些字段。搜索提供方返回 `WebProviderStatus.reason`,但可用性检查只看 `available`,并有意输出一条通用的不可用诊断信息。 + +`WebFetchRequest.timeoutMs` 同样从未被生产调用方设置。`tool-web` 只提供 URL,使用工具定义的 timeout 加 `exec.signal` 作为调用方截止时间,并依赖本地提供方的配置默认值作为兜底。这个未使用的逐请求覆盖迫使 `web-fetch-local` 暴露 `maxTimeoutMs`、对两个 timeout 来源做 clamp,并为没有任何产品路径能选中的优先级规则编写文档和测试。`WebExecContext` 则是另一个单字段包装层:每个调用方分配 `{ signal }`,每个提供方立即解包 `exec?.signal`;不存在第二个执行控制字段。 + +## 决策 + +web seam 移除搜索/抓取结果中的 `providerId` 回显和搜索的 `query` 回显;调用方本身已持有请求和提供方选择信息。提供方以返回布尔值的方法暴露可用性。抓取请求不再有逐请求 timeout 或 `maxTimeoutMs` clamp;本地提供方保留其可配置的默认 timeout,工具保留自身的截止时间。提供方方法直接接收一个可选的 `AbortSignal`,而非单字段的 `WebExecContext` 包装层。 + +所有 web 实现与面向模型的工具使用更精简的契约。接口/实现/消费方的包(package)拆分、提供方选择、来源引用、最终 URL/状态数据、截断报告与安全限制保持不变。 + +## 曾考虑的替代方案 + +**保留自描述结果、逐请求截止时间与可扩展的执行上下文对象。** 结果回显可以帮助通用遥测,请求级 timeout 可以帮助受信的程序化调用方,包装层则为未来的控制字段留出空间。但目前不存在这样的消费方或第二个字段;在每个提供方中携带重复的身份标识、第二套截止时间策略以及包装/解包管道,使当前契约更难实现和解释。如果遥测或逐调用预算控制到来,届时应当定义哪个截止时间优先、在哪里观测提供方身份,以及多个控制字段是否足以证明需要一个上下文对象。 + +## 后果 + +保留下来的每个 web request/result 字段,要么被生产代码消费,要么是执行提供方请求所必需的。工具可见的搜索/抓取输出、提供方回退、中止行为、可配置的 timeout 兜底、截断与引用仍然被覆盖,无需请求级 timeout 优先级分支或执行上下文包装层。 + +预发布阶段的程序化调用方失去了结果来源回显和逐请求的抓取截止时间。提供方仍具备部署级可配置 timeout 并尊重取消信号,因此这次精简移除的是可配置性,而非安全边界。 diff --git a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.i18n.yaml new file mode 100644 index 0000000000..64bea6aec8 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-12-simplify-session-log-representation.md: a40f4013a97a9c940012dbb37d59beb2faf8fb22 +2026-07-12-simplify-session-log-representation.zh.md: a4ecd8c7340affda71d95505ab44910539e36bb9 diff --git a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md index 97a89e5be7..a40f4013a9 100644 --- a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md +++ b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-12-simplify-session-log-representation.zh.md) + ## Problem The session log maintains two representations that cost more machinery than their consumers require: a pseudo-linked surface and custom request-header deltas. diff --git a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.zh.md b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.zh.md new file mode 100644 index 0000000000..a4ecd8c734 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 简化会话日志表示 + +Status: implemented + +[English](2026-07-12-simplify-session-log-representation.md) | 中文 + +## 问题 + +会话日志维护着两种表示,其机制复杂度超出了消费方的实际需求:一个伪链表 surface 和自定义的请求头增量。 + +`SurfaceManager` 同时在数组、seq map 和可变 `prev`/`next` 链接中存储相同顺序。生产代码从不读取任一链接:compact 的工具配对 balance 根据按 surface 顺序缓存的每个切点 balance 作答。替换已经使用 `indexOf`,因此链接并未使其主导操作成为常数时间。使用线性替换查找的 seq 数组具有相同的渐近替换成本,却只有一种表示需要验证。 + +请求头子系统实现了一套自定义的系统/工具增量编解码器和传输决策层,尽管其契约声明增量只是编码优化,而非可重建性要求。在每个 agent loop(智能体循环)实例边界保留初始/恢复的完整快照,然后在该实例的组装头发生变化时写入一条规范的完整 `request/header`,即可保留回放能力,同时删除 `SystemDelta`、`ToolsDelta`、往返回退逻辑以及持久化的 `request/header-delta` 变体。编解码器专属的词汇随编解码器一起消失,并非因为其各分支本身无效。 + +实现保留追加与替换 `sourceEventSeqs`、崩溃修复 provenance,以及所有 `SessionStartSource` 变体,因为这些字段承担审计/拦截职责,当前没有读取方并不能推翻这一点。 + +## 决策 + +`SurfaceManager.nodes` 是由事件序号组成的 `readonly number[]`;公共 `SurfaceNode` 形状、node 链接和 seq-to-node map 均已移除。内部替换 generation 信号保留。session-query 使用的完整 `foldSurface()` 读取会返回相同的数字数组表示和替换元数据,而无需让增量 manager 保留历史。工具配对 balance 和压缩使用事件序号与 surface 位置;由 compact 拥有的每切点 balance cache 不依赖 node 链接。 + +请求头只使用规范的完整快照。初始与恢复锚点即使没有变化也仍是完整快照;实例内变化会追加另一个完整 `request/header`,reason 为 `change`。delta 事件、codec 类型、diff/apply 辅助函数,以及仅供 codec 使用的 `fallback` reason 均已移除。请求重建选择最新快照。 + +`SESSION_FORMAT_VERSION` 仍固定为 `0`,因此 seed、追加和持久化加载验证会显式拒绝旧 v0 `request/header-delta` 事件,以及携带已删除 `fallback` reason 的完整快照。不存在兼容性 fold 或迁移。JSONL 与 SQLite 测试固定了这一响亮失败边界;ACP(Agent Client Protocol)快照 harness 则把合法的会话中途变更表示为完整固定请求头和完整可读提示词。 + +## 曾考虑的替代方案 + +**保留链表节点和紧凑增量以备未来扩展。** 链接可能有助于未来的游标 API,增量在大型工具 schema 仅有少量变化时可以缩减日志。但没有已发布的游标使用这些链接,而完整快照以磁盘空间换取了显著更简单的正确性。如果头部体积确实成为问题,可以基于真实 trace 设计压缩方案或经过度量的规范增量方案。 + +## 验证 + +单元覆盖率固定有序 surface 的追加/替换行为、工具配对、压缩、完整请求头 fold/记录、请求重建和开发不变量。Seed 验证以及 JSONL、SQLite 加载测试会在重放前拒绝旧事件。无密钥 ACP 套件以新形状覆盖记录、刷新、重放、变化请求头固定,以及沙箱模式切换 fixture(测试前置数据)。 + +## 后果 + +完整请求头会增加日志体积,线性替换查找在极大 surface 上也可能较慢。由于先前实现调用 `indexOf`,替换原本就是线性的;benchmark 推迟到真实 trace 表明更简单的数组成为瓶颈时再进行。格式版本仍为 `0`,因此显式拒绝旧事件是预发布格式边界的永久组成部分。作为交换,surface 顺序和请求头状态现在各自只有一种表示,删除了链接维护、map、codec 分支、往返 fallback 和感知 delta 的快照规范化。 diff --git a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.i18n.yaml index 232fec495b..7b529ad317 100644 --- a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.i18n.yaml +++ b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.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 -2026-07-20-retire-readline-front-door.md: 7ebcfdc246bdf6971418609c61acbd4019aa90cb -2026-07-20-retire-readline-front-door.zh.md: cf4d03594ed3a0cf31bed96eb2133bd37959084a +2026-07-20-retire-readline-front-door.md: 166e9ca17989ff14f9c3f38cd9650387581b0f78 +2026-07-20-retire-readline-front-door.zh.md: 8c2568f60c3a12fb16a9ef4fe1775e875966a49a diff --git a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md index 7ebcfdc246..166e9ca179 100644 --- a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md +++ b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md @@ -32,7 +32,7 @@ Pipes remain the default test medium. PTY-driven subprocess tests are sanctioned ## Accepted losses - **Piped multi-turn in one process** — the readline channel could script several turns over stdin; the one-shot bin runs one task per process. Multi-turn continuity is covered by `RESUME_SESSION_ID`/resume e2es and the TUI's scripted PTY conversation. -- **Non-TTY `ask_user_question`** — the readline provider was the only non-TTY terminal implementation of `ctx.userInteraction`. A headless run whose model calls `ask_user_question` now fails that tool call (no provider); the ACP bridge remains the non-terminal provider. A future headless deployment that needs it composes its own provider. +- **Non-TTY `ask_user_question`** — the readline provider was the only non-TTY terminal implementation of `ctx.userInteraction`. A headless or ACP automation run whose model calls `ask_user_question` fails that tool call unless its composition supplies a provider; Web owns the shipped non-terminal provider. ## Alternatives considered diff --git a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md index cf4d03594e..8c2568f60c 100644 --- a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md +++ b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md @@ -32,7 +32,7 @@ Status: implemented ## 接受的损失 - **单进程内的管道多轮对话**——readline 通道可以通过 stdin 脚本化多个轮次;单次任务 bin 每个进程只运行一个任务。多轮连续性由 `RESUME_SESSION_ID`/resume e2e 和 TUI 的脚本化 PTY 对话覆盖。 -- **非 TTY 的 `ask_user_question`**——readline 提供方是 `ctx.userInteraction` 唯一的非 TTY 终端实现。模型调用 `ask_user_question` 的 headless 运行现在会让该工具调用失败(没有提供方);ACP 桥接仍是非终端提供方。未来需要它的 headless 部署自行组合提供方。 +- **非 TTY 的 `ask_user_question`**——readline 提供方是 `ctx.userInteraction` 唯一的非 TTY 终端实现。模型调用 `ask_user_question` 的 headless 或 ACP 自动化运行会让该工具调用失败,除非其组合提供相应的 provider;Web 拥有已交付的非终端 provider。 ## 曾考虑的替代方案 diff --git a/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.i18n.yaml index c6b8ad0680..d0c69e6c43 100644 --- a/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.i18n.yaml +++ b/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.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 -2026-07-22-plan-specific-collaboration-state.md: 2fc163213ca0ee1de5633e4d7db14a814b2f7bb2 -2026-07-22-plan-specific-collaboration-state.zh.md: 811f657bf31c96dde88e400fc25fe2fe6df1f157 +2026-07-22-plan-specific-collaboration-state.md: d6b606d2235b5dbcb7e1882dd34e8965799c1199 +2026-07-22-plan-specific-collaboration-state.zh.md: c0dc22f6ec296a293681b78cebe7cc05f49f774b diff --git a/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.md b/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.md index 2fc163213c..d6b606d223 100644 --- a/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.md +++ b/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.md @@ -8,7 +8,7 @@ English | [中文](2026-07-22-plan-specific-collaboration-state.zh.md) The first plan-mode implementation introduced a generic named-mode registry even though the product shipped only `plan`. `ModeConfig.modes`, definition-name validation, `ctx.modes.list()`, retired-definition fallback, and a synthetic `review` mode in tests existed only to support hypothetical future collaboration modes. The production-specific behavior—plan guidance, `/plan`, and `exit_plan_mode`—still lived in the same package, so the generic API did not isolate a reusable mechanism from plan policy. -The word “mode” also spans unrelated domains. Sandbox mode is an enforcing policy owned by `ctx.sandboxPolicy` and logged as `sandbox/mode`; plan mode is a collaboration stance that contributes guidance and a reviewed exit. Treating both as instances of one named-mode abstraction would obscure their independent ownership. ACP's protocol happens to expose a generic mode picker, but that is an adapter vocabulary rather than evidence that the harness needs a generic mode domain. +The word “mode” also spans unrelated domains. Sandbox mode is an enforcing policy owned by `ctx.sandboxPolicy` and logged as `sandbox/mode`; plan mode is a collaboration stance that contributes guidance and a reviewed exit. Treating both as instances of one named-mode abstraction would obscure their independent ownership. A transport's generic vocabulary is not evidence that the harness needs a generic mode domain. ## Decision @@ -16,7 +16,7 @@ Plan mode owns a plan-specific product package: `@deepseek-ai/dsh-plan-mode` at Configuration is exactly `{ section: string }`. The package registers the fixed `plan:policy` section, `/plan [message]`, the exact `/plan off` direct-exit form, and `exit_plan_mode` itself. Bare `/plan` selects active; another non-empty argument selects it first and then sends the trimmed text through `agent.steer()`, making the text an ordinary logged user message in the affected step. `/plan off` selects inactive without model input and can cancel an entry that is still pending at the boundary. The exit tool remains registered while plan mode is inactive so the request tool catalog stays stable. -ACP keeps its protocol-level `default` and `plan` ids. The bridge maps those two ids to the boolean service, advertises only that fixed pair, rejects every other id at the adapter boundary, and maps committed `plan/mode` events back to `current_mode_update`. The protocol remains generic without forcing genericity into the product domain. +Human-facing compositions own plan selection and review. This note originally kept ACP's protocol-level `default`/`plan` picker as an adapter over the boolean service; [ACP as an automation-only protocol](2026-07-23-acp-automation-only-protocol.md) supersedes that wire projection, so the ACP composition now mounts neither plan mode nor a mode-selection protocol. Sandbox mode and approval policy remain separate enforcement axes. Plan mode neither reads nor writes them, and the simplification introduces no shared base type, registry, or preset abstraction across those concepts. @@ -33,15 +33,14 @@ Sandbox mode and approval policy remain separate enforcement axes. Plan mode nei **Fold sandbox mode into the same service.** Rejected because collaboration guidance and execution confinement have different owners, lifecycle semantics, and consumers. Their shared English noun is not a domain relationship. -**Let ACP own plan state.** Rejected because TUI, resume, fork, prompt assembly, and the exit tool need the same logged fact independently of ACP. ACP owns only the wire projection. +**Let one presentation transport own plan state.** Rejected because TUI, Web, resume, fork, prompt assembly, and the exit tool need the same logged fact independently of any one transport. Presentation adapters own only their projections. ## Verification - Package tests retain boundary ordering, retry, append-failure, HMR disposal, prompt assembly, stable native and Code Mode schemas, review outcomes, and invariant coverage through the boolean service. - Command tests cover bare `/plan`, `/plan <message>`, active `/plan off`, pending-entry cancellation, inactive idempotence, absence of `/mode` and `/review`, and effect-scoped removal. -- ACP tests cover fixed advertisement, both ids, unknown-id rejection, optimistic updates, committed exits, and load replay. - The keyless TUI scenarios enter through `/plan <message>`, leave through `/plan off`, and prove that each committed `plan/mode` precedes the request header it changes, the entry message is logged under plan guidance, and the post-exit request omits that guidance. ## Consequences -The implementation has one vocabulary for one shipped feature. Adding another collaboration stance is now an explicit design decision instead of a config entry, while ACP clients continue to see their standard mode picker. The migration intentionally rejects old `mode/set` logs and old `modes.plan.section` configuration under the repository's pre-release format policy. +The implementation has one vocabulary for one shipped feature. Adding another collaboration stance is an explicit design decision instead of a config entry, and automation clients do not acquire human mode controls through ACP. The migration intentionally rejects old `mode/set` logs and old `modes.plan.section` configuration under the repository's pre-release format policy. diff --git a/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.zh.md b/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.zh.md index 811f657bf3..c0dc22f6ec 100644 --- a/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.zh.md +++ b/.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.zh.md @@ -8,7 +8,7 @@ Status: implemented 产品只交付了 `plan`,首个 plan mode 实现却引入了通用的具名模式注册表。`ModeConfig.modes`、定义名称校验、`ctx.modes.list()`、已退役定义的回退逻辑,以及测试中合成的 `review` 模式,都只为支持假想中的未来协作模式而存在。plan 引导、`/plan` 和 `exit_plan_mode` 这些生产专用行为仍位于同一个包(package)内,因此通用 API 并未将可复用机制与 plan 策略隔离开来。 -「mode」一词还横跨互不相关的领域。沙箱模式是由 `ctx.sandboxPolicy` 拥有、以 `sandbox/mode` 记录日志的强制执行策略;plan mode 则是一种协作方式,会贡献引导内容和经评审的退出路径。若把两者都视为同一个具名模式抽象的实例,就会掩盖二者各自独立的归属关系。ACP(Agent Client Protocol)协议恰好暴露了通用模式选择器,但这只是适配器词汇,并不能证明 harness 需要通用模式领域。 +「mode」一词还横跨互不相关的领域。沙箱模式是由 `ctx.sandboxPolicy` 拥有、以 `sandbox/mode` 记录日志的强制执行策略;plan mode 则是一种协作方式,会贡献引导内容和经评审的退出路径。若把两者都视为同一个具名模式抽象的实例,就会掩盖二者各自独立的归属关系。传输协议的通用词汇并不能证明 harness 需要通用模式领域。 ## 决策 @@ -16,7 +16,7 @@ Plan mode 拥有一个 plan 专用产品包:位于 `packages/plan/plan-mode/` 配置严格为 `{ section: string }`。该包自行注册固定的 `plan:policy` 段、`/plan [message]`、精确匹配的 `/plan off` 主动退出形式,以及 `exit_plan_mode`。不带参数的 `/plan` 选择激活;其他非空参数则先选择激活,再通过 `agent.steer()` 发送去除首尾空白后的文本,使该文本在受影响的步骤中成为一条记录到日志的普通用户消息。`/plan off` 选择未激活,不产生模型输入,并可取消仍待在边界生效的进入选择。即使 plan mode 未激活,退出工具仍保持注册,以确保请求工具目录稳定。 -ACP 保留协议层的 `default` 和 `plan` id。桥接层把这两个 id 映射到布尔服务,只公布这组固定选项,在适配器边界拒绝其他所有 id,并把已提交的 `plan/mode` 事件映射回 `current_mode_update`。协议仍保持通用性,但不会迫使产品领域也采用通用抽象。 +面向人类的组合拥有 plan 选择与评审。本笔记最初把 ACP 协议级的 `default`/`plan` 选择器保留为布尔服务之上的适配器;[ACP 作为仅面向自动化的协议](2026-07-23-acp-automation-only-protocol.md)取代了那个线上投影,因此 ACP 组合现在既不挂载 plan mode,也不提供模式选择协议。 沙箱模式与审批策略仍是彼此独立的强制约束轴。Plan mode 既不读取也不写入二者;此次简化也没有为这些概念引入共享基类型、注册表或预设抽象。 @@ -33,15 +33,14 @@ ACP 保留协议层的 `default` 和 `plan` id。桥接层把这两个 id 映射 **将沙箱模式折叠进同一服务。** 不予采纳,因为协作引导与执行约束有不同的归属方、生命周期语义和消费方。二者的英文名称都含「mode」,不代表存在领域关系。 -**让 ACP 拥有 plan 状态。** 不予采纳,因为 TUI、恢复、fork、提示词组装和退出工具都需要在 ACP 之外独立使用同一项已记录事实。ACP 只拥有协议投影。 +**让一种呈现传输拥有 plan 状态。** 不予采纳,因为 TUI、Web、恢复、fork、提示词组装和退出工具都需要独立于任何单一传输使用同一项已记录事实。呈现适配器只拥有各自的投影。 ## 验证 - 包测试通过布尔服务继续覆盖边界顺序、重试、追加失败、HMR(热模块替换)资源释放、提示词组装、稳定的原生 schema 与 Code Mode schema、评审结果和不变式。 - 命令测试覆盖不带参数的 `/plan`、`/plan <message>`、激活状态下的 `/plan off`、取消待生效的进入选择、未激活状态下的幂等性、不存在 `/mode` 和 `/review`,以及随 effect 作用域移除。 -- ACP 测试覆盖固定模式列表公布、两个 id、未知 id 拒绝、乐观更新、已提交退出和加载回放。 - 无密钥 TUI 场景通过 `/plan <message>` 进入、通过 `/plan off` 退出,并证明每个已提交的 `plan/mode` 都先于其所改变的请求头,进入消息在 plan 引导下记录到日志,且退出后的请求不含该引导。 ## 后果 -该实现只用一套词汇描述一项已交付功能。若要添加另一种协作方式,必须显式作出设计决策,而不能只增加配置项;ACP 客户端仍可看到标准模式选择器。根据仓库的预发布格式策略,本次迁移有意拒绝旧的 `mode/set` 日志与 `modes.plan.section` 配置。 +该实现只用一套词汇描述一项已交付功能。若要添加另一种协作方式,必须显式作出设计决策,而不能只增加配置项;自动化客户端不会通过 ACP 获得面向人类的模式控制。根据仓库的预发布格式策略,本次迁移有意拒绝旧的 `mode/set` 日志与 `modes.plan.section` 配置。 diff --git a/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.i18n.yaml index 72e2341385..3e4286afec 100644 --- a/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.i18n.yaml +++ b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.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 -2026-07-22-tui-titles-from-session-title-service.md: b54b99647230255cf241415f94aa21b2630c44cd -2026-07-22-tui-titles-from-session-title-service.zh.md: 67cc3332f0694887d5af0d71997d140b74669f46 +2026-07-22-tui-titles-from-session-title-service.md: 735c940dbb8a84104ab4320d5c535b41690953d5 +2026-07-22-tui-titles-from-session-title-service.zh.md: 8e7e3ef070cc6518476fe0f53355cb0705e74c6a diff --git a/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.md b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.md index b54b996472..735c940dbb 100644 --- a/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.md +++ b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.md @@ -6,7 +6,7 @@ English | [中文](2026-07-22-tui-titles-from-session-title-service.zh.md) ## Problem -Two model-title implementations coexisted after the tui-staging line merged onto master. The TUI carried its own `autoTitle` feature: a fire-and-forget `ctx.llm.stream` call after the first user message that set the terminal window title via OSC 0, with a one-shot latch, its own prompt, its own 40-character cap, and its own resume re-derivation ([auto-title Agent Note](../feature/2026-07-21-tui-auto-pane-title.md), [default-on Agent Note](../feature/2026-07-21-tui-auto-title-default-on.md)). Master had meanwhile landed [log-backed session titles](../feature/2026-07-21-log-backed-session-titles.md): a `sessionTitle` capability whose accepted revisions are durable `session/title` events, with a deterministic fallback and optional model providers. The TUI already consumed `session/title` for its header subtitle and window title, so a session could be titled twice by different strategies, and the TUI's process-local title was invisible to every other consumer (ACP, resume listings, forks). +Two model-title implementations coexisted after the tui-staging line merged onto master. The TUI carried its own `autoTitle` feature: a fire-and-forget `ctx.llm.stream` call after the first user message that set the terminal window title via OSC 0, with a one-shot latch, its own prompt, its own 40-character cap, and its own resume re-derivation ([auto-title Agent Note](../feature/2026-07-21-tui-auto-pane-title.md), [default-on Agent Note](../feature/2026-07-21-tui-auto-title-default-on.md)). Master had meanwhile landed [log-backed session titles](../feature/2026-07-21-log-backed-session-titles.md): a `sessionTitle` capability whose accepted revisions are durable `session/title` events, with a deterministic fallback and optional model providers. The TUI already consumed `session/title` for its header subtitle and window title, so a session could be titled twice by different strategies, and the TUI's process-local title was invisible to resume listings, forks, and Web consumers. ## Decision diff --git a/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.zh.md b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.zh.md index 67cc3332f0..8e7e3ef070 100644 --- a/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.zh.md +++ b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.zh.md @@ -6,7 +6,7 @@ Status: implemented ## 问题 -tui-staging 分支合入 master 后,两套模型标题实现并存。TUI 自带 `autoTitle` 特性:在首条用户消息后发起一次 fire-and-forget 的 `ctx.llm.stream` 调用,通过 OSC 0 设置终端窗口标题,带有一次性闩锁、自己的提示词、自己的 40 字符截断和自己的恢复重推导([auto-title Agent Note](../feature/2026-07-21-tui-auto-pane-title.md)、[default-on Agent Note](../feature/2026-07-21-tui-auto-title-default-on.md))。而 master 已落地[日志承载的会话标题](../feature/2026-07-21-log-backed-session-titles.md):一个 `sessionTitle` 能力,其被接受的修订是持久的 `session/title` 事件,带确定性回退和可选的模型 provider。TUI 已经消费 `session/title` 作为横幅副标题和窗口标题,于是一个会话可能被两种策略各标题一次,且 TUI 的进程本地标题对其他所有消费者(ACP、恢复列表、fork)不可见。 +tui-staging 分支合入 master 后,两套模型标题实现并存。TUI 自带 `autoTitle` 特性:在首条用户消息后发起一次 fire-and-forget 的 `ctx.llm.stream` 调用,通过 OSC 0 设置终端窗口标题,带有一次性闩锁、自己的提示词、自己的 40 字符截断和自己的恢复重推导([auto-title Agent Note](../feature/2026-07-21-tui-auto-pane-title.md)、[default-on Agent Note](../feature/2026-07-21-tui-auto-title-default-on.md))。而 master 已落地[日志承载的会话标题](../feature/2026-07-21-log-backed-session-titles.md):一个 `sessionTitle` 能力,其被接受的修订是持久的 `session/title` 事件,带确定性回退和可选的模型 provider。TUI 已经消费 `session/title` 作为横幅副标题和窗口标题,于是一个会话可能被两种策略各标题一次,且 TUI 的进程本地标题对恢复列表、fork 和 Web 消费方不可见。 ## 决策 diff --git a/.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.i18n.yaml new file mode 100644 index 0000000000..2901a3b813 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-23-acp-automation-only-protocol.md: 2a92f306065b348764f35e1e63f0d7750a636372 +2026-07-23-acp-automation-only-protocol.zh.md: 5889d668310e3bd63f3934a39d4e5250f83f063d diff --git a/.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md b/.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md new file mode 100644 index 0000000000..2a92f30606 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md @@ -0,0 +1,47 @@ +# Agent Note: ACP as an automation-only protocol + +Status: implemented + +English | [中文](2026-07-23-acp-automation-only-protocol.zh.md) + +## Problem + +The ACP bridge had become a second interactive product UI. It translated durable events into editor cards, terminal metadata, diffs, plans, titles, reasoning, commands, modes, model and permission pickers, session navigation, and human elicitation. Those responsibilities duplicated the TUI and the Web client while coupling an automation transport to UI services, persistence queries, presentation policy, and editor-specific conventions. + +ACP still has one useful role: another agent or automated controller can start a harness process, create an isolated session, send text, receive the committed answer, cancel work, and answer a permission request. The out-of-process ACP subagent backend depends on that standard protocol boundary. + +The snapshot suite complicates removal. Most ACP scenarios exercise the assembled agent backend rather than ACP presentation, so deleting the suite with the editor bridge would discard broad keyless behavioral coverage. + +## Decision + +`@deepseek-ai/dsh-acp` is an automation transport under [`packages/acp/acp`](../../../../packages/acp/acp/README.md), outside the `ui` package group. Its public protocol is intentionally small: version negotiation, fresh text sessions with one in-flight prompt each, committed assistant text updates, per-session cancellation, concurrent sessions, and connection-owned teardown. Prompts carry the spec-required baseline only — text plus resource links flattened to bracketed textual references; the bridge rejects additional directories, MCP servers, beyond-baseline prompt content (image, audio, embedded resources), empty prompts, unknown sessions, and overlapping prompts. + +The bridge emits only committed `assistant/message` text. Reasoning, raw chunks, tool activity, todos, plans, titles, retry markers, terminal metadata, diffs, locations, and resource links remain in the durable session log or in UI-specific transports. It does not provide session load/list/delete, commands, modes, configuration selectors, model switching, plan review, or human elicitation. + +One-shot `session/request_permission` remains. It is a machine policy channel for bridge-owned agents, not a human approval UI: the client chooses allow once, reject once, or cancel, and the bridge never turns that response into a durable grant. [`dsh-subagent-acp`](../../../../packages/subagent/subagent-acp/README.md) uses this channel programmatically. + +The app composition contains the agent spine, persistence, checkpoint policy, and ACP transport. It does not mount command, session-query, session-reference, plan-mode, permission-picker, or user-interaction services for ACP. SDK scaffolding likewise treats `ask_user_question` as TUI-only. + +Disconnect and plugin disposal share one memoized quiescence boundary. Both successful and failed transport closure settle pending prompts as cancelled, dispose every bridge-owned agent, and await loop and session cleanup. A create that loses the close race disposes its unpublished handle. + +## Snapshot boundary + +The ACP snapshot suite still boots the assembled ACP example and retains scenarios that pin backend behavior. Only scenarios driven through deleted UI methods leave the suite; semantic-checkpoint recovery runs through the headless `stream-json` example because ACP no longer loads sessions. + +## Alternatives considered + +**Keep ACP as an editor UI until Web reaches parity.** Rejected because it leaves two interactive contracts to evolve and keeps editor conventions in the automation boundary. + +**Replace ACP with a private subagent RPC.** Rejected because ACP already supplies a typed, interoperable process protocol and is used by the out-of-process subagent backend. + +**Remove machine permission requests with the other interaction features.** Rejected because an automated parent must answer a child agent's one-shot policy decision; this is control flow between agents, not presentation. + +**Delete the ACP snapshot suite or migrate every scenario in this change.** Rejected because most scenarios test the backend and remain valuable, while a full harness migration is an independent testing change. Only scenarios whose driver was a deleted UI method leave this suite. + +## Consequences + +ACP has a narrow contract suitable for agents and automation, while TUI and Web own human interaction and presentation. The package has fewer injected services, dependencies, protocol branches, and lifecycle states, and it no longer claims compatibility as a general editor front door. + +Automation clients receive complete committed text rather than token deltas or structured tool UI. They inspect durable logs or another API when they need reasoning, tool traces, titles, or richer state. Fresh-session-only operation also means callers that need durable browsing or resume use a host API rather than ACP. + +Backend snapshot coverage therefore remains transport-coupled to ACP even though that transport is incidental to the behavior under test. diff --git a/.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.zh.md b/.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.zh.md new file mode 100644 index 0000000000..5889d66831 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.zh.md @@ -0,0 +1,47 @@ +# Agent Note:ACP 作为仅面向自动化的协议 + +Status: implemented + +[English](2026-07-23-acp-automation-only-protocol.md) | 中文 + +## 问题 + +ACP(Agent Client Protocol)桥接层已经变成第二套交互式产品 UI。它将持久事件转换为编辑器卡片、终端元数据、diff、计划、标题、推理、命令、模式、模型和权限选择器、会话导航以及面向人类的询问。这些职责与 TUI 和 Web 客户端重复,同时将自动化传输层与 UI 服务、持久化查询、展示策略和编辑器特定约定耦合在一起。 + +ACP 仍有一个有用的职责:另一个 agent(智能体)或自动化控制器可以启动 harness 进程、创建隔离会话、发送文本、接收已提交的回答、取消工作并回答权限请求。跨进程 ACP subagent 后端依赖这个标准协议边界。 + +快照套件使移除工作更复杂。大多数 ACP 场景测试的是组装后的 agent 后端,而不是 ACP 展示层;如果随编辑器桥接层一起删除整个套件,就会丢失大量无密钥行为覆盖。 + +## 决策 + +`@deepseek-ai/dsh-acp` 是位于 [`packages/acp/acp`](../../../../packages/acp/acp/README.md) 下、独立于 `ui` 包组的自动化传输层。其公开协议特意保持精简:版本协商、全新文本会话(每个会话最多允许一个进行中的提示词)、已提交的助手文本更新、按会话取消、并发会话,以及由连接负责的资源清理。提示词只承载规范要求的基线内容——文本,加上被展平为方括号文本引用的资源链接;桥接层会拒绝附加目录、MCP 服务器、超出基线的提示词内容(图片、音频、内嵌资源)、空提示词、未知会话和重叠提示词。 + +桥接层只发出已提交的 `assistant/message` 文本。推理、原始分片、工具活动、待办事项、计划、标题、重试标记、终端元数据、diff、位置和资源链接仍保留在持久会话日志或 UI 专用传输层中。它不提供会话加载、列出与删除、命令、模式、配置选择器、模型切换、plan 评审或面向人类的询问。 + +保留一次性 `session/request_permission`。它是为桥接层拥有的 agent 提供的机器策略通道,而不是面向人类的审批 UI:客户端可选择允许一次、拒绝一次或取消,桥接层绝不会将该响应转换为持久授权。[`dsh-subagent-acp`](../../../../packages/subagent/subagent-acp/README.md) 会以程序化方式使用该通道。 + +应用组装包含 agent 主干、持久化、检查点策略和 ACP 传输层。它不会为 ACP 挂载命令、会话查询、会话引用、plan mode、权限选择器或用户交互服务。SDK 脚手架同样将 `ask_user_question` 视为 TUI 专属功能。 + +断开连接与插件 dispose(资源释放)共享同一个经记忆化处理的静止边界。传输关闭无论成功还是失败,都会将待处理提示词以已取消状态结算,dispose 每个由桥接层拥有的 agent,并等待循环和会话清理完成。创建流程如果在与关闭的竞态中落败,就会 dispose 其尚未发布的 handle。 + +## 快照边界 + +ACP 快照套件仍会启动组装后的 ACP 示例,并保留用于锁定后端行为的场景。从该套件移出的只有通过已删除的 UI 方法驱动的场景;由于 ACP 不再加载会话,语义检查点恢复通过 headless `stream-json` 示例执行。 + +## 考虑过的替代方案 + +**在 Web 达到同等能力前,继续将 ACP 作为编辑器 UI。** 不予采用,因为这会留下两套需要演进的交互契约,并使编辑器约定继续存在于自动化边界中。 + +**用私有 subagent RPC 替换 ACP。** 不予采用,因为 ACP 已经提供类型化、可互操作的进程协议,并由跨进程 subagent 后端使用。 + +**随其他交互功能一起移除机器权限请求。** 不予采用,因为自动化父 agent 必须回答子 agent 的一次性策略决策;这是 agent 之间的控制流,而不是展示层。 + +**删除 ACP 快照套件,或在本次变更中迁移每个场景。** 不予采用,因为大多数场景测试后端且仍有价值,而完整的 harness 迁移是一项独立的测试变更。只有驱动脚本依赖已删除 UI 方法的场景才离开该套件。 + +## 结果 + +ACP 具有适合 agent 与自动化的精简契约,而 TUI 和 Web 拥有面向人类的交互与展示。该包注入的服务、依赖、协议分支和生命周期状态更少,也不再将自身定位为通用编辑器入口。 + +自动化客户端收到完整的已提交文本,而不是 token 增量或结构化工具 UI。当它们需要推理、工具跟踪信息、标题或更丰富的状态时,需要查看持久日志或其他 API。只支持全新会话也意味着,需要浏览持久会话或恢复会话的调用方必须使用 host API,而不是 ACP。 + +因此,后端快照覆盖仍与 ACP 传输层耦合,尽管对于受测行为而言,该传输层只是附带因素。 diff --git a/.agents/notes/implemented/testing/2026-06-11-property-based-testing.i18n.yaml b/.agents/notes/implemented/testing/2026-06-11-property-based-testing.i18n.yaml new file mode 100644 index 0000000000..e118ff7330 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-11-property-based-testing.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-property-based-testing.md: a1bd4147a26a3d562899310e238096939fc2d01a +2026-06-11-property-based-testing.zh.md: 0e1934a24fcf22442420a664c9824bb74c0fe7f7 diff --git a/.agents/notes/implemented/testing/2026-06-11-property-based-testing.md b/.agents/notes/implemented/testing/2026-06-11-property-based-testing.md index 5109aa1c80..a1bd4147a2 100644 --- a/.agents/notes/implemented/testing/2026-06-11-property-based-testing.md +++ b/.agents/notes/implemented/testing/2026-06-11-property-based-testing.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-11-property-based-testing.zh.md) + > Merges the original proposal and the decision record for one topic. It found a real BlockAssembler duplicate-`block-end` bug on first run. ## Problem diff --git a/.agents/notes/implemented/testing/2026-06-11-property-based-testing.zh.md b/.agents/notes/implemented/testing/2026-06-11-property-based-testing.zh.md new file mode 100644 index 0000000000..0e1934a24f --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-11-property-based-testing.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 对协议形态代码进行基于属性的测试 + +Status: implemented + +[English](2026-06-11-property-based-testing.md) | 中文 + +> 将原始提案与同一主题的决策记录合并为一篇。首次运行即发现了 BlockAssembler 重复 `block-end` 的真实 bug。 + +## 问题 + +基于示例的测试只能固定我们想到的用例。harness 的核心是协议形态的代码:分片流、事件日志、schema 转换、收件箱调度。这些场景的输入空间是组合式的,有趣的 bug 藏在没人写过示例的交错序列中。佐证:一个块组装的排序 bug 曾在 happy path 100% 行覆盖率下存活。逐文件 100% 覆盖率证明每一行都跑过了,但不能证明每种交错都是正确的。 + +## 决策 + +引入 `fast-check`(作为根 devDependency),在每个协议形态的包(package)中编写一个 `tests/properties.spec.ts`。生成器调优为*逼真但对抗性*的输入(而非均匀噪声),`numRuns` 控制在本地套件总耗时远低于约 10 秒。失败时打印可复现的 seed。(原始提案还草拟了一个夜间 CI job,以 100 倍迭代运行;该部分未交付。属性测试套件仅在常规的 `push`/`pull_request` CI 中运行,定时高迭代 job 仍属可能的后续工作。) + +- **dsh-llm / BlockAssembler:** 任意分片流(合法 + 畸形:重复索引、滞后分片、缺少 block-start)。不变式:`blocks()` 计数 ≤ 已见到的不同索引数;重组幂等(`blocks()` 在重复调用间稳定,且 `message().content` 与之一致);`blocks()` 从不抛异常且仅产出合法的 content-block 标签;`finish` 反映最后一个 `finish` 分片,无此类分片时默认为 `{kind:'stop'}`。 +- **dsh-session:** 任意事件日志。不变式:`deriveMessages` 确定性;从 seed 回放结果一致;seq 严格单调递增;非消息事件不影响推导出的历史;推导出的内容与日志解耦。 +- **dsh-tools:** 任意 `ParameterSchemaSpec`。不变式:JSON Schema 的 `required` 等于每一层 `required:true` 的键集;转换对合法声明而言是全函数;**并且与[运行时参数校验](../architecture/2026-06-11-runtime-arg-validation.md)组合验证**——满足 spec 的生成参数通过 `validateArgs`,而定向破坏(删除必填键、顶层非对象)被拒绝。聚焦用例覆盖每种根值类型、恰好一项匹配中的分支重叠与无匹配、显式开放性、原始默认值以及有损 JSON。这封堵了编译器、validator 与 `InferArgs` 之间的漂移风险。 +- **dsh-agent-loop:** 任意发送调度,对接一个永不耗尽的适配器,通过 `agent/status` settle 信号驱动(无挂钟 sleep)。不变式:无消息丢失;轮次编号严格递增;状态转换保持在合法状态机上。 + +## 后果 + +- 生成器质量是价值杠杆——生成器偏向小索引池和短字符串,使碰撞与交错频繁发生。 +- **它已经带来回报:** BlockAssembler 流发现了一个真实 bug——同一索引处重复的 `block-end` 会改写已经完成的块。现已修复(首次关闭优先,与现有迟到项规则一致),并加入专用回归测试。 +- 属性测试因超时而 flake 是一个发现,不应通过重试消除。循环属性测试在设计上是确定性的(通过 `agent/status` settle),因此挂起即为真实缺陷。 +- 属性测试是对示例测试的补充而非替代;示例测试固定特定分支,服务于 100% 覆盖率门禁。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.i18n.yaml b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.i18n.yaml new file mode 100644 index 0000000000..feeadfed91 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-19-acp-snapshot-tests.md: b4cda8f32fe7a84a977bcbdbe5db0671cb9a7083 +2026-06-19-acp-snapshot-tests.zh.md: 5337c3852b524af4e8c556e93ec80084b30a6d0b diff --git a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md index ebc48ba183..b4cda8f32f 100644 --- a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md +++ b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md @@ -2,9 +2,11 @@ Status: implemented +English | [中文](2026-06-19-acp-snapshot-tests.zh.md) + ## Problem -Unit tests do not exercise the complete ACP subprocess transcript, while real-API tests are nondeterministic and key-gated. Editor-facing `session/update` output can therefore regress despite green unit coverage, as the [default-export postmortem](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md) demonstrated. +Unit tests do not exercise the complete assembled-agent subprocess or its ACP automation wire, while real-API tests are nondeterministic and key-gated. Loader wiring, backend behavior, and protocol output can therefore regress despite green unit coverage, as the [default-export postmortem](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md) demonstrated. The blocker for a full-transcript test is the model: the agent's output is driven by a non-deterministic LLM, and a key-gated test that hits the real API on every run is neither deterministic nor CI-runnable. We want the fidelity of a real run with the determinism of a fixture. @@ -50,10 +52,10 @@ Replay uses a `cordis.snapshot.yml` overlay that replaces the real adapter with A snapshot run asserts **two** normalized surfaces, because the harness's external surfaces are distinct: -1. The **stdout transcript** — the framed `session/update` JSON-RPC the editor sees. Catches regressions in the ACP bridge's event→update translation (`streamSessionEventUpdate`). Compared against a committed `stdout.expected.jsonl`. +1. The **stdout transcript** — the framed ACP JSON-RPC responses and committed-message updates an automation client receives. It catches regressions in the transport contract and is compared against a committed `stdout.expected.jsonl`. 2. The **re-persisted session JSONL**, normalized and compared with `session.jsonl`. The same fixture is both replay source and expected log. Prompt text is scrubbed; one scenario per header class pins readable prompt and tool content as described in the [header-pinning Agent Note](2026-07-06-pin-request-header-content-in-one-scenario.md). Override scenarios derive model behavior solely from their sidecar. -The surfaces are complementary: stdout covers bridge projection, while JSONL covers loop, tool, and boundary structure that the projection omits. +The surfaces are complementary: stdout covers the minimal automation wire, while JSONL covers loop, tool, and boundary structure that the wire intentionally omits. Normalization replaces session, cwd, protocol-id, timestamp, path, and process volatility while preserving deterministic sequence numbers. Scenarios constrain real bash use to stable commands. The stdout expected output remains wire-shaped JSONL and every raw line must parse as JSON. Vitest updates only the stdout expected output; normalized session equality never overwrites the replay fixture. @@ -77,6 +79,6 @@ Tool determinism comes from a generated cwd, scrubbed environment, fresh non-log ## Consequences -The new tier adds reviewed per-scenario input, session, stdout, optional override, and optional workspace fixtures. Workspace seeds are copied into the generated cwd for both record and replay. In return the tier provides deterministic keyless transcript coverage through the real Loader and tool composition. The subprocess, input, workspace, normalization, and replay harness can support examples beyond ACP. +The tier adds reviewed per-scenario input, session, stdout, optional override, and optional workspace fixtures. Workspace seeds are copied into the generated cwd for both record and replay. In return the tier provides deterministic keyless coverage through the real Loader and tool composition. Most retained scenarios exercise the assembled backend rather than ACP; the [automation-only ACP decision](../simplification/2026-07-23-acp-automation-only-protocol.md#snapshot-boundary) keeps that corpus here and defers any move to a transport-neutral headless suite as an independent testing change (the suite-level FIXME marks it). -This Agent Note relates to but does not supersede the [proposed determinism Agent Note](../../proposed/testing/2026-06-11-deterministic-and-stress-testing.md): that proposal's "universal replay fixture" re-derives session *message history* after every test (an internal-consistency invariant), whereas snapshot tests pin the *external protocol output*. They are complementary — one guards the event-sourcing invariant, the other guards the editor-facing contract. +This Agent Note relates to but does not supersede the [proposed determinism Agent Note](../../proposed/testing/2026-06-11-deterministic-and-stress-testing.md): that proposal's "universal replay fixture" re-derives session *message history* after every test (an internal-consistency invariant), whereas these snapshots pin assembled behavior plus the external automation output. They are complementary until the backend corpus moves off ACP. diff --git a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.zh.md b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.zh.md new file mode 100644 index 0000000000..5337c3852b --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.zh.md @@ -0,0 +1,84 @@ +# Agent Note: ACP 快照测试——一次录制 / 确定性回放 + +Status: implemented + +[English](2026-06-19-acp-snapshot-tests.md) | 中文 + +## 问题 + +单元测试不会覆盖组装后的完整 agent(智能体)子进程及其 ACP(Agent Client Protocol)自动化线协议,而真实 API 测试不具确定性且受密钥门控。因此,即使单元覆盖率为绿色,Loader 接线、后端行为和协议输出仍可能回归,[默认导出事后分析](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md)已经证明了这一点。 + +全 transcript(文本记录)测试的阻塞因素在于模型:agent 的输出由非确定性的 LLM(大语言模型)驱动,而每次运行都命中真实 API 的密钥门控测试既不确定也无法在 CI 中运行。我们需要真实运行的保真度与 fixture(测试前置数据)的确定性兼得。 + +本 Agent Note(agent 决策记录)记下了新增第三层测试——**快照测试**——的决策,以及让它具备确定性、在 CI 中无需密钥、且维护成本低廉的设计选择。 + +## 决策 + +快照测试会启动真实 ACP 示例,通过确定性脚本驱动其 stdio 协议,并将规范化输出与已提交的预期输出比较。从真实 API 一次记录的会话日志为后续所有模型流提供数据。fixture 就是产品普通的持久化 JSONL。 + +### fixture 即持久化的会话 JSONL + +每个场景的 `session.jsonl` 都从真实运行中采集。`assistant/chunk` 事件复现模型流;工具、消息和边界事件捕获 harness 行为。因此,一份普通会话产物同时充当重放来源和行为预期输出。 + +当场景固定另一种物理存储布局时,其 fixture 会从真实的未打包对应项机械派生。场景测试要求包含每一种预期存储行类型,并在解码后逐事件精确相等;随后,普通重放与日志比较才会证明组合后的进程能够消费并复现该布局。 + +### 回放从日志推导模型脚本 + +`llm-replay` 短路了提供方无关的 `llm/stream` waterfall(瀑布式事件)。`deriveReplayScript()` 按 `(turn, step)` 对已录制的分片分组,每次模型调用服务一组。agent loop(智能体循环)每个步骤发起一次流调用,因此分组精确对应,错误结束分片也无需特殊处理。 + +### 内存中的回放条目遵守完整的 LLM 契约 + +`deriveReplayScript` 产出一组 `ReplayEntry`,即回放监听器按位置服务的内存单元: + +``` +{ kind: 'chunks', chunks: StreamChunk[] } +| { kind: 'throw', chunks: StreamChunk[], message: string, code: string } +| { kind: 'hang' } +``` + +日志推导出分片条目。流开始前的抛出和挂起没有可重建的分片表示,因此这些场景提供 `replay.override.json`。throw 条目可以包含前缀分片以模拟流中途失败。显式覆盖避免了从有损的轮次结束原因推断适配器行为。 + +### 位置式回放,单个在途流 + +回放是位置式的,因此每个场景只允许一个在途模型流。并发会话快照需要按请求键索引的条目。调用顺序变更需要重新录制,fixture 缺失或耗尽时立即报错。 + +### 录制采集日志;无密钥回放需要无提供方的配置 + +记录模式使用真实 `llm-deepseek` 适配器和配置为 `persistenceCompression: 'none'` 的 JSONL 持久化后端运行场景,再把生成的 `.jsonl` 复制到场景目录。显式 raw 模式让已提交重放 fixture 保持逐行可读,而普通部署使用后端的压缩默认值。逐事件追加具有持久性,但 harness 会在采集前优雅关闭子进程(关闭 stdin → `await ctx.dispose()`),以确保最终事件已刷出。`llm-replay` 本身不执行记录——它只负责重放。 + +重放使用 `cordis.snapshot.yml` overlay,以 `llm-replay` 替换真实适配器,同时保留实时组合。记录使用普通配置和由 harness 提供的持久化根目录。重放模式跳过 `.env` 加载,因此意外存在的 API 密钥不会触发实时调用。参见[单一来源配置 Agent Note](2026-07-04-single-source-acp-replay-config.md)。 + +### 两个表面:归一化后比对 + +快照运行断言**两个**归一化后的表面,因为 harness 的外部表面是不同的: + +1. **stdout transcript**——自动化客户端收到的、经过 framing 的 ACP JSON-RPC 响应与已提交的消息更新。它捕获传输契约的回归,与已提交的 `stdout.expected.jsonl` 比较。 +2. **重新持久化的会话 JSONL**,经过规范化后与 `session.jsonl` 比较。同一 fixture 同时作为重放来源和预期日志。提示词文本会被清理;按照[请求头固定 Agent Note](2026-07-06-pin-request-header-content-in-one-scenario.md)所述,每种请求头类别由一个场景固定可读提示词与工具内容。Override 场景仅从其 sidecar 派生模型行为。 + +两个表面互补:stdout 覆盖精简的自动化线协议,JSONL 覆盖线协议有意省略的 loop、工具和 boundary 结构。 + +规范化会替换会话、cwd、协议 id、时间戳、路径和进程易变值,同时保留确定性序号。场景把真实 bash 使用限制在稳定命令上。stdout 预期输出仍是线协议形状的 JSONL,每个原始行都必须可解析为 JSON。Vitest 只更新 stdout 预期输出;规范化会话相等性检查从不覆盖重放 fixture。 + +### 隔离:当前靠归一化,后续可加沙箱 + +工具确定性来自生成的 cwd、清理后的环境、全新的非登录 shell、受限命令和规范化。cwd 默认为平台临时目录;当临时目录是始终可写的策略根,而行为需要独立项目位置时,场景可以改为提供其父目录。并发重放运行各自拥有独立 cwd、持久化目录和由定长场景键区分的 spill 根目录,因此一个场景的拆除无法删除另一个场景仍在进行的完整输出恢复,同时真实路径预览预算保持稳定。该层不声称提供 OS 级隔离。如果需要更强层级,沙箱执行器可以通过现有[能力 seam](../architecture/2026-06-13-capability-seams.md)替换本地后端。 + +### 回放插件是独立的包 + +`@deepseek-ai/dsh-llm-replay` 是一个支撑包(package),而非示例本地的胶水代码。它通过用从 JSONL 重建的流短路 `llm/stream` 来替换真实适配器,其包级放置使回放逻辑处于正常覆盖率门禁之下。 + +### 两个子命令,回放在默认门禁中 + +`pnpm run test:snapshot` 无需密钥即可重放已提交 fixture;`test:snapshot:record` 使用真实 API,并重写采集的会话日志与 stdout 预期输出。缺少 fixture 时会响亮失败。每个场景都包含 `input.json`、`stdout.expected.jsonl` 和 `session.jsonl`;不调用模型的情况使用仅有请求头的日志。只有标记为 `overridden` 的场景才需要 `replay.override.json`,因为它一旦存在就会取代派生重放。Fixture 守卫会拒绝缺失、不匹配和孤立文件。两个命令都接受场景过滤器。 + +## 曾考虑的替代方案 + +- **手工编写包含模型分片的 `llm.json`**——早期草案;复用真实会话日志,使 fixture 成为系统的真实产物而非手工构建的 mock,并让它同时充当行为预期输出。 +- **字节级 HTTP 录制库(Polly/nock/MSW)**:否决。与适配器耦合,处理流式 SSE(Server-Sent Events)时笨拙,且层级低于被测对象。 +- **从 `turn/end {kind:'error'|'aborted'}` 合成抛错/取消条目**:否决。这会将 `llm-replay` 耦合到 loop 内部的轮次关闭语义,且 `turn/end` 原因是有损的(无法区分抛出的 401 与 finish-error);显式的 `replay.override.json` 伴随文件是更清晰的 seam。 + +## 后果 + +该测试层为每个场景增加经过评审的输入、会话、stdout、可选 override 和可选 workspace fixture。记录与重放都会把 workspace seed 复制到生成的 cwd。作为回报,该层通过真实 Loader 和工具组合提供确定性的无密钥覆盖。保留下来的大多数场景测试的是组装后的后端而非 ACP;[仅面向自动化的 ACP 决策](../simplification/2026-07-23-acp-automation-only-protocol.md#snapshot-boundary)将该语料保留在此处,并把向传输无关 headless 套件的任何迁移推迟为一项独立的测试变更(套件级 FIXME 标记了这一点)。 + +本 Agent Note 与[拟议的确定性 Agent Note](../../proposed/testing/2026-06-11-deterministic-and-stress-testing.md)相关,但不取代它:该提案的“通用重放 fixture”在每次测试后重新派生会话*消息历史*(内部一致性不变量),而这些快照固定组装后的行为与外部自动化输出。在后端语料迁出 ACP 之前,两者相互补充。 diff --git a/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.i18n.yaml b/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.i18n.yaml new file mode 100644 index 0000000000..97313f0333 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-19-real-api-e2e-ci.md: 935664fd01df4844ee19be7b4f2f297ebf5bd29b +2026-06-19-real-api-e2e-ci.zh.md: 9c10614f5a7e6b38f6850b29fab87d0e09806c5f diff --git a/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md b/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md index 05da5152ff..935664fd01 100644 --- a/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md +++ b/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md @@ -2,9 +2,11 @@ Status: implemented +English | [中文](2026-06-19-real-api-e2e-ci.zh.md) + ## Problem -The harness leans hard on real-API tests by policy: [docs/testing.md](../../../../docs/testing.md) argues that a no-key suite proves the plumbing but not the product, and the [ACP inject postmortem](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md) is the standing proof — 178 keyless tests stayed green while a real editor session crashed instantly. The real-API e2e suite (`pnpm run test:e2e`, the `*.e2e.ts` files) exists precisely to close that gap: it drives the agent against the live DeepSeek API — real model calls, real bash tools, multi-turn, resume, ACP-over-stdio. +The harness leans hard on real-API tests by policy: [docs/testing.md](../../../../docs/testing.md) argues that a no-key suite proves the plumbing but not the product, and the [ACP inject postmortem](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md) is the standing proof — 178 keyless tests stayed green while a real ACP client session crashed instantly. The real-API e2e suite (`pnpm run test:e2e`, the `*.e2e.ts` files) exists precisely to close that gap: it drives the agent against the live DeepSeek API — real model calls, real bash tools, multi-turn, resume, ACP-over-stdio. The default gate ([.github/workflows/ci.yml](../../../../.github/workflows/ci.yml)) is deliberately keyless: it carries no secret and runs for forks. `test:e2e` self-skips without a key (`describe.skipIf(!process.env.DEEPSEEK_API_KEY)`), so adding it there would report green without exercising the real suite. A separate secret-bearing workflow is required to make real-API coverage a merge signal. diff --git a/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.zh.md b/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.zh.md new file mode 100644 index 0000000000..9c10614f5a --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.zh.md @@ -0,0 +1,102 @@ +# Agent Note: 在 CI 中对外部 DeepSeek API 运行真实 API e2e 测试 + +Status: implemented + +[English](2026-06-19-real-api-e2e-ci.md) | 中文 + +## 问题 + +根据策略,harness 高度依赖真实 API 测试:[docs/testing.md](../../../../docs/testing.md) 指出,无密钥套件证明的是管线,而非产品;[ACP(Agent Client Protocol)inject 事后分析](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md)则是常设证据——178 项无密钥测试保持绿色时,真实 ACP 客户端会话却立即崩溃。真实 API e2e 套件(`pnpm run test:e2e`,即 `*.e2e.ts` 文件)的存在正是为了弥合这一缺口:它针对实时 DeepSeek API 驱动 agent(智能体)——真实模型调用、真实 bash 工具、多轮次、恢复、ACP-over-stdio。 + +默认门禁([.github/workflows/ci.yml](../../../../.github/workflows/ci.yml))刻意无密钥:不携带 secret,可供 fork 运行。`test:e2e` 在无密钥时自动跳过(`describe.skipIf(!process.env.DEEPSEEK_API_KEY)`),因此将其加入该工作流只会报绿而不会真正执行真实套件。要让真实 API 覆盖率成为合并信号,需要一个独立的、携带 secret 的工作流。 + +本 Agent Note(agent 决策记录)记下了新增**第二条消费 secret 的工作流**以在 CI 中运行真实 API 套件的决策;由于向未来可能公开的仓库引入第一个 CI secret 属于安全/隔离决策,本文也记录其依赖的威胁模型,以及仓库公开时需要做出的变更。 + +## 决策 + +添加一个专用工作流 [.github/workflows/e2e.yml](../../../../.github/workflows/e2e.yml),与 ci.yml 分离。它仅使用 repo secret 对外部 API 运行 `pnpm run test:e2e`,仅在可信事件上触发,并带有一个 preflight 检查:将缺失的 secret 转化为明确的失败而非虚假的绿色。无密钥工作流保持独立,使可 fork 的质量门禁与消费 secret 的真实 API 门禁各自拥有不同的触发和凭证策略。 + +### 独立工作流,而非 ci.yml 中的一个 job + +ci.yml 的价值在于它无密钥、可 fork、始终为绿:任何贡献者(包括外部 fork)都能获得完整的无密钥信号,secret 不在爆炸半径内。在其中添加消费 secret 的 job 会将这个始终为绿的门禁耦合到凭证可用性和不同的触发策略上。将携带 secret 的工作放在独立文件中,隔离了 secret、触发和并发策略,并为 fork 保留了 ci.yml 的特性。不同的生命周期→不同的文件。 + +### 约束不是成本,而是可靠性 + +内部推理成本不是限制因素,因此工作流针对覆盖面和信号优化。它会在多种触发条件和每个受信任 PR(Pull Request)上运行所有匹配的 `*.e2e.ts` 文件,以落实 [docs/testing.md](../../../../docs/testing.md) 的有密钥策略。 + +### 触发条件:仅限可信事件 + +`workflow_dispatch` + `push` 到 `main`/`master` + 每夜 `schedule`(`17 0 * * *`,即北京时间 08:17)+ `pull_request`。push 提供合并后信号;schedule 捕捉外部 API 漂移;dispatch 是手动逃生通道;可信 pull request 获得合并前门禁。该合并前信号有意接受 § 安全性中描述的更大密钥暴露面。 + +### 不可信 PR 的门禁 + +GitHub 对两类 PR 扣留 repo secret:来自 **fork** 的 PR,以及 **Dependabot** PR(同仓库分支,`head.repo.fork == false`,但 secret 仍被扣留)。一个 job 级 `if:` 对两者都跳过整个 job: + +``` +github.event_name != 'pull_request' + || !(github.event.pull_request.head.repo.fork || github.event.pull_request.user.login == 'dependabot[bot]') +``` + +Dependabot 子句基于 PR **作者**(`pull_request.user.login`)而非 `github.actor`(运行触发者):维护者重新打开或重跑 Dependabot PR 时,`github.actor` 会变成人类,但该 PR 仍然无密钥;基于作者的判断在这种情况下依然正确。被 **job 级** `if:` 跳过的 job 报告为*成功*检查(不同于工作流/触发级跳过会保持 pending),因此如果需要将此工作流标记为 required status check 也是安全的——fork/Dependabot PR 的跳过但绿色的检查不会阻塞合并。 + +该门禁是一个*干净跳过的便利措施*,而非 secret 的安全边界(见 § 安全性——边界是 GitHub 自身在 `pull_request` 下对 fork 的 secret 扣留机制)。没有该门禁,fork 仍然无法读取密钥;只是会遇到令人困惑的 preflight 硬失败并浪费计算资源。 + +### Preflight:大声失败,绝不虚假为绿 + +由于 job 仅在 secret 应当存在的可信事件上运行,preflight 是一个无条件的存在性检查:密钥为空→`exit 1` 并附带 `::error::` 注解指明需要配置的 secret 名称。这是让自跳过套件可以安全地作为门禁的关键。没有它,被删除/重命名/错误配置的 secret 会让 `test:e2e` 跳过所有真实套件并报告全绿——整个安全网的静默退化。该守卫将「secret 缺失」从不可见的虚假通过转化为可见的失败。(其正确性已在实际中验证:secret 存在之前的运行恰好在此步骤失败。) + +### Secret 映射与卫生 + +repo secret 命名为 `DEEPSEEK_API_KEY_EXTERNAL`;映射到适配器和测试读取的 `DEEPSEEK_API_KEY` 环境变量(`process.env.DEEPSEEK_API_KEY`)。独立的 secret 名称记录了意图(这是*外部*公开 API 密钥,不是内部端点密钥),并允许内部端点密钥日后无冲突地共存。以下卫生选择均为防御性设计: + +- **步骤级 secret。** `DEEPSEEK_API_KEY` 仅在 preflight 和 e2e 步骤的 `env:` 中设置,从不在 job 级设置——因此 checkout/setup-node/install 永远看不到它。依赖中被入侵的安装时生命周期脚本无法读取不在其环境中的 secret。 +- **`permissions: contents: read`。** job 仅读取仓库以运行测试;不需要写权限(无 PR 评论、无 status 写入),因此 `GITHUB_TOKEN` 降至最小权限。 +- **`DEEPSEEK_BASE_URL` 固定**为 e2e 步骤上的 `https://api.deepseek.com`。适配器在未设置时会默认使用此值([packages/llm/llm-deepseek/src/index.ts](../../../../packages/llm/llm-deepseek/src/index.ts) `PUBLIC_BASE_URL`),但显式固定具有自文档性和密封性——仓库根目录的 `.env`(`vitest.e2e.config.ts` 存在时会加载)无法静默地将运行重定向到其他端点。 +- **不回显 secret。** preflight 仅打印 `DEEPSEEK_API_KEY present.`——不打印值或长度。 + +### 范围与运行时形态 + +job 仅在 Node 24 上运行 `test:e2e`;无密钥门禁和版本兼容性属于主 CI 工作流。测试通过 workspace paths 映射以未构建形式运行,使用有界的可配置 worker 池、逐测试重试和 job 超时。被取代的 PR 运行会被取消,而 push 和 schedule 运行完整执行以提供合并后信号。 + +DeepSeek 原生 `web_search` 探测已注册但会跳过。实时 Anthropic 兼容端点可能返回成功响应却没有结构化来源块,因此对来源存在性的正向断言不是可靠的合并信号;单元覆盖率仍会固定响应解析,但 CI 不会证明实时来源块的线协议形状。 + +## 安全性 + +仓库的首个 CI secret 需要一份记录在案的威胁模型,因为同仓库 PR、fork PR 和 Dependabot PR 的访问权限各不相同,且仓库公开后会发生变化。 + +### 当前谁能触及 secret(私有仓库) + +- **无写权限(fork PR):不能。** 两个独立事实阻止了它。第一,工作流使用 `pull_request` 而**非** `pull_request_target`——GitHub 不会将 repo secret 传递给 fork PR 的 `pull_request` 运行,因此 `secrets.DEEPSEEK_API_KEY_EXTERNAL` 在 fork runner 上解析为空。第二,`if:` 门禁完全跳过 fork PR。secret 扣留是真正的边界;门禁是纵深防御和用户体验。 +- **有写(push)权限:能。** 同仓库分支 PR 会收到 secret,因此有写权限的作者可以修改测试代码(或安装生命周期脚本,或其分支上的工作流 YAML)来窃取密钥。这**是 GitHub Actions 的固有特性,并非本文引入的**:任何对任何仓库有 push 权限的人都可以通过编写工作流来窃取该仓库的任何 Actions secret。写权限⇒secret 访问权,始终如此。缓解措施在于谁被授予写权限以及分支保护,而非本文件。 + +因此「任何能开 PR 的人都能窃取它」是错误的:只有写权限集合内的人能,而这些人本来就能窃取仓库持有的任何 secret。 + +### `pull_request` 触发器增加的残余暴露面 + +由于启用了 PR 运行,密钥会在合并前被交给**写权限作者 PR 分支上的代码**。这比 `push` + `schedule` + `workflow_dispatch` 的暴露面更大,为在可信写权限集合内获得合并前信号而接受。如果这一权衡发生变化,可移除 `pull_request` 触发器,同时保留合并后、每夜和按需覆盖。 + +### 仓库公开后的变化 + +**通过本工作流**,secret 对公众仍然受保护:`pull_request` 在公开仓库上行为一致——fork PR(现在任何人都能开)仍然收不到 secret,且在公开仓库上 GitHub 额外要求维护者批准 fork PR 运行,即使批准后运行也不会获得 secret(批准运行不等于交出密钥)。写权限集合不因可见性改变而改变,因此内部人员的现实也不变。 + +变差的是*周边*模型,以下是翻转可见性之前需要处理的事项: + +- **日志变为全球可读。** 今天泄露给组织成员的粗心 secret 回显,公开后会泄露给整个互联网并在数分钟内被爬取。secret 处理纪律(不回显值/长度——已做到)的重要性大幅提升。 +- **`pull_request_target` 陷阱变为灾难性的。** 如果有人为了「修复」PR 运行而将触发器切换为 `pull_request_target`,工作流将在 base-repo 上下文中运行不可信的 fork 代码并**携带** secret——完整的密钥泄露向量。在私有仓库中这勉强无害,在公开仓库中则是灾难。e2e.yml 中触发器上的 `SECURITY —` 注释禁止此更改并指向本文。 +- **翻转时轮换密钥。** 密钥曾存在于私有仓库的 CI 中;将公开视为「假定已暴露」,在那一刻轮换 `DEEPSEEK_API_KEY_EXTERNAL`。 +- **将 secret 置于控制之下。** 确认 Settings → Actions → *"Send secrets to workflows from fork pull requests"* 保持**关闭**(这是唯一真正会打破 fork 边界的设置),并考虑将密钥移入带有 required reviewers 的 GitHub **Environment**,使即使已合并的代码也只在受控条件下使用它,且轮换有单一归属。 + +以上均不需要修改工作流即可公开;它们是运维步骤加上已添加的 `pull_request_target` 守卫注释。 + +## 曾考虑的替代方案 + +- **在 ci.yml 中添加消费 secret 的 job**:否决。会将无密钥、可 fork、始终为绿的门禁耦合到凭证可用性和不同的触发/并发策略上;不同的生命周期,不同的文件。 +- **省略 `pull_request` 触发器**(更小的密钥暴露面):为获得合并前信号而否决;安全性章节承载了已接受的暴露分析。 + +## 后果 + +新增一个 CI 工作流和仓库的首个需要维护的 secret。真实 API 套件现在作为合并门禁(可信 PR 上的合并前门禁、主分支上的合并后门禁)并每夜运行,因此 agent 与外部 API 交互中的真实故障会在 CI 中浮现,而非仅在开发者的本地运行中出现——代价是每个可信 PR 和合并都会产生真实的(但内部免费的)API 调用。preflight 使 secret 配置错误变为自我通告而非静默禁用安全网。 + +该设计带有已记录的约束表面:`pull_request` 触发器在密钥暴露方面的取舍(删除它可加强防护)、`if:` 门禁对基于作者的 Dependabot 检查的依赖,以及对 `pull_request_target` 的严格禁止。上方公开仓库检查清单是操作配套——未来维护者在更改触发器集合或切换仓库可见性之前,应重新阅读本 Agent Note,而不是从头推导 fork/secret 模型。 + +schedule 触发器在仓库不活跃 60 天后会自动禁用(GitHub 行为);push/PR/dispatch 是后备,活跃的 monorepo 不会触及此限制。假设 runner 对 `https://api.deepseek.com` 有出站连通性——GitHub 托管的 `ubuntu-latest` 具备此条件;受出站限制的自托管 runner 需要在依赖每夜运行之前确认连通性。 diff --git a/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.i18n.yaml b/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.i18n.yaml new file mode 100644 index 0000000000..9ea114c43e --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-remove-redundant-snapshot-log-expected-output.md: c2452f971d3cb76dceb766072dbc0a5c81465e78 +2026-06-20-remove-redundant-snapshot-log-expected-output.zh.md: e6175181589eabae064c34044f353efae537961b diff --git a/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.md b/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.md index b17ecad098..c2452f971d 100644 --- a/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.md +++ b/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-20-remove-redundant-snapshot-log-expected-output.zh.md) + ## Problem Model-driving ACP snapshot scenarios ship both `session.jsonl` and `session.expected.jsonl`. For normal recorded scenarios, `session.jsonl` is the replay fixture harvested from a real run, and the replay test normalizes the newly persisted log and compares it to `session.expected.jsonl`. In the current fixtures, the two normalized logs are identical for ordinary recorded scenarios. diff --git a/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.zh.md b/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.zh.md new file mode 100644 index 0000000000..e617518158 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 使用 `session.jsonl` 作为唯一的快照会话日志产物 + +Status: implemented + +[English](2026-06-20-remove-redundant-snapshot-log-expected-output.md) | 中文 + +## 问题 + +驱动模型的 ACP(Agent Client Protocol)快照场景同时包含 `session.jsonl` 和 `session.expected.jsonl`。对于普通记录场景,`session.jsonl` 是从真实运行采集的重放 fixture(测试前置数据);重放测试会规范化新持久化的日志,并将其与 `session.expected.jsonl` 比较。在当前 fixture 中,普通记录场景的两份规范化日志完全相同。 + +手工编写的 override 场景(`error-finish`、`cancel`)目前使用 `replay.override.json` 驱动模型行为,并把 `session.jsonl` 保留为最小 dummy fixture,而 `session.expected.jsonl` 存放预期的持久化日志。override 文件是由 `ReplayEntry` 对象组成的 JSON 数组:`{ "kind": "chunks", "chunks": StreamChunk[] }`、`{ "kind": "throw", "chunks": StreamChunk[], "message": string, "code": string }` 或 `{ "kind": "hang" }`。这种拆分同样没有必要:override sidecar 存在时,`llm-replay` 会替换派生脚本,不需要从 `session.jsonl` 取得模型分片,因此 `session.jsonl` 仍可作为场景的预期会话日志产物。 + +## 决策 + +彻底移除 `session.expected.jsonl` 概念。每个场景最多只有一个已提交会话日志产物,即 `session.jsonl`: + +- 对于录制场景,`session.jsonl` 仍是原始采集的日志。回放仍从中派生模型分片,快照测试将回放运行归一化后的持久化日志与归一化后的 `session.jsonl` 进行比较。 +- 对于手工编写的覆盖场景,`replay.override.json` 驱动模型行为,`session.jsonl` 存放预期产出的会话日志。当覆盖文件存在时,回放适配器不从 fixture 获取模型分片,因此同一个文件既可作为预期日志,又不影响回放行为。 +- 对于无模型场景,`session.jsonl` 可保留为引导 `llm-replay` 所需的最小 fixture;除非场景创建了持久化会话,否则无需进行会话日志比较。 + +Stdout 预期输出保持不变;它们是面向编辑器的投影,与会话 fixture 并不重复。 + +## 曾考虑的替代方案 + +**对两侧基于共享的(回放运行)上下文做归一化**:否决。`normalizeSessionLog` 通过精确字符串匹配擦除 cwd,因此 fixture 中录制的 cwd 不会被擦除,每次比较都会失败。两侧各自基于自身 header 派生的上下文做归一化——下方的实现说明描述了具体机制。 + +## 验证 + +快照 harness、fixture、孤立项守卫和文档中都不再出现 `session.expected.jsonl`;对于每个模型场景,快照测试都从 `session.jsonl` 派生预期会话日志;手工编写 sidecar 的场景把预期生成日志提交为 `session.jsonl`,并以 `replay.override.json` 覆盖模型行为;孤立 fixture 守卫知道每种场景类型所需的文件。[ACP 快照测试 Agent Note(agent 决策记录)](2026-06-19-acp-snapshot-tests.md)描述了精简后的 fixture 集合。 + +## 后果 + +评审者失去了一个能在视觉上区分预期持久化日志与重放 fixture 的产物名。stdout 预期输出仍然保护编辑器 transcript(文本记录),而将重放输出与 `session.jsonl` 比较,无需复制文件即可保留循环/持久化回归检查。 + +## 实现说明 + +两侧各自基于自身 header 值做归一化,因为录制与回放具有不同的 id、路径和时间戳。`fixtureContext()` 从 fixture 的 header 派生上下文,使已归一化的 fixture 具有幂等性。会话日志使用普通相等比较而非文件快照更新,因此比较过程不会改写 fixture。 diff --git a/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.i18n.yaml b/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.i18n.yaml new file mode 100644 index 0000000000..822fc921b4 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-22-fork-child-replay-seed-boundary.md: d3cbbb1dae1d64a10973bd5895ccc47d877eba28 +2026-06-22-fork-child-replay-seed-boundary.zh.md: a944538b9dcb74eb15142593089c7905efc3f565 diff --git a/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.md b/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.md index 93280ed62e..d3cbbb1dae 100644 --- a/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.md +++ b/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-22-fork-child-replay-seed-boundary.zh.md) + ## Problem The [per-session snapshot replay Agent Note](2026-06-22-subagent-snapshot-replay.md) made the snapshot tier express a nested-agent shape: a parent plus one recorded log per in-process subagent, each replayed as its own script keyed by calling session. It noted (§ Scope, final bullet) that a fork snapshot was "a trivial future addition, not a gap in the keying." That was wrong about a fork child specifically — not the keying, but the *script derivation*. diff --git a/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.zh.md b/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.zh.md new file mode 100644 index 0000000000..a944538b9d --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.zh.md @@ -0,0 +1,49 @@ +# Agent Note: 持久化 seed 边界以确保 fork 子会话回放正确路由 + +Status: implemented + +[English](2026-06-22-fork-child-replay-seed-boundary.md) | 中文 + +## 问题 + +[逐会话快照重放 Agent Note(agent 决策记录)](2026-06-22-subagent-snapshot-replay.md)使快照层能够表达嵌套 agent 形状:一个父项加上每个进程内 subagent 的一份记录日志,每份日志都按调用会话作为键,以独立脚本重放。它曾指出(§ 范围,最后一个项目符号),fork 快照“只是未来很容易添加的一项,并非键控缺口”。这一判断对 fork 子项而言是错误的——问题不在键控,而在*脚本派生*。 + +subagent 脚本由 [`deriveReplayScript`](../../../../packages/support/llm-replay) 从已录制的会话日志推导:它按 `(turn, step)` 对日志中的 `assistant/chunk` 事件分组,每次 `stream()` 调用对应一条回放条目。对 **spawn** 子会话而言这是正确的,因为其日志只包含自身的模型调用。 + +**fork** 子会话不同。fork 后端用*父日志的一段平衡的已完成轮次前缀*([`dsh-subagent-inprocess`](../../../../packages/subagent/subagent-inprocess))来播种子会话,而该 seed 会成为子会话持久化的 `log`(`Session` 构造函数将 seed 复制进 `this.log`)。因此 fork 子会话的 `.jsonl` 以**父会话**的事件开头——包括父会话的 `assistant/chunk` 事件——之后才是子会话自身的轮次。 + +从 fork 子会话的完整日志推导脚本,会把**父会话**的已录制响应当作**子会话**的模型调用来回放:实际运行的 fork 子会话第一次调用 `stream()` 时,会收到父会话的第一段分片序列而非自身的。目前已录制的场景全部是 spawn,所以这从未触发——但 fork 快照会静默地错误路由,恰好属于快照层存在的意义所要捕获的那类 bug。 + +## 决策 + +记录会话**继承**前缀的结束位置,将其持久化,并让回放 harness 仅从子会话**自身**的事件推导脚本。 + +### 1. 会话头部的 `seedLength` + +`SessionHeader` 新增可选字段 `seedLength: number`——表示有多少前导事件是通过 seed 继承而来、而非本会话产生的。fork 后端在创建子会话时设置它(= 播种前缀的长度);全新的 spawn 子会话不设置(等同于 0)。它通过 `CreateSessionOptions.meta`(及 `CreateAgentOptions.meta`)传递,在 `SessionStore.prepare` 中设置。 + +`seedLength` 是**显式**的,绝不从 `seed.length` 推断。恢复/加载时用会话的完整已存储日志作为 seed,此时 `seed.length` 是全长而非原始边界——恢复路径改为从加载的 header 中取回持久化的 `seedLength`。(形状与 `createdAt` 相同:恢复时显式保留,而非重新默认为当前时间。) + +### 2. 两个持久化后端均完整往返 + +- **JSONL**:header 行上的 `seedLength` 字段(`toHeaderLine`/`fromHeaderLine`)。 +- **SQLite**:`sessions` 表上的 `seed_length` 列。 + +包含 `seed_length`、`source_event_seqs` 和 `surface_op` 的 SQLite 布局为 schema version 4。更早的 version 3 布局存在歧义,因此在预发布策略下,所有非当前 `user_version` 均直接拒绝,不做迁移。 + +### 3. 回放从边界之后推导子会话脚本 + +`dsh-llm-replay` 的 `parseSessionHeader` 现在也读取 `seedLength`(缺失则为 0),`loadSessionScripts` 从 `parseSessionLog(text).slice(seedLength)` 推导子会话条目——即边界及之后的事件,也就是子会话自身的模型调用。对 spawn 子会话而言 `seedLength` 为 0,此操作是空操作,spawn 场景逐字节不变。 + +这关闭了路由正确性的缺口,两个已录制的 fork 场景对其进行端到端验证——见[记录 fork 与混合 spawn+fork 快照场景](2026-06-22-fork-snapshot-scenarios.md)。 + +## 曾考虑的替代方案 + +- **在 `llm-replay` 中启发式推导边界**(播种前缀是连续的父事件,止于子会话第一条 `user/message` 之前的最后一个 `turn/end`)。否决:在测试 harness 中用脆弱的启发式重新推导一个生产者已经知道的事实。在源头(fork 后端)持久化边界,是「在包(package)seam 处显式优于隐式」这条规则跨越持久化边界的应用——子会话 fixture(测试前置数据)的读取者永远不需要重建继承在哪里结束。 +- **固定格式版本而不递增**(事件日志使用的 `SESSION_FORMAT_VERSION = 0`「不稳定」姿态)。对 SQLite *表*布局否决:`SCHEMA_VERSION` 是单调递增并拒绝旧版的旋钮(一组小的、值得区分的修订),与事件词汇表的 `version` 不同。新增列正是它所版本化的那种破坏性表变更,因此需要递增。 + +## 后果 + +- core 与两个后端新增一个持久化 header 字段;核心数据结构目录(`persistence.md`)在同一变更中更新(其 `SessionHeader` / `CreateSessionOptions` 的 `type-equiv` 块)。 +- 既有的 schema v2 SQLite 数据库在打开时被拒绝(预发布阶段无用户数据)。 +- spawn 回放不变(`seedLength` 为 0)。fork 回放现在将子会话路由到自身的脚本;由 `llm-replay` 测试中的一个回归用例覆盖(一个子会话 fixture,其播种前缀包含父会话的分片——推导出的子会话脚本必须排除它,不做 slice 时该用例为红)以及一个持久化往返测试(两个后端,通过共享的 coordinator 契约)。 diff --git a/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.i18n.yaml b/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.i18n.yaml new file mode 100644 index 0000000000..2e87edf31e --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-22-fork-snapshot-scenarios.md: 46c688a4095a1d8af32b3b99887929f71a1526ce +2026-06-22-fork-snapshot-scenarios.zh.md: 8823611ec02f269e5a21a8065c9ed3cc3911f749 diff --git a/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.md b/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.md index 272e62ba77..46c688a409 100644 --- a/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.md +++ b/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-22-fork-snapshot-scenarios.zh.md) + ## Problem The [seed-boundary Agent Note](2026-06-22-fork-child-replay-seed-boundary.md) made fork-child replay route correctly: `dsh-llm-replay` derives a child's script from the events at or after its persisted `seedLength` boundary, so a fork child's inherited parent prefix is not replayed as the child's own model calls. But it shipped with **no recorded fork scenario** — the slice was exercised only by `llm-replay`'s unit tests (a synthetic child fixture) and a persistence round-trip test. The full-transcript snapshot tier, the one net that boots the real `acp-agent` and replays an end-to-end nested transcript, had only spawn children (`subagent-spawn`, `subagent-multi`). A fork-routing regression that left the unit tests green would still have escaped the tier built to catch transcript regressions. diff --git a/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.zh.md b/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.zh.md new file mode 100644 index 0000000000..8823611ec0 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 记录 fork 与混合 spawn+fork 快照场景 + +Status: implemented + +[English](2026-06-22-fork-snapshot-scenarios.md) | 中文 + +## 问题 + +[seed 边界 Agent Note(agent 决策记录)](2026-06-22-fork-child-replay-seed-boundary.md)让 fork 子项重放能够正确路由:`dsh-llm-replay` 根据持久化 `seedLength` 边界处及其后的事件派生子项脚本,因此 fork 子项继承的父前缀不会作为子项自身的模型调用重放。但落地时**没有记录式 fork 场景**——slice 只由 `llm-replay` 单元测试(合成子项 fixture(测试前置数据))和持久化往返测试覆盖。完整 transcript(文本记录)快照层——会启动真实 `acp-agent` 并重放端到端嵌套 transcript 的那张网——只有 spawn 子项(`subagent-spawn`、`subagent-multi`)。如果 fork 路由回归没有让单元测试变红,它仍会逃过专为捕获 transcript 回归而构建的这一层。 + +表达 fork 场景所需的快照基础设施已经就位:两个进程内后端都在 `cordis.yml` / `cordis.snapshot.yml` 中以两个面向模型的工具接入(`subagent` → spawn、`subagent_fork` → fork),harness 会收集每个子会话的日志,回放按 `seedLength` 为键转发各子会话的 fixture。缺少的是一个*已记录的场景*来驱动 fork 子会话走完这条路径。 + +## 决策 + +针对真实 API 记录两个场景,均在默认门禁中以无密钥方式回放: + +- **`subagent-fork`**:父会话完成一个轮次以建立一个事实,然后通过 `subagent_fork` 委派一个子任务。fork 子会话继承对话(其日志携带非零 `seedLength`),因此可以从父会话的上下文中作答。这是聚焦的回归守卫:子会话 fixture 的 `seedLength` 就是回放切片所依赖的边界,来自真实 fork 的记录而非手工合成。 +- **`subagent-mixed`**——父项完成一个轮次,随后在同一 transcript 中通过 `subagent` 委托一次(全新 spawn 子项,`seedLength` 为 0),再通过 `subagent_fork` 委托一次(fork 子项,`seedLength` 非零)。这是 seed 边界与逐会话重放 Agent Note 都点名作为未来新增项的 spawn+fork 混合场景:一份 transcript 覆盖两种传输方式和 slice 的两个分支(`seedLength` 为 0 = 无操作,`seedLength > 0` = 裁剪继承前缀),两个子项按 `createdAt` 排列为先 spawn、后 fork。 + +### 为什么需要一个已完成的第一轮次 + +fork 后端使用父项的**已配平完整轮次前缀**为子项提供 seed。父项若在第一个轮次就执行 fork,没有已完成轮次可供继承,因此 seed 为空(≡ 全新 spawn,`seedLength` 为 0)——这不会覆盖 slice。因此,两个场景都使用双提示词输入:第一个提示词完成一个轮次(建立稍后要求子项回忆的 codeword),第二个提示词委托 fork。子项 transcript 中回忆出的 codeword 只是模型行为的附带结果;承载关键约束的产物是子项 fixture 中记录、由重放 slice 消费的 `seedLength`。 + +## 后果 + +- fork 路由切片现在由全 transcript 层守卫,而不仅仅是单元测试。移除 `slice(seedLength)`(回放整个子会话日志)会让**两个**新场景变红——fork 子会话收到的是父会话记录的分片而非自己的——证明守卫确实生效(场景落地时已验证红→绿)。 +- `subagent-mixed` 是第一个在同一个 transcript 中驱动两种*不同* subagent 后端的快照场景,同时覆盖了跨 spawn 和 fork 子会话的逐会话回放键控。 +- 进程外(ACP(Agent Client Protocol))subagent 回放形态不同(每个子会话是独立进程、有自己的回放),仍以 `TODO(acp-subagent-replay)` 跟踪——本文场景仅限进程内。 +- 重新录制(`pnpm run test:snapshot:record`)会从真实 API 重新生成全部四个 fork/spawn fixture;两个新场景在无密钥时自动跳过,与所有已录制场景一致。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.i18n.yaml b/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.i18n.yaml new file mode 100644 index 0000000000..d89275da06 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-22-subagent-snapshot-replay.md: 6e5e94308ed145b83160146fd9e9ef023f2dde5d +2026-06-22-subagent-snapshot-replay.zh.md: 82bb7d0735c7dbf918941d00ee4c59498cc59085 diff --git a/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.md b/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.md index d21a081f9b..6e5e94308e 100644 --- a/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.md +++ b/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.md @@ -2,9 +2,11 @@ Status: implemented +English | [中文](2026-06-22-subagent-snapshot-replay.zh.md) + ## Problem -The snapshot tier (`pnpm run test:snapshot`) boots the real `acp-agent` subprocess, replays a recorded session through [`dsh-llm-replay`](../../../../packages/support/llm-replay), and diffs the normalized stdout transcript + re-persisted session log against committed expected outputs. It is the only tier that exercises the full editor-facing transcript end to end. +The snapshot tier (`pnpm run test:snapshot`) boots the real `acp-agent` subprocess, replays a recorded session through [`dsh-llm-replay`](../../../../packages/support/llm-replay), and diffs the normalized automation wire + re-persisted session log against committed expected outputs. Most scenarios exercise assembled backend behavior through that real process boundary. It was built for ONE session per process, and that assumption is wired into two places: diff --git a/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.zh.md b/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.zh.md new file mode 100644 index 0000000000..82bb7d0735 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.zh.md @@ -0,0 +1,58 @@ +# Agent Note: 嵌套 agent 的逐会话快照回放 + +Status: implemented + +[English](2026-06-22-subagent-snapshot-replay.md) | 中文 + +## 问题 + +快照层(`pnpm run test:snapshot`)会启动真实 `acp-agent` 子进程,通过 [`dsh-llm-replay`](../../../../packages/support/llm-replay) 重放已记录会话,并将规范化后的自动化线协议 + 重新持久化的会话日志与已提交预期输出进行 diff。大多数场景通过这条真实进程边界测试组装后的后端行为。 + +该层最初为每个进程只有一个会话而构建,这一假设硬编码在两处: + +- **`dsh-llm-replay` 没有做任何键控。** 它用一个全局游标,将第 N 次 `llm/stream` 调用对应到单一录制序列的第 N 条。当父 agent(智能体)和一个进程内 subagent 在同一个上下文上同时流式输出时,调用交错,单一游标会把子 agent 的脚本发给父 agent(反之亦然)。 +- **harness 只收集一份日志。** `findSessionLog` 遍历 sessions 根目录,返回找到的第一个 `.jsonl`。subagent 作为第二个 `Session` 运行,在同一个 cwd bucket 下有自己的日志,因此子 agent 的 transcript(文本记录)被静默丢弃。 + +这就是 [subagent seam Agent Note(agent 决策记录)](../feature/2026-06-21-subagent-capability-seam.md)中通过 `TODO(subagent-snapshots)` 推迟的工作:进程内后端(PR2)落地时已有单元 + e2e 覆盖,但在这套基础设施落地前,完整 transcript 快照层无法表达嵌套 agent 形状。本 Agent Note 就是该堆叠式后续工作。 + +## 决策 + +回放按**调用方会话**键控,harness 收集**所有**会话日志。 + +### 1. 调用方会话 id 附着在模型请求上 + +`GenerateOptions` 新增可选字段 `sessionId`,在请求组装时从 `agent.session.id` 赋值。适配器忽略它;`llm/stream` 监听器用它按发起会话路由。其类型为 `Branded<'SessionId'>`(来自 `dsh-brand`)而非 `dsh-session` 的 `SessionId`,因为后者所在包(package)导入了 `dsh-llm` 的 `Message`,反向导入会形成循环。两个类型等价,因此会话 id 赋值无需类型转换。将 brand 移到一个专用 ids 包属于独立工作,因为它会影响所有 id 导入。 + +### 2. 回放按首次调用顺序将活跃会话绑定到录制脚本 + +嵌套场景录制多份日志:父会话(`session.jsonl`)加每个 subagent 子会话各一份(`session.1.jsonl`……)。`dsh-llm-replay` 全部加载,为每个录制会话派生一份脚本,并按 header 中的 `createdAt` 排序(父会话先于子会话创建)。 + +活跃会话 id 每次运行都是全新随机值,永远不等于录制时的 id,因此活跃会话无法通过 id 相等绑定到脚本。取而代之的是**首次调用顺序**绑定:第一个发起任何模型调用的活跃会话认领第一份有序脚本(即父会话:`createdAt` 最早,且必然最先流式输出,因为它必须先运行一个轮次才能委派),下一个新活跃会话认领下一份脚本,依此类推。此后每个会话独立推进自己的游标。 + +这种方式按谁在调用键控,而非按全局调用顺序。因此即使 subagent 将来并发或在后台运行(全局游标会导致交错),它仍然正确。不携带 `sessionId` 的调用(直接在单元测试中调用 `stream()`)被视为一个匿名会话、绑定到主脚本,因此单会话路径与旧行为逐字节一致。活跃会话数多于录制脚本数时会快速失败报错(出现了未录制的 subagent),绝不会静默错误路由。 + +子 fixture(测试前置数据)按 `createdAt` 排序,在兄弟会话严格顺序执行时与调用顺序一致。id 平局打破仅使退化碰撞具有确定性。并发或后台子会话必须引入显式的首次调用序号,而非依赖时间戳。 + +## 曾考虑的替代方案 + +曾考虑但否决的方案是:**将父子日志按调用顺序合并**为一份全局脚本(仅在进程内 subagent 执行严格嵌套——父 agent 阻塞等待子 agent——时才正确)。对当前的同步裁剪而言更简单,但将「父阻塞于子」这一不变式固化了进去;未来若引入后台/并发 subagent 就会失效。逐会话键控则不会。 + +### 3. harness 收集所有日志,主会话优先 + +`harvestSessionLogs` 收集 sessions 根目录下每个 cwd bucket 中的所有 `.jsonl`(JSONL 后端将父会话与同 cwd 的子会话放在同一个 bucket),解析各自的 header,并按主会话优先排序:顶层会话(无 `parentSession`)在前,各子会话按 `createdAt` 升序排列。`RunResult.sessionLogs` 是复数结果;spec 在录制时将每份日志写回对应 fixture(`session.jsonl` + `session.<n>.jsonl`),在回放时将每份收集到的日志与其 fixture 做 diff。归一化器已支持复数会话 id 并会折叠任何游离 UUID,因此无需修改归一化器。 + +### 4. 场景 + +新增两个嵌套场景,均对真实 API 录制: + +- **`subagent-spawn`**:父 agent 通过 `subagent` 工具将一个子任务委派给一个新 spawn 的子 agent(2 个会话)。 +- **`subagent-multi`**:父 agent 委派两个子任务,各自交给自己的 spawn 子 agent(3 个会话),以三份并行脚本和同一父 agent 下两个子会话的 `createdAt` 排序来压测逐会话键控。 + +两者均在默认门禁中以 keyless 方式回放。 + +## 后果 + +- `TODO(subagent-snapshots)` 延期项已解决:嵌套 agent 的 transcript 现在是快照层的一等形态。 +- `GenerateOptions.sessionId` 是一个小而诚实的 core-seam 新增,在回放之外同样有用(遥测、请求路由)。 +- `subagent` 工具绑定到单一提供方,因此 `subagent-multi` 中的两个子 agent 都是 spawn(全新创建)。键控按会话路由而非按后端路由,因此对 fork 同样正确。但脚本*派生*逻辑此前不正确:fork 子会话的日志以种子化的父前缀(父会话的 `assistant/chunk` 事件)开头,如果从完整日志派生脚本,就会把父 agent 的响应当作子 agent 的来回放。这一正确性缺口通过持久化种子边界来弥合——见[持久化种子边界,使 fork 子项重放能够正确路由](2026-06-22-fork-child-replay-seed-boundary.md)——录制的 fork 与混合 spawn+fork 场景现在通过一份 transcript 同时验证两种传输方式(见[记录 fork 与混合 spawn+fork 快照场景](2026-06-22-fork-snapshot-scenarios.md))。 +- 进程外(ACP(Agent Client Protocol))subagent 是完全不同的回放形态(每个子 agent 是自己的进程、有自己的回放),作为 `TODO(acp-subagent-replay)` 记录在 PR3 计划中。 diff --git a/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.i18n.yaml b/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.i18n.yaml new file mode 100644 index 0000000000..83bd9197d8 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-hook-snapshot-matrix.md: 98f9db27fd8afaaa99c9985dff4d148ef4eb926b +2026-07-04-hook-snapshot-matrix.zh.md: 40b9ee84ad7232ac806096375e8da42bd02bfddf diff --git a/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.md b/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.md index 7c2c33460c..98f9db27fd 100644 --- a/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.md +++ b/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.md @@ -2,11 +2,13 @@ Status: implemented +English | [中文](2026-07-04-hook-snapshot-matrix.zh.md) + ## Problem The hook bridges — [`dsh-hooks-claude`](../../../../packages/hooks/hooks-claude) (7 Claude Code hook points) and [`dsh-hooks-codex`](../../../../packages/hooks/hooks-codex) (5 Codex points) — map external hook commands onto the harness interception seams. They carry deep unit and coverage-spec coverage (every decision arm, every payload dialect, driven against a mocked seam) plus one key-gated e2e (`hooks.e2e.ts`, a live `PreToolUse` block). But the full-transcript snapshot tier — the one net that boots the real `acp-agent` subprocess, replays a recorded session keyless, and diffs the normalized ACP stdout + re-persisted log against committed expected outputs — covered exactly ONE hook: a Claude `UserPromptSubmit` block (`hook-cc-promptsubmit-block`). -That is the tier a mocked unit test structurally cannot be: it exercises the REAL bridge translating a REAL hook process's outcome into the REAL seam decision, then the REAL loop's reaction, rendered exactly as an editor sees it. A bridge-translation or loop-structure regression that left every unit green would still escape it for every hook point but one — and for the Codex bridge, the ACP example did not even LOAD it, so no Codex hook could fire end-to-end at all. +That is the tier a mocked unit test structurally cannot be: it exercises the REAL bridge translating a REAL hook process's outcome into the REAL seam decision, then the REAL loop's reaction through the automation wire and persisted log. A bridge-translation or loop-structure regression that left every unit green would still escape it for every hook point but one — and for the Codex bridge, the ACP example did not even LOAD it, so no Codex hook could fire end-to-end at all. ## Decision diff --git a/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.zh.md b/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.zh.md new file mode 100644 index 0000000000..40b9ee84ad --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.zh.md @@ -0,0 +1,52 @@ +# Agent Note: 钩子快照矩阵——覆盖两种 bridge 的端到端预期输出测试 + +Status: implemented + +[English](2026-07-04-hook-snapshot-matrix.md) | 中文 + +## 问题 + +钩子 bridge——[`dsh-hooks-claude`](../../../../packages/hooks/hooks-claude)(7 个 Claude Code 钩子点)和 [`dsh-hooks-codex`](../../../../packages/hooks/hooks-codex)(5 个 Codex 点)——把外部钩子命令映射到 harness 拦截 seam。它们有深入的单元与覆盖率规格覆盖(每个决策分支、每种 payload dialect,针对 mock seam 驱动),外加一个受密钥门控的 e2e(`hooks.e2e.ts`,实时 `PreToolUse` 阻止)。但完整 transcript(文本记录)快照层——会启动真实 `acp-agent` 子进程、无需密钥重放已记录会话,并将规范化 ACP(Agent Client Protocol)stdout + 重新持久化日志与已提交预期输出进行 diff 的那张网——只覆盖了一个钩子:Claude `UserPromptSubmit` 阻止(`hook-cc-promptsubmit-block`)。 + +这正是 mock 单元测试在结构上无法替代的层级:它验证的是真实 bridge 将真实钩子进程的结果翻译到真实 seam 决策,再经由自动化线协议和持久化日志检验真实 agent loop(智能体循环)的反应。一个 bridge 翻译或 loop 结构的回归,即使让所有单元测试保持绿色,也会在除那一个钩子点之外的所有点上逃逸;而对于 Codex bridge,ACP 示例甚至没有加载它,因此没有任何 Codex 钩子能端到端触发。 + +## 决策 + +实现由两个耦合部分组成: + +### 1. ACP 示例同时加载两种钩子 bridge + +`examples/acp-agent/cordis.yml` 和 `cordis.snapshot.yml` 现在同时加载 `dsh-hooks-codex` 与 `dsh-hooks-claude`,各自指向自己的配置文件(Claude 用 `./hooks.json`,Codex 用 `./codex-hooks.json`——两种方言无法共用一个文件)。这是一个真正的产品接口变更,而非仅用于测试的接线:交付的 ACP 服务器(以及 `demo:acp` 入口)现在同时携带两种 bridge。 + +这是安全的,因为配置文件不存在时 bridge 是**静默无操作**的:`apply()` 捕获读取失败、通过 `ctx.logger` 记录日志、不注册任何东西——零监听器、零会话事件。`acp-agent` 应用不附带 stdout logger,因此警告不会到达 ACP JSON-RPC 通道。只需要 Claude 钩子的场景(或真实项目)只提供 `hooks.json`;Codex bridge 找不到 `codex-hooks.json` 便自动消失。这已通过实验验证:在两种 bridge 同时加载的情况下,所有既有快照(均不附带 `codex-hooks.json`)逐字节一致。 + +同时加载是让快照层能够在产品交付的同一个真实应用上验证每种方言的最低要求。录制(启动 `cordis.yml`)天然加载两者,回放以同样方式继承:`cordis.snapshot.yml` 是 `cordis.yml` 的 include-overlay,只替换 llm 入口(见[单一来源 acp-agent 回放配置](2026-07-04-single-source-acp-replay-config.md)),因此添加到运行时树的 bridge 无需第二次编辑即出现在回放树中。 + +### 2. 每个钩子点 × 其主要结果各一个快照场景,覆盖两种方言 + +`examples/acp-agent/tests/snapshots/` 下共 13 个场景,命名为 `hook-<dialect>-<point>-<outcome>`: + +- **手工编写、无模型轮次**(无密钥、无 sidecar——派生的回放脚本为空;比对的是携带 `hook/*` 事件的 `rejected` 轮次):`hook-cc-promptsubmit-block`、`hook-codex-promptsubmit-block`。 +- **对真实 API 录制、录制期间钩子活跃**(模型对决策的反应是捕获的 transcript 的一部分,此后无密钥回放):`hook-{cc,codex}-promptsubmit-context`(allow + additionalContext 折叠)、`hook-cc-pretool-deny` / `hook-codex-pretool-block`(deny → `isError` 工具结果)、`hook-cc-pretool-ask`(ask → 降级为 deny 并附带 approval-required 原因)、`hook-{cc,codex}-posttool-block`(阻止并附带反馈)、`hook-{cc,codex}-posttool-context`(accept + additionalContext)、`hook-{cc,codex}-stop-continue`(阻塞性 Stop 钩子通过 steering(中途引导)强制多走一步)。 + +每个钩子命令只输出固定字面量字符串(无时间戳/pid/`$RANDOM`/cwd 回显);快照规范化器擦除 `hook/result` 携带的唯一不稳定字段(`durationMs`)。`Stop` 场景通过标记文件(`.stop_fired`)自限,使 force-continue 不会循环——`stop_hook_active` 循环守卫仍是 bridge 的一个 `TODO`,因此无条件的 Stop 钩子会在每一步都 force-continue。 + +`PostToolUse` 阻止场景会在其证明的机制处自行限制。Claude 钩子在首次拒绝后持久化一个 workspace 标记,因此允许一次恢复调用;Codex 提示词发起一次调用并报告注入结果。每份预期输出固定一次遭阻止调用,不会重复阻止/重试循环。 + +### 三个钩子点被有意排除在快照之外 + +在构建矩阵过程中发现,记录于此是因为这些遗漏是决策而非疏忽: + +- **`SessionStart` 和 `SubagentStart`** 通过脱离且尽力而为的 `void runPoint(...).then(agent.inject())` 注入上下文,没有轮次绑定。由此产生的 `context/message` 会与它应先于的工作(首次模型请求 / 子项的第一个轮次)竞速,并落在不确定的日志位置。记录的预期输出甚至无法在自己的重放中复现——对两者执行 10 次重放稳定性检查,结果均为 10/10 次失败。它们继续留在 bridge 的单元覆盖率中,那里会直接驱动 seam 而不存在时序竞速。(如果注入未来改为绑定轮次且具备确定性——`TODO(session-start-gating)` 所指方向——它们就能接受快照测试。) +- **`SubagentStop`** 只观察:其 `subagent/end` handler 不传递轮次(因此没有 `hook/*` 日志事件),也不执行注入。它不会向 transcript 写入任何内容,因此预期输出会与无钩子运行逐字节相同,永远无法证明失败——一道咬不住问题的守卫。它继续由单元覆盖率负责(`bridge.spec.ts` 已断言仅观察调用)。 + +因此,该矩阵覆盖了所有具有确定性、可观测 transcript 足迹的钩子点,涵盖两种方言。 + +## 后果 + +- 现在,两种 dialect 中每个具有可观察 transcript 的 bridge seam 映射,都在真实应用的完整 transcript 层受到守护——包括此前完全没有端到端覆盖的 Codex bridge。记录的预期输出捕获模型对遭拒绝/遭阻止/强制继续轮次的真实反应,而手工编写的 transcript 只能猜测这种反应。 +- `UserPromptSubmit` 阻止场景无需密钥即可编写(没有模型轮次);其余场景从已记录 fixture(测试前置数据)无需密钥重放。`pnpm run test:snapshot:record` 从实时 API 重新生成记录式 fixture,并像所有记录场景一样在缺少密钥时自行跳过。 +- 证明会变红的准则仍成立:篡改钩子配置输出(例如改变拒绝理由)会让相应场景在重放时变红——钩子进程在重放期间真实运行(只有模型被重放),因此预期输出守护的是实际钩子→seam→循环路径,而非其 mock。 +- `acp-agent` 演示现在加载了一个通常会无操作的 Codex bridge(典型项目中没有 `codex-hooks.json`),这正是预期的柔性失败行为,而非代价。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.i18n.yaml b/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.i18n.yaml new file mode 100644 index 0000000000..719884e56c --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-single-source-acp-replay-config.md: f270d70feca184217503c472c1cb7c536187a249 +2026-07-04-single-source-acp-replay-config.zh.md: 86eb2d3e15c4939d1de3a78150cd0536d46e10f6 diff --git a/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.md b/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.md index 3de645deeb..f270d70fec 100644 --- a/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.md +++ b/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-04-single-source-acp-replay-config.zh.md) + ## Problem `examples/acp-agent` shipped two hand-maintained configs: `cordis.yml` (the live tree) and a `cordis.snapshot.yml` that mirrored it entry-for-entry with only the llm backend swapped — stripped of comments, the entire difference was the eight-line `llm-deepseek` stanza versus the two-line `llm-replay` stanza. Every app-shape change had to be made twice, and nothing gated the symmetry: if the copies drifted, the snapshot tier would silently exercise a different app than the one that ships — the ["green units, broken product" class of gap](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md) the snapshot tier exists to close, reintroduced one level up, with reviewer vigilance as the only defense. diff --git a/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.zh.md b/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.zh.md new file mode 100644 index 0000000000..86eb2d3e15 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.zh.md @@ -0,0 +1,27 @@ +# Agent Note: 将 acp-agent 回放配置改为单一来源 + +Status: implemented + +[English](2026-07-04-single-source-acp-replay-config.md) | 中文 + +## 问题 + +`examples/acp-agent` 发布了两份手工维护的配置:`cordis.yml`(实时树)和逐条镜像它、只替换 llm 后端的 `cordis.snapshot.yml`——去除注释后,两者的全部差异就是八行 `llm-deepseek` stanza 与两行 `llm-replay` stanza。每次应用形状变化都必须修改两遍,也没有任何机制约束对称性:如果副本发生漂移,快照层会悄然覆盖与已发布应用不同的应用——快照层本就是为了弥合[“单元测试绿色,产品损坏”这类缺口](../../../../docs/postmortem/0001-acp-default-export-drops-inject.md),如今同类缺口在上一层重新出现,只能依靠评审者警惕。 + +## 决策 + +`cordis.snapshot.yml` include 正式配置,通过 id 和 name 禁用指定的 DeepSeek 适配器,并插入回放适配器。其余所有条目因此来自正式运行树。回放时选择 overlay;录制仍然启动 `cordis.yml`,加载守卫允许被有意禁用的条目。 + +overlay 有意依赖一项 vendored 插件事实:include 加载文件时会应用 `patches`,而其 `refresh()`/`internal/update` 路径会重新读取但不重新打补丁——这恰好足以满足一次性重放启动(重放应用不加载 `hmr`,运行中也没有内容重写配置)。快照套件就是证明:所有场景都能在 overlay 上原样通过,包括逐字节相同的预期输出。 + +## 曾考虑的替代方案 + +### 为何不采用这些替代方案? + +保留完整的双副本并加一道对称性校验门禁是记录在案的退路——它能消除静默漂移这一类问题,但仍保留一份 125 行的近乎复制品,其全部内容只是一个条目的差异,且随应用每增加一个插件而增长。在 bin 侧做替换(解析配置、替换条目、删除文件)则会把 YAML 手术放进发布产物,并把回放差异藏到视线之外;overlay 让差异保持声明式、可读,且紧邻基础配置——这正是双副本支持者真正看重的教学价值。 + +## 后果 + +- 向 `cordis.yml` 添加插件即自动进入回放树,无需第二次编辑;漂移这一类问题从结构上消失,而非靠门禁拦截。 +- overlay 依赖条目携带稳定的 `id:`。禁用补丁上的 `name` 断言防止误定位(id 被复用时补丁跳过而非禁用错误的插件)。如果 id 被重命名,补丁退化为跳过,其警告需要一个回放应用有意不具备的 logger——可观测结果是一条无效的无密钥 `llm-deepseek` 条目与 `llm-replay` 并存,回放输出仍然正确(`llm-replay` 拥有流的短路权);这属于配置腐烂,留给评审发现,不会产生错误的快照。顶层插入一个 id 与既有条目冲突的新条目时,loader 的 id map 以后者为准;当前配置无冲突,新增补丁行才是引入冲突的场所。 +- 如果未来回放树需要第二处差异(另一个后端被替换),只需多加一行补丁,而非再 fork 一份文件。 diff --git a/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.i18n.yaml b/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.i18n.yaml new file mode 100644 index 0000000000..2b7c1cc937 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-06-pin-request-header-content-in-one-scenario.md: bca6d9eb943e758d68efaf3a76ec367179cd15fd +2026-07-06-pin-request-header-content-in-one-scenario.zh.md: e01c84c63583e2fe14b0b4fe0381a18b209d2346 diff --git a/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md b/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md index 1dcfc2e085..bca6d9eb94 100644 --- a/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md +++ b/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-06-pin-request-header-content-in-one-scenario.zh.md) + ## Problem An ACP snapshot suite needs to prove the exact composed system prompt and tool-schema list sent in each `request/header`, but duplicating that content inside every `session.jsonl` makes a prompt or schema edit rewrite dozens of giant one-line JSON records. Keeping one raw header avoids the duplication but still makes prompt review poor: prose is JSON-escaped onto one line and mixed with thousands of characters of tool schemas. diff --git a/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.zh.md b/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.zh.md new file mode 100644 index 0000000000..e01c84c635 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 在单个快照场景中固定请求头内容 + +Status: implemented + +[English](2026-07-06-pin-request-header-content-in-one-scenario.md) | 中文 + +## 问题 + +一个 ACP(Agent Client Protocol)快照测试套件需要证明每个 `request/header` 中实际发送的组合系统提示词与工具 schema 列表,但如果在每个 `session.jsonl` 中重复这些内容,一次提示词或 schema 编辑就会改写数十条巨大的单行 JSON 记录。保留一份原始 header 可以避免重复,但提示词的评审体验仍然很差:行文被 JSON 转义到一行中,与数千字符的工具 schema 混在一起。 + +## 决策 + +每种请求头组合类别恰好有一个场景标记为 `pinsHeader`。其目录按评审格式拆分固定内容:`system-prompt.expected.md` 以普通 Markdown 包含规范化的完整提示词序列;`tool-schemas.expected.json` 以结构化 JSON 包含对应的完整 schema 序列;`session.jsonl` 保留 config、reason 和所有模型可见前缀,同时将 `header.system` 与 `header.tools` 存为 `"{{system}}"` / `"{{tools}}"`。其他每份 JSONL 都使用相同的提示词与工具 token,并同样将会话前缀内容 token 化。固定机制位于 [`dsh-acp-snapshot`](../../../../packages/support/acp-snapshot/README.md),其套件 factory 强制每种类别恰好有一个固定场景。 + +纯 `scrubSystemPrompts` 和 `scrubToolSchemas` 规范化器会分别将每个已存储完整请求头 token 化。`scrubRequestHeaders` 还会为非固定场景把会话前缀内容 token 化,同时保留请求头数量、字段存在性、config、reason 和前缀消息数量。记录与刷新写回会在写入 JSONL 前应用适当清理,并根据规范化的实时完整请求头序列重新生成两个 sidecar,因此两条路径都无法把大段提示词/schema 重新引入 JSONL,也不会留下陈旧的评审产物。 + +守卫使这种拆分能够自我强制。在磁盘上,每个 `session*.jsonl` 都是提示词和 schema 清理器的固定点;只有非固定 fixture(测试前置数据)必须是完整请求头清理的固定点;两个 sidecar 恰好位于固定 fixture 旁,并采用规范、以换行符结尾的格式;每种类别都有一个固定场景。在实时运行中,由父项、spawn 子项、fork 子项、初始请求、恢复或实例内变化产生的每个 `request/header`,都必须在易变值规范化后与重建的类别序列匹配。请求头若没有字符串提示词、没有数组值工具列表,或超过固定场景声明的变更请求头数量,就会响亮失败。 + +一个固定场景覆盖整个套件,因为每个会话(parent、spawn 子会话、fork 子会话)组合出的工具列表完全相同、提示词除 cwd 外完全相同,而一致性守卫会在这一前提不再成立时立即使套件失败。如果 header 组合将来在设计上变为会话相关的(例如受限的 subagent 工具集),那么分歧的形态将获得自己的固定场景。 + +## 曾考虑的替代方案 + +- **每次变更重新录制或手动编辑所有 fixture**:保留了精确的 header,但行为差异被重复的提示词和 schema 内容淹没。 +- **仅在比较时 scrub,fixture 保持原始内容**:比较能通过,但已提交的 fixture 保留着陈旧的重复内容,下次录制时会整体重写。存储 token 诚实地表明每个 JSONL 没有固定什么。 +- **全部 scrub,不做任何固定**:丢失了组合 header 实际发送内容(提示词组装、已注册工具顺序、完整 schema)的唯一端到端记录。生成的工具目录只孤立地记录每个工具;只有真实 fixture 才能固定组合后的完整集合。 +- **将完整固定内容全部保留在 JSONL 中**:消除了套件范围的重复,但提示词和 schema 变更仍然是一行转义文本。Markdown 和结构化 JSON 为每种内容提供其自然的评审格式,同时不削弱重建 header 的断言。 +- **收窄会话日志本身(记录内容 digest,把请求头存到其他位置)**——违反可重建性契约:产品日志必须逐 bit 复现每个请求([可重建请求 Agent Note(agent 决策记录)](../architecture/2026-07-05-reconstructable-requests.md))。请求头体积是测试产物问题,应在测试规范化中解决;实时日志保持不变。 + +## 验证 + +该套件针对拆分后的固定内容回放每个场景。单元覆盖率会覆盖独立与完整清理器、两种完整请求头 sidecar 格式、记录/刷新重新生成、规范化提示词/schema 提取、固定点强制、必需文件对称性、重建请求头一致性,以及变更请求头数量拒绝。 + +## 后果 + +系统提示词变更在每个受影响的组合类别中产生一个面向行的 Markdown diff;工具描述变更在每个类别中产生一个结构化 JSON diff;普通行为 fixture 不受影响。会话 fixture 对省略的内容显示 token,运行时一致性守卫使每个拆分固定场景对其类别内的所有会话具有权威性。每个固定场景携带两个生成的、换行规范化的 sidecar 文件。 diff --git a/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.i18n.yaml b/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.i18n.yaml new file mode 100644 index 0000000000..5c5bad0b1a --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-08-shared-acp-snapshot-package.md: 3e5a2b12114d535490a17361128862f6d1c09a73 +2026-07-08-shared-acp-snapshot-package.zh.md: 072ef692702cb769c428f8b6aa3863a3b77d3d59 diff --git a/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.md b/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.md index 8d6032d1cc..3e5a2b1211 100644 --- a/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.md +++ b/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-08-shared-acp-snapshot-package.zh.md) + ## Problem The ACP snapshot tier ([snapshot Agent Note](2026-06-19-acp-snapshot-tests.md)) was built from three modules living inside one example's test directory: `snapshot-harness.ts` (boot the real bin subprocess, drive it over ACP JSON-RPC, harvest the persisted logs), `snapshot-normalize.ts` (the pure expected-output normalizers), and the ~150-line scenario body plus fixture guards in `acp.snapshot.ts` (record/replay modes, the stdout expected-output and log comparisons, the pinned-header uniformity guard, the orphan/required-file/single-pin meta-tests). diff --git a/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.zh.md b/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.zh.md new file mode 100644 index 0000000000..072ef69270 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.zh.md @@ -0,0 +1,40 @@ +# Agent Note: 将 ACP 快照套件提取为支持包 + +Status: implemented + +[English](2026-07-08-shared-acp-snapshot-package.md) | 中文 + +## 问题 + +ACP(Agent Client Protocol)快照层([快照 Agent Note(agent 决策记录)](2026-06-19-acp-snapshot-tests.md))由位于一个示例测试目录内的三个模块构建:`snapshot-harness.ts`(启动真实 bin 子进程,通过 ACP JSON-RPC 驱动它,采集持久化日志)、`snapshot-normalize.ts`(纯预期输出规范化器),以及 `acp.snapshot.ts` 中约 150 行的场景主体与 fixture(测试前置数据)守卫(记录/回放模式、stdout 预期输出与日志比较、固定请求头一致性守卫、孤立项/必需文件/单一固定项元测试)。 + +第二个希望获得快照覆盖的 ACP 示例——直接消费方是沙箱/approval 组合——只能复制这些模块,恰好分叉了绝不能漂移的逻辑:记录写回、请求头清理、子会话采集顺序。spawn/client 胶水也在 `acp.e2e.ts`、`hooks.e2e.ts` 和 harness 中重复三份。文件位置决定了测试严格度:逐文件 100% 覆盖率门禁只测量 `packages/*/*/src`,因此这些机制完全未被测量——正是同一种缺口,曾推动 `dsh-llm-replay` 从 `examples/` 移入 [packages/support](../../../../packages/support/README.md)。此外,harness 的 ACP client 硬编码 `requestPermission → cancelled`,因此 approval 往返——沙箱组合的主打行为——完全无法在快照层表达。 + +## 决策 + +这些机制位于 [`packages/support/acp-snapshot`](../../../../packages/support/acp-snapshot/README.md)(`@deepseek-ai/dsh-acp-snapshot`);示例的 `*.snapshot.ts` 只包含场景表、agent 路径和一次工厂调用,依赖自己的 `snapshots/` fixture 与 `cordis.snapshot.yml` overlay([单源回放配置](2026-07-04-single-source-acp-replay-config.md))。读取 `DSH_SNAPSHOT` 留在边缘层——库接收的是已解析的 `mode`。 + +**`src/launcher.ts`**——`launchAcpTestAgent` 拥有通用的未构建进程边界:绝对 tsx loader 解析、`TSX_TSCONFIG_PATH`、隔离的 harness home、stdio 接线、原始字节 stdout tee、stderr 与更新捕获、失败关闭的权限后备、更新 waiter,以及优雅或信号式关闭。快照场景和普通 e2e 套件提供相同的 `AgentUnderTest`(`binScript`、`configPath`、`tsconfigPath`);扮演用户的测试只提供其权限 handler。ACP 与钩子 e2e 套件以及沙箱/approval e2e 套件都使用该 launcher,而不再重新构建 SDK client 边界。 + +**`src/harness.ts`**——`runScenario` 和输入脚本/结果类型在 launcher 之上叠加确定性步骤、临时 workspace、快照环境和持久化日志采集。其 `session/request_permission` handler 消费可选的 `InputScript.permissionAnswers` FIFO 队列,每个条目按选项**类型**进行选择(id 是 agent 生成的随机值,已提交脚本无法预知;类型是 ACP 稳定词汇,会在回答时映射到已提供的 `optionId`);队列不存在或耗尽时回答 `cancelled`,若请求从未提供某种类型则拒绝该次运行——agent 自身收到的回答是 `cancelled`,因此场景 bug 会使 harness 失败,而不会被吸收为 agent 侧拒绝。由此,approval 套件可以根据 `input.json` 确定性地驱动允许/拒绝往返。 + +**`src/normalize.ts`** 是纯规范化器,按策略不含钩子:当未来某个事件携带新的易变字段(例如审批耗时),共享规范化器在同一个变更中学会它,保持「规范化」的含义只有一个归属,而非各套件各自扩展清洗逻辑。 + +**`src/suite.ts`**——包含 `Scenario` 类型和 `defineAcpSnapshotSuite(options)`,注册各场景比较、记录/刷新 fixture 写回、带实时一致性守卫的请求头固定项,以及 fixture 守卫块(没有孤立场景目录、必需文件存在、每种类别恰好一个固定项、每份 JSONL 都是 `scrubSystemPrompts` 固定点、非固定 fixture 同时也是 `scrubRequestHeaders` 固定点)。刷新会先展开打包的计时信封,再对齐现有易变事件时间,因此在打包与未打包布局之间切换不会移动后续记录;全新的分片片段数组仍为权威,因为其边界属于回放行为。场景目录中的 `session.jsonl` 加连续的 `session.<n>.jsonl` 同级文件构成有序主项/子项清单,因此场景表可以声明策略而不重复子项数量。固定请求头契约([固定请求头 Agent Note](2026-07-06-pin-request-header-content-in-one-scenario.md))按套件生效:每种请求头类别恰好标记一个 `pinsHeader` 场景,其 `system-prompt.expected.md` 和 JSONL 工具列表把组合请求头拆成可评审产物;一致性守卫会将两者与该类别的每个实时请求头比较。固定场景可以声明任何合法的变更请求头数量,其 Markdown 产物记录每个完整的已变提示词。纯辅助函数(`sessionFixtureNames`、`fixtureContext`、`normalizedHeaders`、`normalizedSystemPrompts`、`formatSystemPromptSnapshot`、`headerChangeCount`)从模块导出,以便直接进行单元覆盖。 + +## 曾考虑的替代方案 + +- **把模块复制到每个示例中**——这正是本 Agent Note 要防止的分叉:记录/守卫逻辑恰好是必须在各套件间保持逐字节相同的代码,而示例位于覆盖率门禁之外,所以每份副本也都无法测量。 +- **在 `examples/` 下建共享模块目录**:代码仍在覆盖率门禁之外,且需要跨示例边界的相对导入,违反包名导入约定;`examples/` 的叶子节点按设计应保持轻薄。 +- **`dsh-acp-demo` 的 `/testing` 子路径导出**:将测试基础设施耦合到产品包的对外服务接口与依赖集中;`packages/support/` 的存在正是为了真实但兼容性承诺较低的开发/测试包,`dsh-llm-replay` 是先例,本包与之配套。 +- **导出原始测试体函数而非套件工厂**:每个示例将重新拥有 `describe`/`it` 骨架(每套件约 80 行注册样板),却无灵活性收益;工厂使消费方只需一张场景表加一次调用,而导出的纯辅助函数在工厂设计内保留了可单元测试性。 +- **使用可注入 ACP `Client` factory 代替声明式 `permissionAnswers`**——灵活性最大,但会把 SDK client 构造泄漏给每个消费方,并恰好在正在统一的层重新引入逐示例漂移;声明式队列让 `input.json` 保持为唯一脚本表面,并与预期输出规范化兼容。 +- **泛化到 ACP 之外(传输无关的快照 harness)**:不存在第二种传输方式;harness 端到端都是 ACP 形态(SDK 客户端、JSON-RPC 帧、`session/update` 等待器),推测性的抽象将是一个超前于任何消费方的 seam 拆分。 + +## 测试 + +提取一致性得到机械证明:迁移后,`pnpm run test:snapshot` 的结果与基准提交匹配,`examples/acp-agent/tests/snapshots/` 下没有任何字节变化。包的 `src/` 在门禁单元运行中保持逐文件 100% 语句/分支/函数/行覆盖,并通过脚本化 fake ACP bin(`tests/fixtures/fake-acp-agent.ts`,每个场景由 fixture 旁的 `behavior.json` 编排行为)经过真实 launcher 驱动:`harness.spec.ts` 直接覆盖 launcher 默认值、捕获、更新等待、关闭以及环境/配置变体,随后覆盖每种场景步骤操作、两个 expect-error 分支、权限队列(选择、后备、不可能点击)、workspace seed,以及采集顺序/噪音/后备分支;`suite.spec.ts` 在收集时真实运行 factory——一个针对已提交合成 fixture 的回放套件和一个针对临时副本的记录套件(写回从不触及已提交树;`ACP_SNAPSHOT_SPEC_BOOTSTRAP=1` 会重新引导它)——并包含纯辅助函数的直接用例。fake bin 会把 `session/new` cwd 而非 `process.cwd()` 代入脚本化日志,与真实 bin 请求头携带的内容一致(darwin 会将 `/var/folders/…` realpath 为 `/private/var/folders/…`)。 + +## 后果 + +新示例通过场景表加 fixture 即可获得完整快照层,普通 ACP e2e 则通过一次 launcher 调用获得同一条经过测试的进程/client 边界。代价是:`suite.ts` 导入 vitest,因此包入口只能在 vitest 运行中导入——其他包都没有这种形状,其 README 已说明;每个套件还要固定自己的约 8 KB 请求头 fixture(真正不同的组合理应拥有自己的固定项;相同组合则会被该套件的一致性守卫捕获)。 diff --git a/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.i18n.yaml b/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.i18n.yaml new file mode 100644 index 0000000000..e36caa3f12 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-16-typed-event-schemas.md: 97a7d0c3787eb5556696e25a6c8b1bb75642aba9 +2026-06-16-typed-event-schemas.zh.md: c19f67c6ff058d42293ff2b6346630fe91c54dec diff --git a/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.md b/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.md index 500be241c6..97a7d0c378 100644 --- a/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.md +++ b/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-06-16-typed-event-schemas.zh.md) + ## Problem The harness models its core vocabulary — content blocks, message sources, finish reasons, turn triggers, turn-end reasons, and session events — as **merge-extensible maps**: a TypeScript `interface` (e.g. `SessionEventMap`, `ContentBlockMap`) that plugins augment via declaration merging, with the public union derived as `Map[keyof Map]`. This is the repo's universal extension pattern, documented in [docs/architecture.md](../../../../docs/architecture.md) ("The same merge-extensible-map pattern is used for `MessageSource`, `FinishReason`, `TurnTrigger`, and `TurnEndReason`") and relied on by the `defineTool` `InferArgs` DSL and the `assertNever` exhaustiveness convention. diff --git a/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.zh.md b/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.zh.md new file mode 100644 index 0000000000..c19f67c6ff --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.zh.md @@ -0,0 +1,77 @@ +# Agent Note: 事件词汇的运行时 schema(Zod 与 merge-extensible-map 模式之辩) + +Status: proposed + +[English](2026-06-16-typed-event-schemas.md) | 中文 + +## 问题 + +harness 将其核心词汇——内容块、消息来源、结束原因、轮次触发器、轮次结束原因与会话事件——建模为 **merge-extensible map**:一个 TypeScript `interface`(如 `SessionEventMap`、`ContentBlockMap`),插件通过声明合并对其扩展,公开联合类型则以 `Map[keyof Map]` 派生。这是本仓库的通用扩展模式,记录在 [docs/architecture.md](../../../../docs/architecture.md) 中(「The same merge-extensible-map pattern is used for `MessageSource`, `FinishReason`, `TurnTrigger`, and `TurnEndReason`」),`defineTool` 的 `InferArgs` DSL 和 `assertNever` 穷举约定都依赖于它。 + +该模式**仅存在于编译期**。类型在运行时消失:没有 schema 对象可供校验传入值、解析不可信输入或在运行时枚举变体。[会话持久化契约](../../implemented/architecture/2026-06-14-session-persistence.md)暴露了两个后果: + +1. **持久化将 `event.data` 视为不透明 JSON。** JSONL/SQLite 后端对每个事件逐字 `JSON.stringify`/`JSON.parse`;唯一的运行时守卫是 `isJsonValue`(往返可序列化性检查:拒绝 BigInt、函数、循环引用、非有限数等),而非结构校验。一个损坏但仍为合法 JSON 的事件数据(字段类型错误、字段缺失)会静默往返,只有在后续消费方的 `switch` 中才可能被捕获。 +2. **插件新增变体没有运行时契约。** 一个通过声明合并添加新 `SessionEventMap` 键的插件,在自身代码中获得了编译期类型,但没有任何机制校验它产出的值是否符合它所声明的形状——无论是在生产者处、持久化边界处还是重新加载时。 + +由此引出问题:事件词汇是否应迁移到 **Zod** 或其他运行时 schema 库,使持久化和插件边界拥有运行时 schema 而非被擦除的类型。 + +本 Agent Note(agent 决策记录)界定该问题的范围,不提出具体实现。 + +## 为什么这不是一个持久化层的改动 + +很容易把「用 Zod 做序列化」理解为对 `dsh-session-persistence-jsonl/src/format.ts` 的局部修改。但它不是,原因在于一个结构性事实:**插件无法对 Zod schema 进行声明合并。** 声明合并是 TypeScript 编译期机制;Zod schema 是运行时值。要用 Zod 校验事件,就需要一个**运行时注册表**,每个产出事件的包(package)向其贡献自己的 schema(如 `ctx.sessionEvents.register('compaction/marker', z.object({…}))`),每个消费方从中读取。这个注册表——而非持久化后端——将成为词汇的真源,取代 merge-extensible 接口。 + +因此,真正的提案是:**用运行时 schema 注册表替换编译期的 merge-extensible-map 模式,范围覆盖整个仓库。** 这是一次核心词汇的重新设计。 + +## 影响范围(已度量) + +将事件/词汇表面迁移到运行时 schema,至少涉及: + +- **六个 merge-extensible map**(约 370 行核心类型):`ContentBlockMap`、`MessageSourceMap`、`FinishReasonMap`(位于 `dsh-llm`);`TurnTriggerMap`、`TurnEndReasonMap`、`SessionEventMap`(位于 `dsh-session`)。 +- **约 10 处 `declare module` 扩展点**,分布在 `dsh-agent`、`dsh-agent-loop`、`dsh-bash`、`dsh-llm`、`dsh-session`、`dsh-session-persistence`、`dsh-system-prompt`、`dsh-tools` 各包中——每处都将从声明合并改为运行时 `register()` 调用。 +- **事件生产者**——agent loop(智能体循环)中 16 处 `session.append(...)` 调用——形状不变,但现在在边界处被校验。 +- **约 7 个 switch 消费方**,对这些联合类型进行分支:`deriveMessages` 与包自有的不变式 companion(`dsh-session`)、`BlockAssembler`(`dsh-llm`)、两个 LLM(大语言模型)适配器(`dsh-llm-deepseek`、`dsh-llm-pi-ai`)以及工具 schema 层(`dsh-tools`)。`assertNever` 对封闭联合类型的穷举 vs 对可扩展联合类型的 fall-through 约定(一条已记录的 lint 规则)需要重新考量——运行时变体在静态层面不可穷举。 +- **`defineTool` 的 `InferArgs` DSL**(`dsh-tools`),它从编译期 schema 规范派生出零类型转换的 `execute` 参数类型——这是当前方案的标杆用例。 +- **文档**:architecture.md(该模式被描述为基础性的)、[开发模式不变式](../../implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md),以及所有引用该模式的 Agent Note。 + +这是一次仓库级别的词汇重新设计,而非持久化的实现细节。 + +## 曾考虑的替代方案 + +### A. 维持现状——merge-extensible 类型 + 持久化边界处 `isJsonValue` +保留编译期模式。持久化继续使用不透明 JSON + 可序列化性守卫。插件通过声明合并扩展;事件*形状*的正确性由生产者负责,并由 TypeScript 在编译期保证。启用包自有的不变式 companion 后,它们会检查选定的跨记录关系,但不提供通用运行时形状 schema。 + +- **优点**:零变动;插件扩展只需一行 `interface` 增补,享有完整类型推断,无需运行时注册仪式;无新运行时依赖;`defineTool` DSL 与 `assertNever` 穷举继续工作。 +- **缺点**:持久化边界和插件 seam 处无运行时结构校验;格式错误但仍为合法 JSON 的数据被延迟捕获。 + +### B. 仅对头部/封闭形状做校验(schemastery),事件仍为不透明 +仅对那些已有手写类型守卫的真正封闭形状加以收紧——例如 JSONL 的 `HeaderLine` 守卫(`isHeaderLine`)——使用 **schemastery**(仓库现有的 schema 库,已用于每个插件的 `static Config`)。merge-extensible 事件联合类型保持不变。 + +- **优点**:改动小,契合现有约定(schemastery,而非新库);用声明式 schema 替换封闭形状上的手写守卫;无核心重新设计。 +- **缺点**:不解决事件数据校验问题;仅固定的元数据记录得到改善。 + +### C. 为整个词汇建立运行时 schema 注册表(Zod 或 schemastery) +用运行时注册表替换 merge-extensible map,生产者向其贡献 schema,持久化/消费路径据此校验。 + +- **优点**:持久化边界和插件 seam 处获得真正的运行时校验;单一真源;可支撑通用工具(自动生成文档、模糊测试、协议格式检查)。 +- **缺点**:上述全部影响范围;**Zod 目前不是直接依赖**(仅作为 `@earendil-works/pi-ai` 的传递依赖),仓库选定的 schema 库是 **schemastery**——广泛引入 Zod 本身就是一个依赖决策;声明合并的易用性(一行插件扩展、完整推断)被运行时注册 + 手动类型接线取代;`assertNever` 穷举保证弱化(运行时变体在静态层面不可穷举)。 + +## 提案 + +推迟。如果需要在持久化边界做运行时校验,**方案 B**(对封闭的头部和元数据形状使用 schemastery)是现有约定下的适度步骤。**方案 C** 是一个架构决策,需要自己的实现 Agent Note,其中包括 Zod 与 schemastery 之间的选择。 + +## 验收标准 + +- 方案 C 只能通过自己的实现 Agent Note 推进,绝不能作为持久化的附带改动。 +- 如果采纳方案 B,封闭的头部/元数据形状(JSONL 的 `isHeaderLine` 守卫及同类)改用 schemastery 校验,替代手写守卫,merge-extensible map 保持不动。 + +## 风险 + +- 推迟意味着事件 `data` 在持久化边界处仍无结构校验:格式错误但仍为合法 JSON 的数据被延迟捕获,由消费方的 `switch` 兜底——这是现状的代价,有意接受。 +- 如果方案 C 最终被采纳,易用性的损失是真实的:一行声明合并变为运行时注册加手动类型接线,`assertNever` 的静态穷举保证弱化。 + +## 待解问题 + +- 如果采用注册表,库选 **schemastery**(已在仓库中,已作为配置 schema 库)还是 **Zod**(生态更丰富,目前仅为传递依赖)?同时维护两个 schema 库本身就是一种成本。 +- 能否采用混合方案:保留编译期推断(使 `defineTool` 和插件开发体验不受影响),同时为每个变体添加*可选*的运行时 schema,仅在持久化/协议边界校验,而非每次进程内 append 都校验? +- `ctx.invariants` 服务启用后是否已覆盖了足够多的运行时形状缺口,使得边界校验仅在面对真正不可信输入(重新加载外部修改过的日志)时才有必要? diff --git a/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.i18n.yaml b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.i18n.yaml new file mode 100644 index 0000000000..5ab7a8229d --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-24-domain-kv-storage-and-workspace.md: cd666a47a3cba4dea8846cd0f1373224e6fc456f +2026-07-24-domain-kv-storage-and-workspace.zh.md: 81adf1eb6bc32aa3ca8b9ef4c352fb94f95ace91 diff --git a/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md new file mode 100644 index 0000000000..cd666a47a3 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md @@ -0,0 +1,329 @@ +# Agent Note: Domain KV storage capability seam and the workspace entity + +Status: proposed + +English | [中文](2026-07-24-domain-kv-storage-and-workspace.zh.md) + +## Problem + +The host's only persistence surface is the session event log (`packages/session-persistence`: append-only, one file per session). Anything that does not belong to a single session has nowhere to live, and two real needs exist today: + +- **The workspace entity.** The GUI needs workspace as a real object: path, title, and the list of owned sessions. Ownership belongs to the workspace — "which sessions belong to this workspace" is not any single session's fact, so writing it into the session log is semantically wrong. Until now workspace was only a sidebar visual grouping derived from cwd, with no entity (that conclusion has been overturned). +- **Dynamic session metadata** (the foreseeable second consumer). Cold session listings read only the first log line (an immutable creation-time snapshot); title, terminal status, and anything that evolves with the session is unavailable. The fix direction is a sidecar metadata table — exactly a KV table with high-frequency per-key updates. + +Separately, workspace deletion will eventually need to delete its owned sessions, and `SessionPersistence` has no delete primitive nor does the host expose a `session.delete` endpoint — that gap's design is settled in this note, but its implementation is marked future work: this phase touches no session-side code. + +## Proposal + +Create the `packages/storage/` group — the `ctx.storage` hub (backend registry + data-form mounts), two backends, the domain data form — plus the workspace consumer package; extend `SessionPersistence` with a delete primitive. + +| Package | Path | ctx surface | This phase | +| --- | --- | --- | --- | +| `@deepseek-ai/dsh-storage` | `packages/storage/storage/` | `ctx.storage` (the hub) | ✓ | +| `@deepseek-ai/dsh-storage-json` | `packages/storage/storage-json/` | registers backend `json` | ✓ | +| `@deepseek-ai/dsh-storage-sqlite` | `packages/storage/storage-sqlite/` | registers backend `sqlite` | ✓ | +| `@deepseek-ai/dsh-storage-domain` | `packages/storage/storage-domain/` | mounts `ctx.storage.domain` | ✓ | +| `@deepseek-ai/dsh-workspace` | `packages/workspace/workspace/` | `ctx.workspace` | ✓ | +| `SessionPersistence.delete` extension + cascade orchestration | `packages/session-persistence/*` | new method on the existing seam | ✗ future work (session side untouched this phase) | +| `workspace.*` / `session.delete` RPC, GUI wiring, boot assembly | — | — | ✗ next phase | + +(workspace lives in its own group rather than `packages/host/`: the host group's naming rule requires the `dsh-host-*` prefix while this package is named `dsh-workspace`; and the workspace entity is a domain concept, not bound to the host assembly tier. Unrelated to the existing `workspace-context` package — that is an AGENTS.md instruction loader.) + +Dependency direction: `dsh-workspace` → `dsh-domain` → `dsh-storage` ← the two backends. `dsh-workspace` additionally depends on the read-only face of `ctx.sessionPersistence` (attach's cwd check reads the session header; when the service is absent, attach rejects outright — no verification, no bookkeeping). The `ctx.sessions` running-check for session deletion moves into future work together with the cascade. + +### `dsh-storage`: the storage hub + +A pure registration hub, no IO of its own, no Config. The `Storage` service mounts at `ctx.storage` with two faces: `backend` (a `BackendRegistry`: `register(name, backend)` returns the disposer, duplicate names throw; `get(name)` throws `backend-not-found` for unknown names) and data-form mounting (`mount(form, facility)` over the merge-extensible `StorageForms` map, into which `dsh-domain` merges the `domain` key; unmounted access throws `form-not-mounted`). The signature text lives in `packages/storage/storage/src/index.ts` and `src/registry.ts`. + +**Multiple backends stay mounted side by side**; which backend serves a domain is `dsh-domain`'s configuration (below), never a global either-or. Disposer semantics = remove the name from the table; closing the backend itself belongs to the backend package's effect closure, unregister first then close. + +A backend is one **medium owner** (a file-tree root / one db file) exposing primitives through **data-shape facets** — only `kv` this phase; the session migration adds `log` (see the migration section). A facet is an optional member: absence means the backend cannot serve that shape, and resolution fails loud. The `kv` facet's primitive surface: `open(descriptor)` (descriptor = name/version/table list/global flag, with names and table names restricted to `^[a-z][a-z0-9_]*$` doubling as file-name and SQL-identifier segments) returns a unit exposing `loadAll` / `putRecord` / `deleteRecord` (missing key is a no-op) / `setGlobal` / `close` (idempotent); values are opaque JSON to the backend. The normative text (with per-method JSDoc) is `packages/storage/storage/src/backend.ts`. + +The backend contract (asserted clause by clause by the shared conformance suite, one suite for both backends): + +1. `open` creates when the medium holds nothing (lazy materialization allowed: may defer to the first write, but `loadAll` must immediately serve empty tables); loads when the medium exists. +2. A stored version ≠ descriptor.version → `StorageError('version-mismatch')`; no migration, no rebuild. +3. Durability: after a write primitive resolves, a process crash followed by a re-open must observe the write in `loadAll`. +4. The backend does not promise write ordering within a unit — **the caller serializes**; the backend only guarantees each single call is atomic (JSON whole-file replace / SQLite single statement). +5. `deleteRecord` is idempotent; `putRecord` overwrites. +6. Any string key / any JSON value is safe (keys never reach file paths, a structural property). +7. `close` is idempotent; any operation after close → `StorageError('closed')`. + +The error vocabulary is `StorageError` with a code discriminant: `backend-not-found` / `form-not-mounted` / `duplicate-backend` / `duplicate-mount` / `version-mismatch` / `malformed-medium` / `closed` (`packages/storage/storage/src/error.ts`). + +### `dsh-storage-json` + +Config is `root` only (required, no default, schemastery); apply registers backend `json` inside `ctx.effect()`, and the disposer unregisters the name before `backend.close()`. + +- Layout `<root>/<unitName>.json`, one file per unit; directory 0o700, files 0o600. +- File format (version stamp in the header; the file is always the current net state, `JSON.stringify(…, null, 2)` human-readable — that legibility is this backend's reason to exist): + +```json +{ + "unit": { "name": "workspace", "version": 1 }, + "global": null, + "tables": { "workspaces": { "<key>": {} } } +} +``` + +- Writes: every write primitive = full serialization of the in-memory state → temp write + fsync → atomic rename publish (the Windows variant follows session-persistence-jsonl's win32 path). Memory is authoritative, disk is its projection. +- `loadAll`: parse the whole file at open; a missing `unit` header, non-object tables, etc. → `malformed-medium`. A missing file = an empty unit, materialized on first write. + +### `dsh-storage-sqlite` + +Config is `path` (required, `':memory:'` allowed) plus `journalMode` (enum, default `wal`); apply mirrors json, registering backend `sqlite`. + +- `node:sqlite` `DatabaseSync`; the open sequence follows session-persistence-sqlite: mkdir 0o700 → `open(path,'wx',0o600)` exclusive create when missing → `PRAGMA foreign_keys=ON` → journal_mode → version check → create tables. +- Physical layout version `STORAGE_SQLITE_SCHEMA_VERSION = 1` in `PRAGMA user_version`: 0 → stamp; ≠ → `version-mismatch`. +- DDL (all STRICT; table names concatenated from the restricted character set with the `u_` prefix, no external input ever reaches DDL): + +```sql +CREATE TABLE IF NOT EXISTS units (name TEXT PRIMARY KEY, version INTEGER NOT NULL) STRICT; +CREATE TABLE IF NOT EXISTS unit_globals ( + unit TEXT PRIMARY KEY REFERENCES units(name), value TEXT NOT NULL) STRICT; +-- 每 unit 每表: +CREATE TABLE IF NOT EXISTS "u_<unit>_<table>" ( + key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT; -- value = 记录 JSON 文档 +``` + +- Unit versions live in `units` rows; a descriptor mismatch → `version-mismatch`. Row granularity is document-per-row, preserving precise per-key durable updates (the path left open for high-frequency point-update tables like the session sidecar); when query needs appear, JSON1 reads the value column directly. +- Write primitives are single statements and thus atomic; no cross-statement transactions needed (the domain layer has no cross-table transactions, see the out-of-scope list). + +### `dsh-domain`: the domain data form + +A single implementation, not abstracted; consumers depend on this layer only and never touch backends directly. + +```ts ignore-check +export const Config = z.object({ + backend: z.string().required(), // 默认后端名,必填 + routes: z.dict(z.string()).default({}), // per-domain 覆盖:{ workspace: 'sqlite' } +}) + +export function apply(ctx: Context, config: Config) { + ctx.effect(() => ctx.storage.mount('domain', new DomainFacility(ctx, config))) +} +``` + +(Facility unmount order: dispose each domain first (drain its write chain), then remove the name from the hub — in-flight writes still emit `domain/changed` during the drain, and the event-consistency invariant resolves domains back through the facility, so the name must stay resolvable at that point.) + +Domain declarations (the spec object is defined and exported by the package that owns the domain — the single source of type and runtime truth; schemas use zod with `z.infer` deriving the types without re-declaration — the record model projects into RPC wire schemas next phase and the wire boundary is all zod; schemastery still owns plugin Config only): + +```ts ignore-check +export interface DomainGlobalSpec<G> { readonly schema: ZodType<G>; readonly initial: G } +export interface DomainTableSpec<K extends string, V> { readonly valueSchema: ZodType<V> } + +export interface DomainSpec { + readonly name: string // ^[a-z][a-z0-9_]*$ + readonly version: number + readonly global?: DomainGlobalSpec<unknown> + readonly tables: Record<string, DomainTableSpec<string, unknown>> +} + +export function defineDomain<S extends DomainSpec>(spec: S): S +export function domainTable<K extends string, V>(schema: ZodType<V>): DomainTableSpec<K, V> +``` + +`DomainFacility.open(spec)` exact semantics (sequential; any failing step fails the whole open): + +1. A domain with this name already open → `DomainError('already-open')`. +2. Backend name = `config.routes[spec.name] ?? config.backend`; `ctx.storage.backend.get(name)` (an unmounted name propagates `backend-not-found` — misconfiguration fails loud). +3. Backend lacks the `kv` facet → `DomainError('facet-unsupported')`. +4. `kv.open(descriptorOf(spec))` (the descriptor is a direct projection of the spec). +5. `loadAll()`; every record passes `valueSchema.parse`, the global passes its schema (null takes `initial`, not persisted — first write materializes). A failure → `DomainError('invalid-record', { table, key })` (the durable boundary must validate; the write side does not re-validate). +6. Construct the `Domain` and register `ctx.effect()`: the disposer drains the write chain → `unit.close()`. + +```ts ignore-check +export interface Domain</* 由 spec 推导 */> { + readonly name: string + readonly global: { get(): G; set(value: G): Promise<void> } // 仅当 spec.global 声明 + table<N extends keyof S['tables']>(name: N): KvTable<KeyOf<N>, ValueOf<N>> +} + +export interface KvTable<K extends string, V> { + get(key: K): V | undefined // 内存快照,同步 + entries(): IterableIterator<[K, V]> + keys(): IterableIterator<K> + readonly size: number + put(key: K, value: V): Promise<void> + delete(key: K): Promise<boolean> // false = 本就不存在 + /** Atomic read-modify-write on the domain's single write chain; fn is sync-pure. */ + update(key: K, fn: (current: V) => V): Promise<V> // 缺 key → DomainError('missing-key') +} +``` + +Rules: + +- **Single-level mapping**: key → record, no nested tables; hierarchical needs use composite keys or fields inside the value. The two backends stay isomorphic as a result (one JSON object level ↔ one SQLite row). +- **Records are plain data**: immutable, directly JSON-serializable POJOs; values returned by `get`/`entries` must not be mutated in place (TypeScript readonly projection, no runtime freezing). Behavior-carrying domain objects belong to consumer packages. +- **Serialized writes**: one promise chain per domain; `put`/`delete`/`update`/`global.set` all queue on it; `update`'s fn runs on the chain, so concurrency cannot interleave. No active-record (pulling out a mutable object that auto-persists — uncontrollable persist timing, in conflict with the whole-unit atomic-rewrite model). +- **Version fails loud**: a stored version differing from the spec throws outright; no migration, no rebuild (the data is not regenerable; pre-release rejects old formats). +- **Change events**: after each write's durability resolves, emit `domain/changed` (`@mode emit`), one per record, no old value (matching the repository's "new snapshot + operation discriminant" convention, template `goal/changed`); the payload `DomainChanged` is a put/deleted discriminated union — domain + table + key (both `''` for global changes) + operation, with the put branch carrying the new snapshot value and the deleted branch carrying none (`packages/storage/storage-domain/src/events.ts`). This is next phase's RPC push-frame event source. The error vocabulary is `DomainError`, codes: `already-open` / `facet-unsupported` / `invalid-record` (with `{ table, key }`) / `missing-key` / `closed`. + +### Future work: session-side deletion (design settled, not implemented this phase) + +This section is the settled construction spec; the implementation phase changes code only, not semantics. No session-persistence file is modified this phase. + +```ts ignore-check +export abstract class SessionPersistence extends Service { + /** + * Permanently delete one session's stored log. + * Queued on the per-id write chain (serialized with in-flight appends). + * Unknown id → reject; un-materialized create intent → cancel it and resolve. + * After deletion the id behaves as unknown for every subsequent operation. + */ + abstract delete(id: SessionId): Promise<void> +} +``` + +- JSONL backend: unlink the session's file (including the `.zstd` variant); neither file nor intent → reject. +- SQLite backend: one transaction `DELETE FROM events…; DELETE FROM sessions…`; zero rows hit and no intent → reject. +- After a successful delete, emit `'session-persistence/deleted'(id: SessionId)` (`@mode emit`; the session-persistence event surface, unrelated to `domain/changed`). Derived data (the session-query full-text index and the like) subscribes and cleans itself; the persistence layer never reaches into indexes, and the crash window is covered by derived indexes being droppable-and-rebuildable. + +Orchestration rules (implemented together with the cascade; the `session.delete` RPC and the workspace cascade reuse the same rules): + +| Check (in order) | On failure | +| --- | --- | +| No target (the whole subtree when recursive) is running in `ctx.sessions` | throw, delete nothing; callers cancel first then delete — the persistence layer never reaches back into the runtime | +| Non-recursive: the target has no descendants (descendants = the `parentSessionId` transitive closure, derived from `list()` headers) | throw: by default only leaves are deletable; `recursive: true` opts into recursion | +| Recursive order is bottom-up (leaves → root) | — a mid-way crash leaves only "half the subtree deleted, ancestors intact"; re-running the same delete converges, and no dangling parent exists at any moment | +| Some id in the cascade is already gone from disk | skip (idempotent resumption); any other error aborts | + +### `dsh-workspace` + +The package owns the `WorkspaceId` brand and exposes `ctx.workspace`. The record key is a generated uuid — path is not the key: normalization rewrites it, and reference anchors must be stable. + +```ts ignore-check +export type WorkspaceId = Branded<'WorkspaceId'> +export function WorkspaceId(id: string): WorkspaceId + +const workspaceRecord = z.object({ + path: z.string(), // realpath,见下 + title: z.string(), + sessionIds: z.array(z.string().transform(SessionId)), + createdAt: z.string(), // ISO + updatedAt: z.string(), +}) +export type WorkspaceRecord = z.infer<typeof workspaceRecord> + +export const workspaceDomainSpec = defineDomain({ + name: 'workspace', version: 1, + tables: { workspaces: domainTable<WorkspaceId, WorkspaceRecord>(workspaceRecord) }, +}) + +declare module 'cordis' { interface Context { workspace: WorkspaceRegistry } } + +export interface Workspace { + readonly id: WorkspaceId + readonly path: string + readonly title: string + readonly sessionIds: readonly SessionId[] // 唯一真相且有序:数组序即展示序 + setTitle(title: string): Promise<void> + /** Record a session under this workspace (idempotent). Rejects when the session + * header's cwd (realpath) differs from this workspace's path. */ + attachSession(sessionId: SessionId): Promise<void> + detachSession(sessionId: SessionId): Promise<void> + /** Live directory check, uncached. */ + status(): Promise<'ok' | 'missing-dir'> +} + +export class WorkspaceRegistry extends Service { + constructor(ctx: Context) // super(ctx, 'workspace') + // start(): this.domain = await ctx.storage.domain.open(workspaceDomainSpec) + // 实体缓存 Map<WorkspaceId, WorkspaceEntity> 重建 + create(path: string, title?: string): Promise<Workspace> // realpath 后撞已有 → reject + get(id: WorkspaceId): Workspace | undefined + list(): Workspace[] + resolveByPath(path: string): Promise<Workspace | undefined> // 同 realpath 口径,故 async + // delete:future work(与 session 级联删一起做,见下);本期不提供任何删除入口 +} +``` + +- **Path canon**: the stored value = `fs.realpath(input)` (trailing slashes, `..`, and symlinks all resolved); uniqueness = string equality after normalization (a symlink resolving to the same directory counts as a collision). A missing directory makes create reject outright (realpath fails — a workspace must point at an existing directory; "Create new = make the directory" is upper-layer interaction: mkdir first, then create). The session cwd in attach checks follows the same canon. Single-valued cwd + unique path ⇒ one session structurally belongs to at most one workspace; double bookkeeping is impossible on the write side. +- **Title**: a display name, defaults to `basename(path)`, mutable, duplicates allowed. Ownership is never derived from cwd as a fallback — cwd cannot express ordering, and ownership is a workspace-side fact; sessions started headless belong to no workspace. +- Consumers see only the `Workspace` interface; `WorkspaceEntity` stays inside the package (a single implementation does not pre-split a seam). Entities are unique per id (registry cache); the record snapshot is swapped in place after each write, and the outside sees getters only. Every write funnels through the entity's internal `mutate(fn)` → `table.update`, with `updatedAt` refreshed inside mutate. Domain objects never cross RPC; next phase the wire layer projects records into zod wire schemas. +- **Workspace deletion is future work as a whole** (settled 2026-07-24): the registry ships no delete method this phase — the half-measure "delete the record, keep the sessions" is not exposed; deletion and the session cascade (`recursive` parameter, running checks, bottom-up order, crash-rerun convergence) land as one complete semantic together with the session delete primitive; the order then is delete sessions one by one → prune the ledger → delete the workspace record. + +Consistency doctrine (the ledger = the only ownership authority; the implementation and test baseline): + +| Situation | Behavior | +| --- | --- | +| A ledger id has no session on disk | filtered at `list()`/entity projection; pruned by the next mutate; no error (a normal product of deletion crash-consistency) | +| A session's cwd matches a workspace but is not in the ledger | not owned: no merging, no adoption. The GUI may later build an "orphan sessions" area (orphans = the complement of all ledgers) | +| One session in two ledgers | structurally blocked on the write side (attach check); detected at load → throw (externally hand-edited data, never masked) | +| The workspace directory does not exist | record and ledger stay; `status()` = `'missing-dir'`; the storage layer never auto-deletes (the directory may only be temporarily moved) | + +### Reuse and the session-backend migration outlook + +**Long-term direction**: the pure medium operations inside session-persistence's JSONL/SQLite backends sink into `dsh-storage` backends (the session packages stay; the `SessionPersistence` seam and coordinator semantics do not move — only the file/db operation layer beneath them does). The motive for reuse: the medium layer is all filesystem operations, database calls, and cross-platform grit (Windows permission and atomic-publish variants, fsync semantics, exclusive file creation…), which should be written once; business semantics (how a session appends, when, and what) stay above — while "did this append complete correctly underneath" (durability/atomicity/platform correctness) is the lower layer's responsibility, and the responsibility boundary is the facet primitive contract. The backend interface is therefore designed as **medium owner + data-shape facets**: a session log is an append-only stream, a different shape from KV — forcing them into one set of primitives would deform both, so facets split them (`kv` this phase, `log` at migration) while sharing the medium and its lifecycle. + +The current reuse audit (an account already legible before the migration): + +| Existing session-persistence logic | Nature | Disposition | +| --- | --- | --- | +| JSONL: temp write + fsync + link/unlink atomic publish, 0o700/0o600 permissions, Windows variant (win32.ts) | pure medium | copied by `dsh-storage-json` this phase (whole-file atomic rewrite is the same protocol); becomes the shared implementation at migration | +| JSONL: line-append, first-line header fast read, zstd per-frame compression | log shape | stays put; moves into the `log` facet at migration | +| SQLite: openDatabase (mkdir/exclusive create/PRAGMA sequence/user_version check) | pure medium | copied by `dsh-storage-sqlite` this phase — the two openDatabase copies are already near line-identical and this group is the third user; copy now, extract at migration | +| SQLite: events/sessions schema, same-transaction materialization | log shape | stays put; moves into the `log` facet at migration | +| coordinator (per-id write chain, lazy materialization, crash repair, flush barrier) | session semantics | never sinks — event-log domain logic whose counterpart here is the domain layer's write chain; each owns its own | +| encodeSegment (id-to-path escaping) | medium utility | unused on the domain side (keys never reach paths); sinks together with the `log` facet (one file per session) at migration | + +**This phase does not touch session-persistence's medium code** (only the delete primitive is added); the table above is the migration-phase work list and the design evidence that the backend interface must accommodate the log shape. + +### Test matrix + +| Suite | Coverage | Backends | +| --- | --- | --- | +| backend contract (shared suite, written once, run on both) | the seven contract clauses + version rejection + close idempotence | json, sqlite (`:memory:` + temp dirs) | +| registry/mount | duplicate registration, unmounted access, disposer removal | — | +| domain layer | the six open steps, schema rejection, update serialization (concurrent interleaving stress), `domain/changed` per record, global initial-value lazy materialization, routing and `facet-unsupported` | either (json) | +| workspace | create/uniqueness/realpath, attach checks (including rejection when sessionPersistence is absent), the four consistency-doctrine cases | mock domain or json | +| session delete contract (future work, joins runPersistenceContract at implementation) | unknown id, deleted-id reuse, un-materialized intent, serialization with in-flight appends, the deleted event | jsonl, sqlite | + +Snapshots: no model-visible or assembly surface this phase, none added; next phase's RPC wiring brings them with the `workspace.*` domain. + +### Out-of-scope list + +| Not doing | Trigger | Rework point | Groundwork | +| --- | --- | --- | --- | +| The full deletion suite (`SessionPersistence.delete`, the deleted event, `registry.delete` cascade, recursive delete, running checks) | future work starts (before the GUI needs delete interactions) | implement per the future-work section above: the session primitive + `registry.delete(id, { recursive? })` land as one | orchestration rules and rejection table settled in this note; no deletion entry exists this phase, so no half-semantics to stay compatible with | +| The `log` facet and the session-backend migration | any phase after this one | sink the medium operations (the reuse audit table is the work list) | the facet structure is in place; both backends' medium code is organized in sinkable shape already | +| Multi-process write protection | two host processes writing one medium | JSON backend file locks; SQLite WAL is natively multi-process | all writes already funnel through the domain's single point; locking touches backends only | +| Cross-process change observation | GUI reconnect awareness | the revision pattern (copy session-persistence) | `domain/changed` already exists in-process | +| Data migration | model changes after the first tagged release | version-driven per-domain migration | versions are on the medium from day one | +| Large-table performance | a thousand-record domain routed to json | point `routes` at sqlite, migrate the data by hand once | routing is configuration; consumers unchanged | +| Multi-segment keys | a real two-segment consumer appears (per-workspace per-session dimension data) | key generics become tuples, SQLite composite primary keys, JSON nested levels | single-level tables are the one-segment special case; no arbitrary-depth nesting; no string-concatenated keys | +| The scope dimension | a "one per workspace" domain appears and composite keys cannot express it | DomainSpec gains a scope declaration + a scope segment in file names (encodeSegment) | the name character set is already restricted; file names cannot collide | +| Cross-table atomic transactions | one business operation touching two tables of one domain atomically | `domain.transact(fn)`; JSON whole-unit rewrite is naturally atomic, SQLite wraps a transaction | — | +| Secondary indexes / conditional queries | in-memory filtering stops scaling (tens of thousands of records) | SQLite JSON1 over the value column, a read-only query facet on the seam | the JSON backend does not follow | +| Moving a session across workspaces | a product need appears | relax the attach check into a "detach first, then attach" orchestration | — | +| RPC/GUI/boot | next phase | `workspace.*` + `session.delete` endpoints, wire schemas, boot mounting, sidebar on real data | this phase's model and semantics are the direct source of the wire projection | + +## Alternatives considered + +- **Reusing session-persistence's coordinator/backends**: event-log semantics (append-only, turn crash repair, lazy materialization) do not match KV overwrite semantics; only the layering idea is borrowed (a coordination layer owns write ordering, backends implement minimal primitives). +- **A workspace-specific storage package, seam extracted later**: the second consumer (the session sidecar) is already foreseeable; generalizing later means touching the interface twice. +- **Merging domain and storage into one layer**: backends would be forced to touch schema validation, change events, and write serialization — domain concerns; split apart, storage backends implement only opaque primitives (the smallest replaceable surface) while the single domain implementation concentrates all domain logic (zod/events/serialization written once, not doubled per backend). +- **JSON backend as jsonl append + tombstones + compaction**: temp+fsync+rename crash safety is equivalent to append; rewriting keeps the file the net current state, human-readable, with no folding/compaction/torn-line tolerance; at domain scale a full rewrite costs the same as appending a line. +- **JSON one file per table**: under whole-file rewrites the file granularity does not affect write cost; merging per domain means fewer files and gives the global singleton a home. +- **SQLite storing a whole domain as one blob row**: any single-record change rewrites the whole domain, forfeiting per-key precise updates — SQLite's only edge over JSON reduced to zero. +- **SQLite generating typed columns from the schema**: a DDL generator is over-engineering; document-per-row suffices, revisit when real query needs appear. +- **One sqlite db file per domain**: contrary to the repository's one-database-many-tables convention. +- **A single whole-store backend choice (the session-persistence single-slot pattern)**: the initial design; changed to coexisting backends + configured routing because the hub will carry multiple data forms whose backend preferences (human-readable vs high-frequency point updates) are bound to diverge — a single slot forces the coarse "swap everything + hand-migrate data" move. The cost is one extra name lookup, backed by fail-loud. +- **path as the workspace key**: normalization/symlink resolution rewrites the path; reference anchors must be stable. +- **Ownership derived from cwd (or merged with the ledger)**: two sources of truth; cwd cannot express ordering; ownership is a workspace-side fact to begin with. +- **Change events carrying the old value**: the repository's change-event convention is "new snapshot + operation discriminant" (the sole exception, fs's before/after, is a method return value rather than an event, because the old value is unrecoverable afterwards and has a diff consumer); consumers needing diffs hold their own previous snapshot. +- **Delete auto-cancelling a running session**: the persistence/orchestration layer reaching back into the runtime dirties the layering; cancel already exists, callers compose it. + +## Acceptance criteria + +- This phase's four test suites all green: the shared backend contract suite on both json/sqlite, registry/mount disposer semantics, the domain layer (including the six open steps and fail-loud routing), and full workspace semantics (create/attach checks/consistency doctrine). +- `ctx.workspace` completes the create → attach → list lifecycle under a test assembly (deletion is future work). +- Zero diff in the session-persistence packages (the acceptance line for not touching the session side this phase). +- No new snapshots this phase (no model-visible or assembly surface); added next phase with the RPC wiring. + +## Risks + +- **The repository's first push-mode change event on a persistence surface** (session-persistence polls revisions): the shape has the `goal/changed` template, but "the storage layer emits events" is a new precedent, validated only when next phase's RPC consumes it. +- **The JSON backend's whole-unit rewrite scale premise**: if the second consumer (the session sidecar) lands on the JSON backend at thousand-record scale before being routed to SQLite, the rewrite cost surfaces earlier than expected; the mitigation is exactly `routes` pointing at sqlite. +- **The deletion orchestration's weak dependency on `ctx.sessions`**: a headless assembly without the runtime registry treats it as "no hot sessions", leaving a window (an external process running the session); multi-process is already out of scope, accepted. +- **Facet generalization designed against the future `log` facet without implementing it this phase**: a "reserved shape does not fit" risk; mitigated by organizing both backends' medium code in the sinkable shape from the reuse audit, so when the `log` facet lands only the facet layer moves. diff --git a/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md new file mode 100644 index 0000000000..81adf1eb6b --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md @@ -0,0 +1,329 @@ +# Agent Note: Domain KV storage capability seam and the workspace entity + +Status: proposed + +[English](2026-07-24-domain-kv-storage-and-workspace.md) | 中文 + +## Problem + +host 侧唯一的持久化面是 session 事件日志(`packages/session-persistence`:append-only、一 session 一文件)。凡是"不属于某个 session"的信息就没有落盘处,眼下有两个真实需求: + +- **workspace 实体**。GUI 要把 workspace 做成真实对象:路径、标题、关联 session 清单。归属关系由 workspace 持有——"哪些 session 属于这个 workspace"不是任何单个 session 自己的事实,塞进 session log 语义不成立。此前 workspace 只是 sidebar 上按 cwd 分组的视觉概念,没有实体(该结论已被推翻)。 +- **session 动态元信息**(可预见的第二个消费者)。冷会话列表只读日志首行 header(创建时的不可变快照),title、结束状态这类随会话推进变化的信息拿不到;补齐方向是 sidecar 元数据表——正是一张按 key 高频点更新的 KV 表。 + +另外,workspace 删除最终需要删除其关联 session,而 `SessionPersistence` 没有删除原语,host 也没有 `session.delete` 端点——该空白的设计随本 Note 定案,但实施标记为 future work:本期不动 session 侧任何代码。 + +## Proposal + +新建 `packages/storage/` 组——`ctx.storage` 存储枢纽(后端注册面 + 数据形式挂载面)、两个后端、domain 领域数据形式——及 workspace 消费者包;给 `SessionPersistence` 扩删除原语。 + +| 包 | 路径 | ctx 面 | 本期 | +| --- | --- | --- | --- | +| `@deepseek-ai/dsh-storage` | `packages/storage/storage/` | `ctx.storage`(枢纽) | ✓ | +| `@deepseek-ai/dsh-storage-json` | `packages/storage/storage-json/` | 注册 backend `json` | ✓ | +| `@deepseek-ai/dsh-storage-sqlite` | `packages/storage/storage-sqlite/` | 注册 backend `sqlite` | ✓ | +| `@deepseek-ai/dsh-storage-domain` | `packages/storage/storage-domain/` | 挂载 `ctx.storage.domain` | ✓ | +| `@deepseek-ai/dsh-workspace` | `packages/workspace/workspace/` | `ctx.workspace` | ✓ | +| `SessionPersistence.delete` 扩面 + 级联删编排 | `packages/session-persistence/*` | 既有 seam 新方法 | ✗ future work(本期不动 session 侧) | +| `workspace.*` / `session.delete` RPC、GUI 接线、boot 组装 | — | — | ✗ 下期 | + +(workspace 放独立组不放 `packages/host/`:host 组命名规则要求 `dsh-host-*` 前缀,而包名定为 `dsh-workspace`;且 workspace 实体是领域概念,不绑定 host 装配层。与既有 `workspace-context` 包无关——那是 AGENTS.md 指令加载器。) + +依赖方向:`dsh-workspace` → `dsh-domain` → `dsh-storage` ← 两后端。`dsh-workspace` 另依赖 `ctx.sessionPersistence` 的只读面(attach 的 cwd 校验读 session header;服务缺席时 attach 直接拒绝——无法校验即不写账)。session 删除相关的 `ctx.sessions` 运行中检查随级联删一并归入 future work。 + +### `dsh-storage`:存储枢纽 + +纯注册枢纽,自身不做 IO,无 Config。`Storage` service 挂 `ctx.storage`,两个面:`backend`(`BackendRegistry`:`register(name, backend)` 返回 disposer、重名 throw;`get(name)` 未知名 throw `backend-not-found`)与数据形式挂载(`mount(form, facility)` 配 merge-extensible 的 `StorageForms` map,`dsh-domain` merge 进 `domain` 键;未挂载访问 throw `form-not-mounted`)。签名正文见 `packages/storage/storage/src/index.ts` 与 `src/registry.ts`。 + +**多后端同时挂载**;域→后端的选择是 `dsh-domain` 的配置(见下),不是全局二选一。disposer 语义 = 从表中摘名;后端自身的 close 由后端包的 effect 闭包负责,顺序先摘名后 close。 + +一个后端是一个**介质 owner**(一棵文件树 root / 一个 db 文件),通过**数据形状 facet** 暴露原语——本期只有 `kv`;session 迁移期加 `log`(见迁移节)。facet 是可选成员,缺席即该后端不支持该形状,解析时 fail loud。`kv` facet 的原语面:`open(descriptor)`(descriptor = 名字/版本/表名清单/有无 global,名字与表名限 `^[a-z][a-z0-9_]*$` 兼作文件名与 SQL 表名段)返回 unit,unit 提供 `loadAll` / `putRecord` / `deleteRecord`(缺 key 为 no-op)/ `setGlobal` / `close`(幂等);值对后端是不透明 JSON。规范正文(含逐方法 JSDoc)在 `packages/storage/storage/src/backend.ts`。 + +backend 契约(共享契约测试逐条断言,两后端同套件): + +1. `open` 对不存在的介质创建(懒物化允许:可延迟到首写,但 `loadAll` 立即可用返回空表);对已存在介质载入。 +2. 介质上版本 ≠ descriptor.version → `StorageError('version-mismatch')`,不迁移不重建。 +3. 持久性:写原语 resolve 后进程崩溃再 open,`loadAll` 必须反映该写入。 +4. 后端不承诺 unit 内写并发序——**调用方负责串行**;后端只保证单次调用原子(JSON 整文件替换 / SQLite 单语句)。 +5. `deleteRecord` 幂等;`putRecord` 覆写。 +6. 任意字符串 key / 任意 JSON 值安全(key 不进文件路径,结构性质)。 +7. `close` 幂等;close 后任何操作 → `StorageError('closed')`。 + +错误词汇是带 code 判别的 `StorageError`,码表:`backend-not-found` / `form-not-mounted` / `duplicate-backend` / `duplicate-mount` / `version-mismatch` / `malformed-medium` / `closed`(`packages/storage/storage/src/error.ts`)。 + +### `dsh-storage-json` + +Config 仅 `root`(必填无默认,schemastery);apply 在 `ctx.effect()` 里注册后端 `json`,disposer 先摘名再 `backend.close()`。 + +- 布局 `<root>/<unitName>.json`,一 unit 一文件;目录 0o700、文件 0o600。 +- 文件格式(版本戳在头,文件即当前净值,`JSON.stringify(…, null, 2)` 肉眼可读——这是该后端的存在理由): + +```json +{ + "unit": { "name": "workspace", "version": 1 }, + "global": null, + "tables": { "workspaces": { "<key>": {} } } +} +``` + +- 写入:任何一次写原语 = 内存态全量序列化 → temp 写 + fsync → rename 原子发布(Windows 变体照抄 session-persistence-jsonl 的 win32 路径)。内存态是权威,盘是投影。 +- `loadAll`:open 时整文件 parse;缺 `unit` 头、tables 非对象等 → `malformed-medium`。文件不存在 = 空单元,首写才落盘。 + +### `dsh-storage-sqlite` + +Config 为 `path`(必填,`':memory:'` 允许)+ `journalMode`(枚举,默认 `wal`);apply 同 json,注册后端 `sqlite`。 + +- `node:sqlite` `DatabaseSync`;打开序列照抄 session-persistence-sqlite:mkdir 0o700 → 不存在则 `open(path,'wx',0o600)` 独占建文件 → `PRAGMA foreign_keys=ON` → journal_mode → 版本检查 → 建表。 +- 物理布局版本 `STORAGE_SQLITE_SCHEMA_VERSION = 1` 存 `PRAGMA user_version`:0 → 盖章;≠ → `version-mismatch`。 +- DDL(全 STRICT;表名由受限字符集拼接加 `u_` 前缀,杜绝外部输入进 DDL): + +```sql +CREATE TABLE IF NOT EXISTS units (name TEXT PRIMARY KEY, version INTEGER NOT NULL) STRICT; +CREATE TABLE IF NOT EXISTS unit_globals ( + unit TEXT PRIMARY KEY REFERENCES units(name), value TEXT NOT NULL) STRICT; +-- 每 unit 每表: +CREATE TABLE IF NOT EXISTS "u_<unit>_<table>" ( + key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT; -- value = 记录 JSON 文档 +``` + +- unit 版本存 `units` 行,descriptor 不符 → `version-mismatch`。行粒度 document-per-row,保住按 key 精确落盘更新(为 session sidecar 这类高频点更新大表留路);查询需求出现时 JSON1 直查 value 列。 +- 写原语单语句即原子,无跨语句事务需求(domain 层无跨表事务,见不做清单)。 + +### `dsh-domain`:领域数据形式 + +单实现不抽象;消费者只依赖这层,不直接触后端。 + +```ts ignore-check +export const Config = z.object({ + backend: z.string().required(), // 默认后端名,必填 + routes: z.dict(z.string()).default({}), // per-domain 覆盖:{ workspace: 'sqlite' } +}) + +export function apply(ctx: Context, config: Config) { + ctx.effect(() => ctx.storage.mount('domain', new DomainFacility(ctx, config))) +} +``` + +(facility 卸载顺序:先 dispose 各域(排空写链)再从枢纽摘名——排空期间在途写仍发 `domain/changed`,事件一致性 invariant 经 facility 反查域,要求此时域名仍可解析。) + +域声明(spec 对象由拥有该域的包定义导出,是类型与运行时的单一来源;schema 用 zod,`z.infer` 推导类型不重复声明——记录模型下期要投影成 RPC wire schema,wire 边界全是 zod;schemastery 仍只管插件 Config): + +```ts ignore-check +export interface DomainGlobalSpec<G> { readonly schema: ZodType<G>; readonly initial: G } +export interface DomainTableSpec<K extends string, V> { readonly valueSchema: ZodType<V> } + +export interface DomainSpec { + readonly name: string // ^[a-z][a-z0-9_]*$ + readonly version: number + readonly global?: DomainGlobalSpec<unknown> + readonly tables: Record<string, DomainTableSpec<string, unknown>> +} + +export function defineDomain<S extends DomainSpec>(spec: S): S +export function domainTable<K extends string, V>(schema: ZodType<V>): DomainTableSpec<K, V> +``` + +`DomainFacility.open(spec)` 精确语义(顺序执行,任一步失败即整体失败): + +1. 同名域已打开 → `DomainError('already-open')`。 +2. 后端名 = `config.routes[spec.name] ?? config.backend`;`ctx.storage.backend.get(name)`(未挂载穿透 `backend-not-found`——misconfiguration fails loud)。 +3. 后端无 `kv` facet → `DomainError('facet-unsupported')`。 +4. `kv.open(descriptorOf(spec))`(descriptor 由 spec 直接投影)。 +5. `loadAll()`;每条记录 `valueSchema.parse`,global 过 schema(null 取 `initial`,不落盘,首写才落盘)。失败 → `DomainError('invalid-record', { table, key })`(durable 边界必须校验;写侧不重复校验)。 +6. 构造 `Domain` 并注册 `ctx.effect()`:disposer 排空写链 → `unit.close()`。 + +```ts ignore-check +export interface Domain</* 由 spec 推导 */> { + readonly name: string + readonly global: { get(): G; set(value: G): Promise<void> } // 仅当 spec.global 声明 + table<N extends keyof S['tables']>(name: N): KvTable<KeyOf<N>, ValueOf<N>> +} + +export interface KvTable<K extends string, V> { + get(key: K): V | undefined // 内存快照,同步 + entries(): IterableIterator<[K, V]> + keys(): IterableIterator<K> + readonly size: number + put(key: K, value: V): Promise<void> + delete(key: K): Promise<boolean> // false = 本就不存在 + /** Atomic read-modify-write on the domain's single write chain; fn is sync-pure. */ + update(key: K, fn: (current: V) => V): Promise<V> // 缺 key → DomainError('missing-key') +} +``` + +规则: + +- **一级 mapping**:key → 记录,不做嵌套表;层级需求用复合 key 或值内字段。两后端因此同构(JSON object 一层 ↔ SQLite 一行)。 +- **记录是纯数据**:可直接 JSON 序列化的不可变 POJO;`get`/`entries` 返回值不得原地改(TypeScript readonly 投影,不做运行时冻结)。带行为的领域对象属于消费者包。 +- **写串行**:域内一条 promise 链,`put`/`delete`/`update`/`global.set` 全排队;`update` 的 fn 在链上执行,并发不交错。不做 active-record(取出可变对象自动落盘——落盘时机不可控,与整域原子覆写冲突)。 +- **版本 fail loud**:盘上版本与 spec 不符直接报错,不迁移不重建(数据不可再生,pre-release 拒绝旧格式)。 +- **变更事件**:每次写落盘 resolve 后 emit `domain/changed`(`@mode emit`),逐条发、不带旧值(对齐仓库"新快照 + 操作判别"惯例,范本 `goal/changed`);payload `DomainChanged` 是 put/deleted 判别联合——域名 + 表名 + key(global 变更两者为 `''`)+ operation,put 支带新快照 value、deleted 支无 value(`packages/storage/storage-domain/src/events.ts`)。此为下期 RPC 推帧的事件源。错误词汇 `DomainError`,码表:`already-open` / `facet-unsupported` / `invalid-record`(带 `{ table, key }`)/ `missing-key` / `closed`。 + +### Future work:session 侧删除(设计定案,本期不实施) + +本节是定案的施工规范,实施期不动语义只动代码;本期 session-persistence 的任何文件都不修改。 + +```ts ignore-check +export abstract class SessionPersistence extends Service { + /** + * Permanently delete one session's stored log. + * Queued on the per-id write chain (serialized with in-flight appends). + * Unknown id → reject; un-materialized create intent → cancel it and resolve. + * After deletion the id behaves as unknown for every subsequent operation. + */ + abstract delete(id: SessionId): Promise<void> +} +``` + +- JSONL 后端:unlink 该 session 文件(含 `.zstd` 变体);文件与 intent 均无 → reject。 +- SQLite 后端:单事务 `DELETE FROM events…; DELETE FROM sessions…`;0 行命中且无 intent → reject。 +- 删除成功后 emit `'session-persistence/deleted'(id: SessionId)`(`@mode emit`;session-persistence 层事件面,与 `domain/changed` 无关)。派生数据(session-query 全文索引等)订阅自清;持久层不直连索引,崩溃窗口靠派生索引可丢弃重建兜底。 + +编排层规则(随级联删一起实施;`session.delete` RPC 与 workspace 级联复用同一规则): + +| 检查(按序) | 不满足时 | +| --- | --- | +| 目标(递归时含整棵子树)无一在 `ctx.sessions` 运行 | throw,什么都不删;调用方先 cancel 再删,持久层不反向牵动运行时 | +| 非递归时目标无后代(后代 = `parentSessionId` 传递闭包,由 `list()` header 求得) | throw:默认只能删叶子,`recursive: true` 显式递归 | +| 递归序自底向上(叶→根) | ——中途崩溃只留"子树删一半、祖先在",重跑收敛,任何时刻无悬空 parent | +| 级联中某 id 已不在盘上 | 跳过(幂等续删);其余错误中止 | + +### `dsh-workspace` + +包拥有 `WorkspaceId` brand,暴露 `ctx.workspace`。记录 key 为生成的 uuid——path 不做 key:规范化会改写它,引用锚点必须稳定。 + +```ts ignore-check +export type WorkspaceId = Branded<'WorkspaceId'> +export function WorkspaceId(id: string): WorkspaceId + +const workspaceRecord = z.object({ + path: z.string(), // realpath,见下 + title: z.string(), + sessionIds: z.array(z.string().transform(SessionId)), + createdAt: z.string(), // ISO + updatedAt: z.string(), +}) +export type WorkspaceRecord = z.infer<typeof workspaceRecord> + +export const workspaceDomainSpec = defineDomain({ + name: 'workspace', version: 1, + tables: { workspaces: domainTable<WorkspaceId, WorkspaceRecord>(workspaceRecord) }, +}) + +declare module 'cordis' { interface Context { workspace: WorkspaceRegistry } } + +export interface Workspace { + readonly id: WorkspaceId + readonly path: string + readonly title: string + readonly sessionIds: readonly SessionId[] // 唯一真相且有序:数组序即展示序 + setTitle(title: string): Promise<void> + /** Record a session under this workspace (idempotent). Rejects when the session + * header's cwd (realpath) differs from this workspace's path. */ + attachSession(sessionId: SessionId): Promise<void> + detachSession(sessionId: SessionId): Promise<void> + /** Live directory check, uncached. */ + status(): Promise<'ok' | 'missing-dir'> +} + +export class WorkspaceRegistry extends Service { + constructor(ctx: Context) // super(ctx, 'workspace') + // start(): this.domain = await ctx.storage.domain.open(workspaceDomainSpec) + // 实体缓存 Map<WorkspaceId, WorkspaceEntity> 重建 + create(path: string, title?: string): Promise<Workspace> // realpath 后撞已有 → reject + get(id: WorkspaceId): Workspace | undefined + list(): Workspace[] + resolveByPath(path: string): Promise<Workspace | undefined> // 同 realpath 口径,故 async + // delete:future work(与 session 级联删一起做,见下);本期不提供任何删除入口 +} +``` + +- **path 规范**:落盘值 = `fs.realpath(输入)`(尾斜杠、`..`、符号链接全解析);唯一性 = 规范化后字符串相等(符号链接指向同一目录算撞)。目录不存在时 create 直接 reject(realpath 失败——workspace 必须指向存在目录;"Create new = 建目录"是上层交互,先 mkdir 再 create)。attach 校验的 session cwd 同口径。cwd 单值 + path 唯一 ⇒ 一个 session 结构上最多归属一个 workspace,双重记账写侧不可能。 +- **title**:显示名,默认 `basename(path)`,可改,允许重复。归属不用 cwd 派生兜底——cwd 表达不了排序,归属是 workspace 侧事实;headless 直开的 session 不属于任何 workspace。 +- 消费者只见 `Workspace` 接口,`WorkspaceEntity` 不出包(单实现不预拆 seam);实体按 id 唯一(registry 缓存),记录快照写后原地换新,外部只见 getter;所有写收敛到实体内 `mutate(fn)` → `table.update`,`updatedAt` 在 mutate 内统一刷。领域对象不过 RPC,下期 wire 层把记录投影成 zod wire schema。 +- **workspace 删除整体为 future work**(2026-07-24 拍板):本期 registry 不提供 delete 方法——半截的"只删记录留 session"语义不对外暴露,删除与 session 级联(`recursive` 参数、运行中检查、自底向上、崩溃重跑收敛)作为一个完整语义随 session 删除原语一起落地;届时顺序为逐个删 session → 摘账 → 删记录。 + +一致性口径(账 = 归属唯一依据;实现与测试基准): + +| 情形 | 行为 | +| --- | --- | +| 账中 id 盘上无 session | `list()`/实体投影时过滤;下次任何 mutate 顺手摘除;不报错(删除崩溃一致性的正常产物) | +| session cwd 匹配某 workspace 但未上账 | 不属于:不合并不收编。GUI 将来可做"游离 session"专区(游离 = 全部账的补集) | +| 同一 session 上两本账 | 写侧结构性堵死(attach 校验);load 检出 → throw(外部手改数据,不掩盖) | +| workspace 目录不存在 | 记录与账保留,`status()` = `'missing-dir'`;存储层不自动删(目录可能只是暂时挪走) | + +### 复用与 session 后端迁移展望 + +**长期方向**:session-persistence 的 JSONL/SQLite 后端里"纯介质操作"下沉到 `dsh-storage` 后端(session 包不删,`SessionPersistence` seam 与 coordinator 语义不动;动的只是它们脚下的文件/db 操作层)。复用的动机:介质层全是文件系统操作、数据库调用与跨平台兼容的脏活(Windows 权限与原子发布变体、fsync 语义、独占建文件……),这些只应写一遍;业务语义(session 怎么 append、何时 append、append 什么)留在上层——而"底下这次 append 是否正常完成"(持久性/原子性/平台正确性)是底层的责任,责任界面就是 facet 原语的契约。为此后端接口按**介质 owner + 数据形状 facet** 设计:session 日志是 append-only 流,与 KV 形状不同——强行统一进 KV 原语会两头变形,所以按 facet 分开(`kv` 本期、`log` 迁移期),介质与生命周期共享。 + +现状复用审计(迁移前就能看清的账): + +| session-persistence 现有逻辑 | 归属 | 处置 | +| --- | --- | --- | +| JSONL:temp 写 + fsync + link/unlink 原子发布、0o700/0o600 权限、Windows 变体(win32.ts) | 纯介质 | 本期 `dsh-storage-json` 直接抄用(整文件原子覆写正是同一套);迁移期成为共享实现 | +| JSONL:逐行 append、首行 header 快读、zstd 逐帧压缩 | log 形状 | 留在原地;迁移期进 `log` facet | +| SQLite:openDatabase(mkdir/独占建文件/PRAGMA 序列/user_version 检查) | 纯介质 | 本期 `dsh-storage-sqlite` 抄用——两处 openDatabase 已几乎逐行同构,本组是第三个使用者;先抄后提,提取放迁移期 | +| SQLite:events/sessions 表结构、同事务物化 | log 形状 | 留在原地;迁移期进 `log` facet | +| coordinator(per-id 写链、懒物化、崩溃修复、flush 屏障) | session 语义 | 永不下沉——事件日志的领域逻辑,对应物在 domain 层(写串行链),各归各 | +| encodeSegment(id 进路径转义) | 介质工具 | domain 侧 key 不进路径用不到;`log` facet(一 session 一文件)迁移时随之下沉 | + +**本期不改 session-persistence 的介质代码**(只加 delete 原语);上表是迁移期的施工清单,也是后端接口"必须装得下 log 形状"的设计依据。 + +### 测试矩阵 + +| 套件 | 覆盖 | 后端 | +| --- | --- | --- | +| backend 契约(共享套件,一次编写两端跑) | 七条契约 + 版本拒绝 + close 幂等 | json、sqlite(`:memory:` + 临时目录) | +| registry/mount | 重复注册、未挂载访问、disposer 摘除 | — | +| domain 层 | open 六步语义、schema 拒绝、update 串行(并发交错压测)、`domain/changed` 逐条、global 初值懒物化、路由与 `facet-unsupported` | 任一(json) | +| workspace | create/唯一性/realpath、attach 校验(含 sessionPersistence 缺席拒绝)、一致性口径四情形 | mock domain 或 json | +| session delete 契约(future work,随实施并入 runPersistenceContract) | 未知 id、已删 id 复用、未物化 intent、与在途 append 串行、deleted 事件 | jsonl、sqlite | + +快照:本期无模型可见面与组装面,不新增;下期 RPC 接线时随 `workspace.*` 域补。 + +### 不做清单 + +| 不做 | 触发条件 | 返工点 | 预埋 | +| --- | --- | --- | --- | +| 删除全套(`SessionPersistence.delete`、deleted 事件、`registry.delete` 级联、递归删、运行中检查) | future work 启动(GUI 需要删除交互前) | 按上文 future work 节实施:session 原语 + `registry.delete(id, { recursive? })` 一体落地 | 编排规则/拒绝清单已定案在本 Note;本期无任何删除入口,无半截语义要兼容 | +| `log` facet 与 session 后端迁移 | 本期后任意期启动 | 介质操作下沉(复用审计表即施工清单) | facet 结构已留位;两后端介质代码本期即按可下沉形状组织 | +| 多进程并发写保护 | 两 host 进程同写一介质 | JSON 后端文件锁;SQLite WAL 天然多进程 | 写全经 domain 单点串行,加锁只动后端 | +| 跨进程变更观测 | GUI 断线重连感知 | revision 模式(抄 session-persistence) | 进程内已有 `domain/changed` | +| 数据迁移 | 首个 tagged release 后模型再变 | 版本号驱动逐域迁移 | 版本号自第一天入介质 | +| 大表性能 | 千级记录域挂 json | `routes` 改指 sqlite,数据手工导一次 | 路由即配置,消费者零改动 | +| 多段 key | 两段 key 消费者出现(每 workspace 每 session 维度数据) | key 泛型换 tuple、SQLite 复合主键、JSON 嵌套层 | 一级表 = 段数 1 特例;不做任意深度嵌套;不拼字符串 key | +| scope 维度 | "每 workspace 一份"的域出现且复合 key 表达不动 | DomainSpec 加 scope + 文件名 scope 段(encodeSegment) | 名字字符集已收紧,文件名不冲突 | +| 跨表原子事务 | 同域两表一次原子操作需求 | `domain.transact(fn)`;JSON 天然原子,SQLite 包事务 | — | +| 二级索引/条件查询 | 内存过滤不动(万级记录) | SQLite JSON1 查 value 列,加只读 query 面 | JSON 后端不陪跑 | +| session 跨 workspace 移动 | 产品需求出现 | attach 校验放宽为"先 detach 后 attach"编排 | — | +| RPC/GUI/boot | 下期 | `workspace.*` + `session.delete` 端点、wire schema、boot 挂载、sidebar 接真数据 | 本期模型与语义即 wire 投影的直接来源 | + +## Alternatives considered + +- **复用 session-persistence 的 coordinator/后端**:事件日志语义(append-only、turn 崩溃修复、懒物化)与 KV 覆写语义不匹配;只借其分层思想(协调层持写序、后端只实现最小原语)。 +- **workspace 专用存储包,后续再抽 seam**:第二个消费者(session sidecar)已可预见,届时泛化要再动一次接口。 +- **domain 与 storage 合为一层**:后端会被迫接触 schema 校验、变更事件、写串行等领域关切;拆开后 storage 后端只做不透明原语(可替换面最小),domain 单实现收敛全部领域逻辑(zod/事件/串行化只写一遍,不随后端翻倍)。 +- **整库单后端二选一(学 session-persistence 单坑位模式)**:曾是初版方案;改为多后端并存 + 配置路由,因为存储枢纽要承载多种数据形式,不同形式/域对后端的偏好(肉眼可读 vs 高频点更新)注定分化,单坑位会逼出"整体换挂 + 手工导数据"的粗粒度动作。代价是按名查找多一步,fail-loud 兜底。 +- **JSON 后端 jsonl 追加 + 墓碑 + 压实**:temp+fsync+rename 的崩溃安全与 append 等价;覆写让文件永远是净值、肉眼可读,免掉折叠/压实/断行容错。域规模下整写与追加一行同量级。 +- **JSON 一表一文件**:覆写下文件粒度不影响写成本,按域合并文件更少,global 单例有落点。 +- **SQLite 整域存单行 blob**:任何一条记录变更都重写整域,失去按 key 精确更新——SQLite 相对 JSON 的唯一优势归零。 +- **SQLite 按 schema 生成 typed columns**:DDL 生成器过度建设;document-per-row 足够,查询需求出现再议。 +- **每域独立 sqlite db 文件**:与仓库一库多表惯例相反。 +- **path 作为 workspace key**:规范化/符号链接解析会改写 path;引用锚点必须稳定。 +- **归属用 cwd 派生(或与账合并)**:双真相源;cwd 表达不了排序;归属本就是 workspace 侧事实。 +- **变更事件带旧值**:仓库变更事件惯例是"新快照 + 操作判别"(唯一例外 fs 的 before/after 是方法返回值而非事件,因旧值事后不可重建且有 diff 消费者);需要 diff 的消费者自己持有上次快照。 +- **删除自动 cancel 运行中 session**:持久层/编排层反向牵动运行时,层次变脏;cancel 机制已存在,调用方组合即可。 + +## Acceptance criteria + +- 测试矩阵本期四套件全绿:backend 契约共享套件在 json/sqlite 双端、registry/mount disposer 语义、domain 层(含 open 六步与路由 fail-loud)、workspace 全语义(create/attach 校验/一致性口径)。 +- `ctx.workspace` 可在测试组装下完成 create → attach → list 生命周期(删除为 future work)。 +- session-persistence 包零 diff(本期不动 session 侧的验收线)。 +- 本期无新快照(无模型可见面与组装面);下期 RPC 接线时补。 + +## Risks + +- **仓库持久化面第一个推式变更事件**(session-persistence 靠 revision 轮询):形态虽有 `goal/changed` 范本,但"存储层发事件"是新先例,下期 RPC 消费时才能验证形态是否合适。 +- **JSON 后端整域覆写的规模前提**:若第二个消费者(session sidecar)在路由到 SQLite 前就以千级记录落在 JSON 后端,整写成本会先于预期显现;缓解即 `routes` 改指 sqlite。 +- **删除语义的编排层检查依赖 `ctx.sessions` 弱依赖**:headless 组装拿不到运行时注册表时按"无热 session"处理,存在窗口(外部进程正在跑该 session);多进程本就在不做清单内,接受。 +- **facet 泛化以未来的 `log` facet 为设计依据但本期不实现它**:存在"预留形状不合身"的风险;缓解是本期后端介质代码按复用审计表的下沉形状组织,`log` facet 真正落地时只动 facet 层。 diff --git a/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.i18n.yaml b/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.i18n.yaml new file mode 100644 index 0000000000..23961c33c7 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-30-pre-tool-input-rewrite.md: f35e6af465ce8cec5685911c43e12b8dd66f2e6a +2026-06-30-pre-tool-input-rewrite.zh.md: c94c647bb6867199b72528bc84c58a08ae93e27e diff --git a/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.md b/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.md index e6c5d9eb1e..f35e6af465 100644 --- a/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.md +++ b/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-06-30-pre-tool-input-rewrite.zh.md) + ## Problem The [interception-seams Agent Note](../../implemented/feature/2026-06-30-interception-seams.md) defines `tools/pre-execute` as an allow/deny/ask gate over an execution whose identity is already protected and whose arguments are deeply frozen. Claude Code's `PreToolUse` hook also offers `updatedInput`, so a faithful bridge needs an explicit rewrite mechanism. A rewrite cannot be a mutation escape hatch on the existing execution object: it must keep the durable history, audit record, presentation, and executed value consistent. @@ -12,7 +14,7 @@ In the loop, a tool call's arguments are committed to the log and read by live c 1. **`assistant/message`** is appended before tool dispatch — it is the model-history source `deriveMessages()` replays, so it carries the tool-call arguments the model itself emitted. 2. **`tool/call`** is the durable AUDIT record, appended before `ctx.tools.execute()`. -3. **Live presentation reads `tool/call.arguments`**: the ACP bridge remembers them and passes them to `presentResult`; `dsh-tool-bash` derives the card title, the rawInput, the cwd, and the terminal-vs-background treatment from them. +3. **Human-facing presentation reads `tool/call.arguments`**: UI renderers pass them to `presentResult`; `dsh-tool-bash` derives the card title, the rawInput, the cwd, and the terminal-vs-background treatment from them. An execution-only rewrite would make the UI show one command while another ran and render the result against the wrong arguments. The registry prevents that failure mode today: it structured-clones and deep-freezes `arguments`, makes the execution identity properties non-writable, and exposes no test shim or listener path that can replace them. The rewrite design must preserve that protected-identity boundary rather than weaken it. diff --git a/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.zh.md b/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.zh.md new file mode 100644 index 0000000000..c94c647bb6 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.zh.md @@ -0,0 +1,53 @@ +# Agent Note: 工具执行前输入重写——一致性设计 + +Status: proposed + +[English](2026-06-30-pre-tool-input-rewrite.md) | 中文 + +## 问题 + +[拦截 seam Agent Note(agent 决策记录)](../../implemented/feature/2026-06-30-interception-seams.md) 将 `tools/pre-execute` 定义为一道针对执行的允许/拒绝/询问门禁,此时执行的身份标识已受保护、参数已被深度冻结。Claude Code 的 `PreToolUse` 钩子还提供了 `updatedInput`,因此忠实的桥接需要一个显式的重写机制。重写不能是对现有执行对象的可变逃逸口:它必须保持持久化历史、审计记录、展示层与实际执行值之间的一致性。 + +## 问题本质:执行前参数的三个读取方 + +在 agent loop(智能体循环)中,工具调用的参数在工具执行之前就已提交到日志并被实时消费方读取: + +1. **`assistant/message`** 在工具分发之前追加——它是 `deriveMessages()` 回放时的模型历史来源,因此携带模型自身输出的工具调用参数。 +2. **`tool/call`** 是持久化的审计记录,在 `ctx.tools.execute()` 之前追加。 +3. **面向人类的展示读取 `tool/call.arguments`**:UI 渲染器将这些参数传给 `presentResult`;`dsh-tool-bash` 从中派生卡片标题、rawInput、cwd 以及终端/后台处理方式。 + +如果只做执行层面的重写,UI 会显示一条命令而实际运行的是另一条,并且结果会对着错误的参数渲染。注册表目前通过以下方式防止这种失败模式:对 `arguments` 做 structured-clone 并深度冻结,将执行身份属性设为不可写,且不暴露任何可替换它们的测试 shim 或监听路径。重写设计必须维护这一受保护的身份边界,而非削弱它。 + +## 提案 + +重写是一个「身份标识创建前的一致性事务」。当钩子提供 `updatedInput` 时,有效值必须在注册表构造其不可变的 `ToolExecution` 之前确定,并且必须原子地反映到全部三个读取方: + +- `tool/call` 审计事件记录重写后的参数(原始参数保留在一个伴随字段中,作为审计线索——钩子修改了调用,原始参数与生效参数都是值得保留的事实)。 +- 派生历史中的 `assistant/message` 必须与实际执行一致。待评估的选项:就地重写 assistant 消息中的工具调用块(改变模型「看到自己说了什么」),或记录一条单独的修正让下一次请求携带。Claude Code 的模型是让模型看到重写已生效。 +- 展示层(`presentCall`/`presentResult`)读取重写后的参数,使 UI 显示实际运行的内容。 + +在 `PreToolDecision` 当前的触发点上做扩展是不够的:此时两条持久化记录已经存在,执行身份已受保护。实现必须将相关决策移到日志提交之前,或者增加一个专门的、更早的重写决策点来处理待定的模型调用。agent loop 将生效参数提交到历史和审计之后,再构造普通的不可变执行对象,并照常运行现有的允许/拒绝/询问和工具流水线。 + +## 曾考虑的替代方案 + +### 为什么不直接修改执行对象? + +允许 pre-execute 监听器赋值 `exec.arguments` 只能提供执行层面的重写,模型历史、审计和展示层不会随之改变。保持身份标识受保护使得这种局部行为不可表达。在一致性事务实现之前,CC/Codex 桥接对 `updatedInput` 记录日志并发出警告,而非声称已兑现;循环分发点的 `TODO(pre-tool-input-rewrite)` 标记了缺失的更早阶段。 + +## 验收标准 + +- 请求的重写在 `ToolExecution` 身份标识创建之前解决,并原子地反映到全部三个读取方:`tool/call` 审计记录重写后的参数(原始参数保留在伴随字段中)、派生历史与实际执行一致、展示层渲染重写后的参数。 +- 生效的 `ToolExecution.arguments` 在 pre-policy、守卫、分发、post-policy 和最终观测全程保持深度冻结且不可写;不引入任何可变 shim。 +- CC/Codex 桥接兑现 `updatedInput`,不再记录忠实但降级的警告。 + +## 风险 + +- 重写 `assistant/message` 中的工具调用块会改变模型「看到自己说了什么」;是否有提供方在回放时拒绝这种改动,是一个需要通过实验确定的开放问题,必须在决策形状冻结之前解决。 +- 更早的重写阶段改变了 `assistant/message`、`tool/call`、钩子审计事件与执行之间的顺序关系;设计必须固定这一顺序,同时不削弱轮次封闭性或调用/结果邻接性。 + +## 开放问题 + +- 重写 `assistant/message` 中的工具调用块是否会破坏某些提供方在回放时的预期?还是单独的修正更安全? +- 原始参数是否应保留在 `tool/call` 事件(审计)上?如果是,放在什么字段? +- 重写决策是移到日志提交之前,还是成为一个专门的更早 seam?现有的 pre-tool 允许/拒绝钩子如何避免运行两次? +- 这与未来的权限 `ask` 流程(用户批准一个被重写的调用)如何交互? diff --git a/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.i18n.yaml b/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.i18n.yaml new file mode 100644 index 0000000000..ecb4e98def --- /dev/null +++ b/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-07-claude-code-and-codex-subagent-backends.md: ee8576f97a9fdef8c88dcad3a73f28b63ca3ebe1 +2026-07-07-claude-code-and-codex-subagent-backends.zh.md: 14e8dde04d9526aaffc0e58be049e13858362887 diff --git a/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.md b/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.md index 620f39c4a4..ee8576f97a 100644 --- a/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.md +++ b/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-07-07-claude-code-and-codex-subagent-backends.zh.md) + ## Problem The subagent seam ([the seam Agent Note](../../implemented/feature/2026-06-21-subagent-capability-seam.md)) hosts multiple named providers on `ctx.subagents`, and the ACP backend ([the ACP backend Agent Note](../../implemented/feature/2026-06-22-acp-subagent-backend.md)) proved the seam generalizes across a process boundary; its Future-providers section explicitly named the Codex app-server and the Claude Code Agent SDK as mechanically similar siblings. Those two are the engines actually worth delegating to today: a harness turn should be able to hand a self-contained task to a real Claude Code or a real Codex — a separate product with its own model, tools, and sandbox — and get back one final answer, without the parent deployment leaking its secrets into the child or the child's behavior silently depending on whatever `~/.claude` / `~/.codex` state exists on the host machine. diff --git a/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.zh.md b/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.zh.md new file mode 100644 index 0000000000..14e8dde04d --- /dev/null +++ b/.agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.zh.md @@ -0,0 +1,89 @@ +# Agent Note: Claude Code 与 Codex subagent 后端(向外部编码 agent(智能体)的进程外委派) + +Status: proposed + +[English](2026-07-07-claude-code-and-codex-subagent-backends.md) | 中文 + +## 问题 + +subagent seam([seam Agent Note(agent 决策记录)](../../implemented/feature/2026-06-21-subagent-capability-seam.md))在 `ctx.subagents` 上托管多个命名提供方,ACP(Agent Client Protocol)后端([ACP 后端 Agent Note](../../implemented/feature/2026-06-22-acp-subagent-backend.md))证明了该 seam 能跨越进程边界泛化;其「未来提供方」一节明确将 Codex app-server 与 Claude Code Agent SDK 列为机械上相似的兄弟。如今真正值得委派的就是这两个引擎:harness 的一个轮次应能把一个自包含任务交给真实的 Claude Code 或真实的 Codex——一个拥有自身模型、工具与沙箱的独立产品——并取回一个最终答案,同时父部署不向子进程泄漏密钥,子进程行为也不静默依赖宿主机上碰巧存在的 `~/.claude` / `~/.codex` 状态。 + +## 提案 + +两个兄弟提供方包(package),作为 ACP 后端的结构变体,另加一次提取: + +- `@deepseek-ai/dsh-subagent-claude-code`:通过 `@anthropic-ai/claude-agent-sdk` 的 `query()` 驱动一个 Claude Code 子进程(SDK 在父进程中运行,并将其内置的 `claude` CLI(命令行界面)作为子进程 spawn)。提供方名称为 `claude-code`:子进程是 Claude Code 这个*产品*,而非 Anthropic 模型适配器——「claude」保留给未来的 `dsh-llm` 适配器。 +- `@deepseek-ai/dsh-subagent-codex`:spawn `codex app-server`,通过其 JSON-RPC-over-stdio 协议驱动一个 thread/turn,使用包内一个手写的换行 JSON 客户端(约 200–300 行)。 +- `@deepseek-ai/dsh-subagent-process`:纯库(沿用 `subagent-inprocess` 的先例),提取 `dsh-subagent-acp` 已有且两个新后端都需要的内容:凭证环境清洗(`buildChildEnv`)、EOF → SIGTERM → SIGKILL 的 dispose(资源释放)阶梯,以及新的隔离配置目录辅助函数(`mkdtemp` 创建、尽力删除)。ACP 后端迁移到该库上;`bash-local` 的兄弟副本保持不动以限制变更范围。 + +两个提供方逐字复制 ACP 后端的 seam 姿态:每次 `start` 创建全新子进程、恰好一次提示词往返、所有能力均为 `false`、`inheritsParentContext: false`、忽略 `request.parent`/`request.agentOptions`、`id = SessionId(randomUUID())`,且 `result` 从不 reject——子进程级失败扁平化为 stop reason,原始错误则通过 `onError` spec 回调送到 `ctx.logger`。模型暴露无需新代码:每个提供方各加载一次 `dsh-tool-subagent`,使用不同的 `toolName`(`subagent_claude_code`、`subagent_codex`)。无需新的会话事件——唯一的模型可见产物是工具结果,因此可重建性与 ACP 完全相同。明确边界:会话日志重建模型可见的 transcript(文本记录),而不是工作区变更历史——获准写入的子进程将文件作为日志之外的环境副作用进行修改,与 bash 工具和 ACP 后端现有行为完全一致;回放复现请求,而非磁盘。 + +## 已验证的接口事实(固定版本) + +两个集成面在本提案之前均已针对固定版本进行了验证——阅读类型与打包源码、运行无需密钥的 spike——而非仅依赖厂商文档。固定版本是验证基线,不是运行时契约:后端不执行运行时版本探测(无 `codex --version` 门禁、无 SDK 版本嗅探)。兼容性在开发时强制执行——每次依赖升级都会针对真实加载路径重跑无密钥套件——在运行时则通过大声失败来保障:协议层面的意外通过 `onError` 结算为 `error`,绝不静默异常。 + +**`@anthropic-ai/claude-agent-sdk` 0.3.202。** `options.env` 会替换子进程环境(不与 `process.env` 合并),恰好满足清洗需求。`settingSources` 默认加载所有文件系统设置——隔离要求显式传入 `[]`。结果子类型为 `success` | `error_during_execution` | `error_max_turns` | `error_max_budget_usd` | `error_max_structured_output_retries`。中止时 SDK 自行逐级加强对 CLI 子进程的终止措施:立即关闭 stdin,约 2 秒后若子进程未退出则发送 SIGTERM(已观察到;无残留进程)——无需自定义 kill 回退。`outputFormat: {type: 'json_schema'}` 和 `agents` 选项已存在,为 seam 的 `outputSchema` 能力和命名 subagent 类型提供了未来着陆点;两者均不在本 Agent Note 范围内。 + +**codex CLI 0.142.5,`codex app-server`(v2 词汇)。** LF 分隔的 JSON,JSON-RPC 2.0 形状但省略 `"jsonrpc"` 头。 + +- 生命周期:`initialize{clientInfo}` + `initialized` → `thread/start`(接受 `cwd`、`model`、`sandbox`、`approvalPolicy`、`ephemeral`;未认证即可成功)→ `turn/start{threadId, input:[{type:'text',text}]}` 立即返回一个 `inProgress` 的轮次;终止信号是携带 `Turn{status: completed|interrupted|failed|inProgress, error}` 的 `turn/completed` 通知。 +- 审批是服务端发起的请求——`item/commandExecution/requestApproval`、`item/fileChange/requestApproval`、`item/permissions/requestApproval`、`item/tool/requestUserInput`、`mcpServer/elicitation/request`——以 `accept`/`decline` 系列决策应答。 +- 认证:`account/login/start{type:'apiKey', apiKey}` 是一等 RPC,`account/read` 报告 `requiresOpenaiAuth`——且未认证的 `turn/start` 不会快速失败(它会挂在重试中),因此后端必须预检认证状态,并在失败时大声结算为 `error`,而非等待轮次。 +- 隔离:`CODEX_HOME` 重定向被尊重(`initialize` 响应会回显它,测试可据此断言隔离),`ephemeral: true` 的 thread 不留任何会话文件。 + +## 隔离与凭证 + +部署只使用 API key 认证,子进程不得看到宿主用户的 Claude Code / Codex 配置:行为必须只由 `cordis.yml` 决定。每次运行获得一个全新的 `mkdtemp` 配置目录——Claude Code 使用 `CLAUDE_CONFIG_DIR`(并显式设置 `settingSources: []`),Codex 使用 `CODEX_HOME`——dispose 时尽力删除;配置字段也可以固定一个持久目录。子进程环境通过提取逐字复用 ACP 后端的 `buildChildEnv` 语义:转发环境变量,但移除凭证形态的变量(`/KEY|SECRET|TOKEN/i`),再叠加 `config.env`——因此 `PATH`、`HOME`、`TMPDIR`、locale 和代理变量保留,CLI 正常运行;只有环境中的凭证形态变量被清洗(Claude Code 的 `ANTHROPIC_API_KEY` 通过 `config.env` 显式进入),Codex key 则通过 `account/login/start` RPC 进入隔离的 `CODEX_HOME`,而非手写 `auth.json`。 + +## 权限与审批策略 + +每个后端不压缩为 ACP 单一的 `permission: allow|reject` 旋钮,而把引擎原生词汇作为配置暴露,并采用保守默认值:Claude Code 获得 `permissionMode`(默认 `default`)以及 `permission: allow|reject`(默认 `reject`),后者作为所有漏过请求的 `canUseTool` 自动应答;Codex 获得 `sandboxMode`(默认 `read-only`)和 `approvalPolicy`(默认 `never`),以及同一个 `permission` 后备值,用来应答仍然到达的审批请求。默认值刻意做到不造成损害(开箱即用的子进程无法写文件);示例演示如何开放权限(`acceptEdits` / `workspace-write`)。机械规则是:每一个服务端发起的请求都由程序迅速结算——枚举出的审批/用户输入/elicitation 请求按配置策略应答,未知请求方法用 JSON-RPC method-not-found 错误响应(绝不保持 pending),未知通知被消费——因此任何子进程请求都不会因等待永远不会到来的应答而卡住轮次。这一版中提示词不会到达人类,与 ACP 一致。 + +## StopReason 映射 + +Claude Code:`success` → `completed`;`error_max_turns`、`error_during_execution`、`error_max_budget_usd`、`error_max_structured_output_retries` → `error`(与 ACP 对 `max_turn_requests` 的处理对齐:未完成的任务不是成功);生成器中止 → `aborted`;未知值 → `error`。Codex:`Turn.status` 为 `completed` → `completed`;`interrupted` → `aborted`;`failed` 且 `codexErrorInfo: 'contextWindowExceeded'` → `max-tokens`,其他 `failed` → `error`;传输/spawn/认证预检失败 → `error`(若已请求取消则为 `aborted`)。两者中,`cancel()` 采用 ACP 形状:标志位 + abort/interrupt + 一个 cancel-settled 竞争分支,使不合作的子进程无法阻塞结果。 + +活性姿态,明确声明:teardown 时序是配置项,轮次时长不是。两个后端将 dispose 阶梯的宽限期作为带默认值的已验证配置字段(ACP 后端的 `disposeEofGraceMs`/`disposeGraceMs` 形状,由提取库承载),但刻意不设轮次时长或启动超时——与 ACP 一致:轮次期间的活性由调用方通过 `cancel()`/abort signal 掌控,subagent 轮次持续数分钟也属合理,而 Codex 认证预检消除了唯一已验证的必然挂起场景;需要墙钟上限的部署从父侧取消即可。 + +## 测试 + +依照根 AGENTS.md 规则在每个层级明确命名,并预先消除风险: + +- **无密钥单元/集成测试**:每个后端都镜像 ACP spec 清单(往返和输出累积、每种 stop 映射、两条取消路径、已中止、两种策略下的权限自动应答、未知消息容错、错误命令的 spawn 失败、HMR(热模块替换)提供方清理、导出形状、子进程环境隔离断言和临时目录删除;Codex 另加认证预检失败路径)。Claude Code harness 是通过 `pathToClaudeCodeExecutable` 接入真实 SDK 的脚本化假 `claude` 可执行文件——一个 spike 已在 24ms 内完成端到端无密钥验证(假 CLI 应答一次 `control_request/initialize`,并讲 plain stream-json,约 40 行)。Codex harness 是讲已验证协议格式的脚本化 mock app-server 子进程,沿用 `mock-acp-server.ts` 形状。 +- **有密钥 e2e 测试**:每个后端的真实引擎执行并由磁盘验证真实文件工作,固定使用开放后的配置,以免验收与不造成损害的默认值冲突——Claude Code 使用 `permissionMode: 'acceptEdits'`,Codex 使用 `sandboxMode: 'workspace-write'` + `approvalPolicy: 'never'`;自跳过会准确报告缺失的是二进制还是 key。CI 没有密钥,因此依照有密钥策略在本地运行。 +- **快照测试**:以 `TODO(claude-code-subagent-replay)` / `TODO(codex-subagent-replay)` 推迟——即 ACP 后端也推迟的独立回放形状([按会话回放 Agent Note](../../implemented/testing/2026-06-22-subagent-snapshot-replay.md));在此期间由无密钥套件提供确定性覆盖。 + +## 曾考虑的替代方案 + +### 为什么不用官方 `@openai/codex-sdk` 而手写客户端? + +dispose 阶梯和环境清洗要求拥有子进程(spawn 参数、env、信号、exit 等待);SDK 隐藏了进程。协议格式(wire format)极其简单(LF JSON),形状可按固定版本生成(`codex app-server generate-json-schema`),仓库先例(`hook-protocol`)是拥有薄协议核心而非包装他人的运行时。SDK 能节省协议演进的维护成本,但代价是失去本后端存在的意义所在的精确控制。 + +### 为什么不用模型可见的 `subagent_type` 参数(单一 Task 风格工具)? + +Claude Code 自身的 Task 工具将 subagent 类型放在模型可见的 schema 中,选择一个提示词 + 工具集人格。这里的选择是在执行引擎之间做出的,而只有部署者知道哪些引擎配置了凭证——因此选择留在部署配置层,保持 `dsh-tool-subagent` 文档中的「一个提供方对应一个工具」契约。人格风格的类型选择器应是针对工具的另一个 Agent Note,而非针对后端。 + +### 为什么不用登录态凭证和用户自身的配置? + +继承 `~/.claude` / `~/.codex`(订阅登录、用户设置、skill(技能)、MCP 服务器)会使子进程行为依赖宿主机状态,并在 ACP 后端和 bash 执行器确立的「凭证通过 `config.env` 显式进入,绝不隐式继承」规则上打开一个隐式例外。仅 API key 加强制配置目录隔离使运行可复现;需要共享状态的部署可以有意将配置目录字段指向一个持久目录。 + +### 为什么不为 Claude Code 无密钥测试注入驱动层 seam? + +注入假的 `query()` 会 mock 我们自己的边界,使真实 SDK 加载路径未被测试(docs/testing.md 中的 real-over-mock 策略)。曾考虑此方案的风险——SDK↔CLI 的 stream-json 控制协议是内部实现——已被 spike 消除:假 CLI harness 今天能对真实固定版本的 SDK 正常工作。如果 SDK 升级破坏了 mock,无密钥套件会让升级 PR(Pull Request)失败,这正是门禁在发挥作用。 + +### 为什么不用 ACP 适配器(如 `claude-code-acp`)复用既有后端? + +社区 shim 将两个引擎包装为 ACP,这会使它们在 `dsh-subagent-acp` 上变成「仅配置」。但这在 harness 与引擎之间插入了一个非官方的第三方层,抹去了本 Agent Note 暴露的原生控制面(permissionMode、sandboxMode/approvalPolicy、配置目录隔离、apiKey RPC),并以 shim 的发布节奏替换了第一方协议的稳定性。第一方接口——Agent SDK 和 app-server——才是受支持的集成点。 + +## 验收标准 + +在两个引擎和密钥均已配置的机器上:一个 REPL 驱动的模型通过 `subagent_claude_code` 完成一个真实文件任务,通过 `subagent_codex` 完成另一个,工具结果为子进程的最终答案,父会话日志中仅有 `tool/call` + `tool/result`。无密钥套件在无凭证环境下以逐文件 100% 覆盖率通过,断言隔离(清洗后的子进程环境、dispose 后无残留临时配置目录),并断言 `~/.claude` / `~/.codex` 的存在与否不影响子进程行为。取消父轮次后,两个后端在有界时间内完全停稳,无残留子进程。e2e 套件干净地自跳过,命名缺失的前置条件。 + +## 风险 + +- `codex app-server` 被 CLI 标记为实验性,其 v1/v2 词汇共存;客户端固定 0.142.5、仅实现 v2、对未知方法/通知消费而不崩溃,但未来 codex 升级仍可能迫使返工(每次升级重新生成 schema 并重跑无密钥套件——这是上述「不做运行时版本探测」立场背后的开发时强制执行)。 +- Claude Code 假 CLI mock 依赖一个内部协议:任何 SDK 升级都必须通过无密钥套件,控制协议的破坏性变更意味着返工 mock(回退方案:上面否决的驱动注入 seam 成为逃生舱口)。 +- SDK 的 optionalDependencies 每平台约 280MB——已接受,限制在单个后端包内。 +- SDK 的 SIGKILL 分支(EOF→SIGTERM 之后)未被观察到,信任其实现;e2e 保留无残留进程断言。 +- Codex 是部署前置条件(无 npm 内置二进制);缺失或不兼容的二进制以大声的 spawn/协议 `error` 呈现,而非版本探测。 +- 每次运行付出一个全新子进程的代价,且仅最终答案浮出——思考、工具卡片和用量被消费后丢弃;连接池、中间进度浮出、`sendMessage`/`resume`、通过 SDK 的 `outputFormat` 实现 `outputSchema`、以及通过 SDK 的 `agents` 选项实现命名 subagent 类型,均为刻意推迟。 diff --git a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.i18n.yaml b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.i18n.yaml new file mode 100644 index 0000000000..b815cfdd2a --- /dev/null +++ b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-08-interactive-side-sessions.md: dfd325babe215782c9c1cbec3fd9f874783af7ab +2026-07-08-interactive-side-sessions.zh.md: 9bc9d5c94fdef893134844551a594acc39a99d3b diff --git a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.md b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.md index f2e3e74ca1..dfd325babe 100644 --- a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.md +++ b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-07-08-interactive-side-sessions.zh.md) + ## Problem A user may want to explore a question from a live session without changing its main context. Existing primitives do not expose that product shape: [session-store fork](../../implemented/feature/2026-06-30-session-store-fork-api.md) creates an unattached session, while [fork subagents](../../implemented/feature/2026-06-21-subagent-capability-seam.md) are model-driven tasks whose transcript collapses into one tool result. Neither gives the user a separate conversation, and neither records a conclusion back into the parent with provenance. diff --git a/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.zh.md b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.zh.md new file mode 100644 index 0000000000..9bc9d5c94f --- /dev/null +++ b/.agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.zh.md @@ -0,0 +1,41 @@ +# Agent Note: 交互式侧会话与合并回写 + +Status: proposed + +[English](2026-07-08-interactive-side-sessions.md) | 中文 + +## 问题 + +用户可能希望在不改变当前会话主上下文的前提下,探索一个来自活跃会话的问题。现有原语无法提供这种产品形态:[会话存储 fork](../../implemented/feature/2026-06-30-session-store-fork-api.md)创建的是一个无关联的会话,而 [fork subagent](../../implemented/feature/2026-06-21-subagent-capability-seam.md)是模型驱动的任务,其 transcript(文本记录)会折叠为一条工具结果。两者都不能给用户一个独立的对话,也都不能将结论带着出处信息记录回父会话。 + +## 提案 + +**侧会话(side session)** 是一个普通的活跃会话,从源会话的最后一个已完成轮次 fork 而来,绑定到自己的 agent(智能体),定位为只读顾问,并能**合并回写**一条精简笔记。 + +- **Fork 并绑定:** 以父会话的平衡已完成轮次前缀创建子会话,并在其元数据中标记 `parentSession` 与 `seedLength`。这组合了 `ctx.agents.create({ seed, meta })`;不新增核心服务或会话存储方法。 +- **顾问定位:** 创建后注入一条插件来源的 `context/message`,告知子会话只做解释,不执行变更或继续任务。保持系统提示词逐字节一致,可在继承的历史上保留提供方的前缀缓存。 +- **合并回写:** 向子会话请求一条有长度上限的 handback,然后向父会话注入一条插件来源的 `context/message`。父会话的下一次请求在其日志位置看到该消息,保持回放与[请求可重建性](../../implemented/architecture/2026-07-05-reconstructable-requests.md),无需新增会话事件。 +- **呈现:** 调用方式、会话切换与 handback 渲染属于首个客户端拥有的界面。本 Agent Note(agent 决策记录)仅规定与界面无关的机制。 + +回退产品化、会话树视图、面向模型的侧会话工具,以及 `forkName`/`mergedInto` 元数据均不在本 Agent Note 范围内。一次真实适配器 spike 已验证了源日志隔离、继承上下文、多轮子会话交互,以及合并回写在父会话下一轮次中的可见性。 + +## 曾考虑的替代方案 + +- **使用 subagent seam:** 否决。侧会话是用户驱动的、客户端可见的,且可能存活超过父会话的一个轮次;subagent 是模型驱动的运行,返回一条工具结果。 +- **修改子会话的系统提示词:** 默认否决,因为任何字节变化都会从第零个 token 起使前缀缓存失效。部署方仍可选择这种更强的隔离方式。 +- **新增 `sidechat/*` 事件:** 延后。插件来源的 `context/message` 已提供持久性、出处与回放能力;只有当某个界面需要差异化渲染时,专用事件才有正当理由。 +- **现在就绑定一个协议界面:** 否决。当前 UI 由客户端拥有。实时呈现最终必须从持久消息派生,以使回放渲染出相同的记录。 + +## 验收标准 + +- Fork 不改变源会话,创建的子会话具有平衡的已完成轮次前缀、`parentSession`、`seedLength`,以及逐字节一致的系统提示词。 +- 顾问定位在子会话追加历史的头部恰好添加一条插件来源的 `context/message`,而非修改其系统提示词。 +- 合并回写恰好添加一条有长度上限的 `context/message`,来源为 `plugin: sidechat`;父会话的下一次请求与回放在相同位置看到它。 +- 父会话与子会话并发运行,日志和流之间无串扰。 +- 单元测试覆盖 fork/attach 与合并回写;快照覆盖率随首个绑定界面一起落地。 + +## 风险 + +- 只读行为在 `tools/pre-execute` 拒绝门禁强制执行之前仅为建议性质;[拦截 seam](../../implemented/feature/2026-06-30-interception-seams.md) 可在不改变本机制的前提下添加该门禁。 +- 经过压缩(compaction)的源会话 fork 出的是其压缩视图,因此绑定的界面应当告知用户子会话继承的是摘要而非被替换的轮次。 +- 反复的 handback 会消耗父会话上下文。每次合并的长度上限约束了单条笔记的大小;后续的合并整理属于上下文压缩的职责。 diff --git a/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.i18n.yaml b/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.i18n.yaml index f64160a5a0..b2f1ade046 100644 --- a/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.i18n.yaml +++ b/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.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 -2026-07-14-sdk-developer-projects.md: aa5cf64d7dd33dea229d74c2ae45a9244ee70e3c -2026-07-14-sdk-developer-projects.zh.md: 8f7d1de5b16f38019c802f07eda701cee72deb4f +2026-07-14-sdk-developer-projects.md: 65d2bf66232993222832eb0f2f4f56cfcf7afd16 +2026-07-14-sdk-developer-projects.zh.md: 8435a07d9b2545a8f41a1f96743c9c7e6d4daf3d diff --git a/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.md b/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.md index aa5cf64d7d..65d2bf6623 100644 --- a/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.md +++ b/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.md @@ -59,7 +59,7 @@ The table is the developer-visible support set for this phase. A `required` feat | `hooks` | optional | `claude` (default) / `codex`, multiple | Each feature option creates a separate editable configuration file | | `guard` | optional | `repeat-tool` | Provides repeated-tool-call reminders | | `timeout-policy` | optional | `default` | Applies a uniform policy to tools that declare timeout budgets | -| `ask-user` | optional | `default` | Provides the `ask_user_question` tool; only `acp` and `tui` can select it because those two feature options provide the injected user-interaction service | +| `ask-user` | optional | `default` | Provides the `ask_user_question` tool; only `tui` can select it because ACP is an automation transport and embed provides no human-interaction service | Both `bash` feature options apply to ACP, TUI, and embed and are not selected by the run interface. The sandbox feature option writes no active config key and therefore keeps `dsh-bash-sandbox`'s `read-only` default. Generated `cordis.yml` includes a commented example that developers can change explicitly to `workspace-write`: @@ -107,7 +107,7 @@ Generated `package.json` provides the following scripts. `dev`, `build`, `start` `dsh-sdk start` and `dsh-sdk dev` accept a module target and forward arguments after `--` unchanged to the project entrypoint. Generic argument parsing uses Node `parseArgs()` with zero schema: valued flags use `--key=value`, bare flags become `true`, and `--no-*` becomes `false`. - TUI projects pass the selected model through `--model=<name>` and create or resume an agent according to optional `--resume=<session-id>`; -- ACP uses protocol `session/load` +- ACP clients create fresh sessions through protocol `session/new`; - Embed uses the model written into the generated code. Each feature-owned Cordis config entry keeps its developer-editable Cordis plugin config and explanatory comments in `cordis.yml`. When `dsh-sdk config` changes other features, it preserves unknown fields, formatting on untouched nodes, and comments. HMR is an ordinary leaf config entry: when the feature is selected, dev and start load the same watcher, and the command does not change the plugin tree implicitly. diff --git a/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.zh.md b/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.zh.md index 8f7d1de5b1..8435a07d9b 100644 --- a/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.zh.md +++ b/.agents/notes/proposed/feature/2026-07-14-sdk-developer-projects.zh.md @@ -59,7 +59,7 @@ create 还提供一次 `none / plugin / tool` 选择。`plugin` 固定生成 `pl | `hooks` | optional | `claude`(默认)/ `codex`,可多选 | 各功能选项生成独立的可编辑配置文件 | | `guard` | optional | `repeat-tool` | 提供重复工具调用提醒 | | `timeout-policy` | optional | `default` | 对声明超时预算的工具执行统一策略 | -| `ask-user` | optional | `default` | 提供 `ask_user_question` 工具;注入的 user-interaction 服务由 acp/tui 两个功能选项提供,因此仅这两个接口可选 | +| `ask-user` | optional | `default` | 提供 `ask_user_question` 工具;只有 `tui` 可选,因为 ACP 是自动化传输,而 embed 不提供人类交互服务 | `bash` 的两个功能选项都适用于 ACP、TUI 和 embed,不由运行接口决定。sandbox 功能选项不写任何生效的配置键,因而沿用 `dsh-bash-sandbox` 的 `read-only` 默认值;生成的 `cordis.yml` 保留注释示例,开发者可以显式改为 `workspace-write`: @@ -107,7 +107,7 @@ my-agent/ `dsh-sdk start` 与 `dsh-sdk dev` 可以接收模块 target,并把 `--` 后的参数原样转发给工程入口。通用参数解析使用 Node `parseArgs()` 的零 schema 模式:带值 flag 采用 `--key=value`,bare flag 转换为 `true`,`--no-*` 转换为 `false`。 - TUI 工程通过 `--model=<name>` 传入所选 model,并根据可选的 `--resume=<session-id>` 创建或恢复 agent; -- acp 使用协议 `session/load` +- ACP 客户端通过协议 `session/new` 创建全新会话; - embed 使用生成代码中的 model。 每个功能拥有的 Cordis 配置项在 `cordis.yml` 中保留自己的可编辑 Cordis 插件配置和说明注释;`dsh-sdk config` 修改其他功能时必须保留未知字段、未修改节点的格式和注释。HMR(热模块替换)是普通叶子配置项:选择该功能后,dev 和 start 加载同一个 watcher,命令不隐式改变插件树。 diff --git a/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.i18n.yaml b/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.i18n.yaml new file mode 100644 index 0000000000..8f00d8b537 --- /dev/null +++ b/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-api-extractor-reports.md: f110bfe3353e65442f218336aca3e9d492ac2341 +2026-06-11-api-extractor-reports.zh.md: 8cb7353e10a8811b20ccd539de15f8e06b76e6ae diff --git a/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.md b/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.md index b32dc7e2af..f110bfe335 100644 --- a/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.md +++ b/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-06-11-api-extractor-reports.zh.md) + > Split out from the original "Doc-sync and API reports" Agent Note (2026-06-11). Parts 1-2 (doc-block typechecking, event-taxonomy verification) shipped — see [doc-sync enforcement](../../implemented/process/2026-06-11-doc-sync-enforcement.md). This is the deferred part 3, kept as a standalone proposal. ## Problem diff --git a/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.zh.md b/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.zh.md new file mode 100644 index 0000000000..8cb7353e10 --- /dev/null +++ b/.agents/notes/proposed/process/2026-06-11-api-extractor-reports.zh.md @@ -0,0 +1,32 @@ +# Agent Note: API extractor 报告 + +Status: proposed + +[English](2026-06-11-api-extractor-reports.md) | 中文 + +> 从最初的「doc-sync(文档同步门禁)与 API 报告」Agent Note(agent 决策记录)中拆出(首次提出于 2026-06-11)。第 1 至第 2 部分(文档块类型检查、事件分类体系校验)已交付,见 [doc-sync 强制](../../implemented/process/2026-06-11-doc-sync-enforcement.md)。本文是被推迟的第 3 部分,作为独立提案保留。 + +## 问题 + +公开 API 的变更是不可见的:没有任何机制将「此次提交改变了公开接口」变为一个显式、可评审的事实。评审者阅读 diff 时可能遗漏某个导出类型新增了字段,或某个方法签名发生了变化。 + +## 提案 + +使用 api-extractor(或 `tsc --emitDeclarationOnly` 加一份规范化的公开接口导出)为每个包(package)生成一份签入仓库的 `etc/<pkg>.api.md`;CI 在重新生成结果与已签入报告不一致时失败。这样,每一次公开 API 变更都会成为评审者(或评审 agent(智能体))必须看到的一行 diff。 + +## 曾考虑的替代方案 + +**`tsc --emitDeclarationOnly` 加规范化的公开接口导出**:如果 api-extractor 过于笨重,这是更轻量的机制;两者都能满足提案所需的「签入仓库、可 diff」的报告形态。 + +## 验收标准 + +- 每个包都有一份签入仓库的 `etc/<pkg>.api.md`;CI 在重新生成结果与已提交报告不一致时失败。 +- 公开 API 变更(新增导出、字段放宽、签名变化)在评审中以报告 diff 行的形式可见。 + +## 风险 + +该依赖笨重且难以调教(这正是它被推迟的原因),且报告格式会随编译器升级而变动,增加一个维护面;在各包尚未发布的阶段,收益有限。 + +## 推迟原因 + +在 doc-sync 落地时被推迟:对于一个内部 monorepo,评审者已经能看到源码 diff,价值不高;且依赖笨重、难以调教。如果各包将来对外发布,再重新评估——届时一份稳定、可 diff 的公开接口报告才值得其维护成本。 diff --git a/.agents/notes/proposed/process/2026-06-11-architectural-conformance.i18n.yaml b/.agents/notes/proposed/process/2026-06-11-architectural-conformance.i18n.yaml new file mode 100644 index 0000000000..624b671a37 --- /dev/null +++ b/.agents/notes/proposed/process/2026-06-11-architectural-conformance.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-architectural-conformance.md: f7cb0d7397d4e03df225f68417da43b1fec8de62 +2026-06-11-architectural-conformance.zh.md: aa25ef6d2772642885ef268bd548fc6dad40d3cf diff --git a/.agents/notes/proposed/process/2026-06-11-architectural-conformance.md b/.agents/notes/proposed/process/2026-06-11-architectural-conformance.md index 006aa76ad1..f7cb0d7397 100644 --- a/.agents/notes/proposed/process/2026-06-11-architectural-conformance.md +++ b/.agents/notes/proposed/process/2026-06-11-architectural-conformance.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-06-11-architectural-conformance.zh.md) + ## Problem Two architectural guarantees currently live only in prose: (1) nothing depends on the concrete loop package ([the microkernel promise](../../implemented/architecture/2026-06-11-microkernel-event-taxonomy.md)), and (2) every LlmAdapter speaks the chunk protocol correctly. Both should be mechanical ([the quality-gates principle](../../implemented/process/2026-06-11-quality-gates.md)). diff --git a/.agents/notes/proposed/process/2026-06-11-architectural-conformance.zh.md b/.agents/notes/proposed/process/2026-06-11-architectural-conformance.zh.md new file mode 100644 index 0000000000..aa25ef6d27 --- /dev/null +++ b/.agents/notes/proposed/process/2026-06-11-architectural-conformance.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 架构一致性——依赖规则与适配器套件 + +Status: proposed + +[English](2026-06-11-architectural-conformance.md) | 中文 + +## 问题 + +目前有两项架构保证仅存在于行文中:(1)没有任何组件依赖具体的 loop 包(package)([微内核承诺](../../implemented/architecture/2026-06-11-microkernel-event-taxonomy.md));(2)每个 LlmAdapter 都正确遵循分片协议。二者都应由机制强制执行([质量门禁原则](../../implemented/process/2026-06-11-quality-gates.md))。 + +## 提案 + +**dependency-cruiser** 配合以下规则: + +- `packages/*`(除 agent-loop(智能体循环)自身的 tests 和 examples/ 外)禁止导入 `@deepseek-ai/dsh-agent-loop`。 +- 禁止跨包深层导入(`@deepseek-ai/dsh-*/src/...` 路径)——只允许使用公开入口点。 +- packages/ 内禁止导入循环。 +- `vendor/*` 禁止从 `packages/*` 导入。 +- 分层:dsh-llm 不导入其他 dsh 包;dsh-session 仅导入 dsh-llm;以此类推(packages/README.md 中的依赖表,强制执行)。 + +**适配器一致性套件**位于 dsh-llm(`@deepseek-ai/dsh-llm/conformance`):一个以适配器工厂为参数的可复用 vitest 套件,用于断言分片协议契约,包括每个块内的索引单调递增、某个索引出现 `block-end` 后不再接收增量、恰好出现一个 `finish`、用量至多出现一次、每个 `tool-call-delta` 都携带调用 id,并且及时响应 abort。当前先对 mock 运行;DeepSeek V4 适配器从第一天起继承该套件。还可以选择提供开发模式下的 `strictAdapter()` 包装层,在调试标志开启时于运行时强制执行相同规则(与 [开发模式不变式](../../implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md) 配对)。 + +## 计划 + +先落地 dependency-cruiser 配置与 CI 步骤(约一小时工作量,换来永久保证);一致性套件随其首个消费方测试(针对 MockAdapter)一起落地,并作为 V4 适配器阶段的前置条件。 + +## 验收标准 + +- dependency-cruiser 在 CI 中运行上述规则族;违规导入导致构建失败。 +- 一致性套件对 mock 适配器和两个正式适配器运行,新适配器包通过调用该套件并传入自己的工厂即可继承测试。 + +## 风险 + +随着包的增加,dep-cruiser 规则需要维护——规则应基于模式(`dsh-*`)而非逐一枚举。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.i18n.yaml b/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.i18n.yaml new file mode 100644 index 0000000000..bf98665195 --- /dev/null +++ b/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-supply-chain-and-vendor-drift.md: a27ae64556dc7366279824f1480e5681b1e86bf1 +2026-06-11-supply-chain-and-vendor-drift.zh.md: 25c27650709faf1a462ce9779ee6f0a909746311 diff --git a/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.md b/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.md index a79f719751..a27ae64556 100644 --- a/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.md +++ b/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-06-11-supply-chain-and-vendor-drift.zh.md) + ## Problem The vendor manifest ([the vendoring decision](../../implemented/process/2026-06-11-vendor-cordis-as-source.md)) is enforced at commit time in the *forward* direction (vendored change ⇒ manifest update) but nothing verifies the manifest's *claims*: that vendor/ actually equals upstream-at-SHA plus exactly the logged modifications. And the handful of true npm dependencies have no advisory monitoring or update cadence. diff --git a/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.zh.md b/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.zh.md new file mode 100644 index 0000000000..25c2765070 --- /dev/null +++ b/.agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 供应链检查与 vendor 漂移验证 + +Status: proposed + +[English](2026-06-11-supply-chain-and-vendor-drift.md) | 中文 + +## 问题 + +vendor manifest(元数据清单)(见[引入 vendor 的决策](../../implemented/process/2026-06-11-vendor-cordis-as-source.md))在提交时仅在*正向*强制执行(vendor 变更 ⇒ manifest 更新),但没有任何机制验证 manifest 的*声明*:即 vendor/ 确实等于上游指定 SHA 的内容加上所记录的修改。此外,少量真正的 npm 依赖也没有安全公告监控或更新节奏。 + +## 提案 + +1. **Vendor 漂移检查**(夜间 CI):以 manifest 中记录的 SHA 浅克隆上游仓库,复制对应的包(package)源码,与 `vendor/*/src` 做 diff。除非 diff 与已记录的本地修改一致(每项修改以签入的 patch 文件保存——日志条目从行文描述变为可验证的产物),否则任务失败。 +2. **依赖安全公告**:对 lockfile 运行 osv-scanner(或 `pnpm audit`),按计划定期执行,并在涉及 lockfile 变更的 PR(Pull Request)上触发。 +3. **许可证清单**:一个脚本断言每个 vendor 包都携带其 LICENSE 文件,且 package.json 的 `license` 字段与 vendor/README.md 中的清单一致(我们混合了 vendor 的 MIT 与自有的 BSD-3)——作为 CI 步骤运行。 +4. **Renovate**(或定时 agent(智能体)任务)以小 PR 的形式提议 npm 依赖更新,这些 PR 走完整门禁套件;vendor 包不在其列(它们的更新遵循 manifest 同步流程,理想情况下是半自动化的 agent 工作流:拉取上游、重新应用 patch、运行门禁、以更新后的 manifest 表格开 PR)。 + +## 计划 + +第 3 项最简单,先做。第 1 项需要 CI 能通过网络访问上游仓库(私有仓库,需要 token),并将现有两项已记录的修改转换为 patch 文件。第 2 项和第 4 项是配置工作。 + +## 曾考虑的替代方案 + +- **用 `pnpm audit` 替代 osv-scanner**:两者都满足安全公告扫描的需求;具体选择推迟到实现阶段决定。 +- **用定时 agent 任务替代 Renovate**:在提议小型更新 PR 并走完整门禁套件方面效果等价;vendor 包无论哪种方案都不在其列(它们的更新遵循 manifest 同步流程)。 + +## 验收标准 + +- 许可证清单脚本在 CI 中运行,缺少 LICENSE 或 `license` 字段与 `vendor/README.md` 中的清单矛盾时失败。 +- 夜间漂移任务从 manifest SHA 加签入的 patch 文件重建 `vendor/`,出现任何无法解释的 diff 时失败。 +- 安全公告扫描按计划定期运行,并在涉及 lockfile 变更的 PR 上运行。 + +## 风险 + +上游仓库是私有镜像;CI 凭证与可用性是漂移检查的主要阻力。如果受阻,可改为本地定时 agent 任务而非 CI。 diff --git a/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.i18n.yaml b/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.i18n.yaml new file mode 100644 index 0000000000..bf44db6bee --- /dev/null +++ b/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-discover-package-inventory.md: 50e42686cea48985dedc7fa290e06bc959ecc5d4 +2026-06-20-discover-package-inventory.zh.md: dc79162dd3ec5ba2bf3225fc8e9d44c552a514cb diff --git a/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.md b/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.md index f9286aeefd..50e42686ce 100644 --- a/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.md +++ b/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-06-20-discover-package-inventory.zh.md) + ## Problem Package and gate inventories are repeated across TypeScript project references, package docs, CI prose, and Knip overrides. Most restate package layout, manifest data, or aggregate command contents. Each new package therefore creates avoidable synchronization points. diff --git a/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.zh.md b/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.zh.md new file mode 100644 index 0000000000..dc79162dd3 --- /dev/null +++ b/.agents/notes/proposed/process/2026-06-20-discover-package-inventory.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 通过发现机制获取包清单,而非维护静态列表 + +Status: proposed + +[English](2026-06-20-discover-package-inventory.md) | 中文 + +## 问题 + +包(package)与门禁清单在 TypeScript project references、包文档、CI 描述和 Knip 覆盖项中反复出现。大多数只是重述包布局、manifest(元数据清单)数据或聚合命令内容。因此每新增一个包都会产生本可避免的同步点。 + +[包层级结构](../../implemented/architecture/2026-06-20-package-hierarchy.md)已经手动消除了其中若干:`scripts/publint-all.ts` 现在从 `packages/<group>/<pkg>` 布局推导列表,两份 `tsconfig` 的 `paths` 映射也合并为一个 `@deepseek-ai/dsh-*` 通配符。剩下的是无法用 glob 消除的清单,主要是聚合配置(`tsconfig.host.json`、`tsconfig.client.json`)的 project `references`——TypeScript 要求它们是显式数组(没有通配符形式)。 + +当静态列表编码的是策略时,它们是合理的;当它们只是重复 `package.json`、workspace glob 或包层级结构中已有的 manifest 数据或布局事实时,就是不必要的摩擦。 + +## 提案 + +让剩余的包与门禁清单可被发现。一个唯一的权威来源,即 `packages/<group>/<pkg>` 层级结构加上包 manifest,应当驱动聚合配置的 `references`、模块图以及任何全量包列表,并配合一个生成加校验步骤(沿用现有的 `gen-module-graph` / `gen-cordis-catalog` 模式:生成器写出产物,`--check` 模式在 `hygiene` / `doc-sync`(文档同步门禁)中发现已提交副本陈旧时失败)。模块图生成已经在读取包 manifest。`doc-sync` 应当成为定义并打印其子门禁的唯一命令,文档链接到该命令,而非重述第二份列表。 + +层级结构不需要编码关于包的所有事实,但应当编码宽泛的维护策略:core/product 包、集成包、能力 seam 包与 support/test/example 包不应在脚本能区分它们之前先要求一份手工维护的例外列表。 + +有一项已编目的内容根本不需要生成器:将 e2e 入口 glob 折入 Knip 的默认配置段,即可直接删除逐包的重复声明。 + +## 验收标准 + +- 聚合配置的 project `references` 由层级结构生成(生成器输出它们;`--check` 门禁在提交副本陈旧时报错),而非手工维护。 +- 新增一个包时,不需要为任何门禁编辑静态包列表。 +- 文档描述真源,而非重复生成的清单。 +- CI 调用聚合命令,由这些命令自行管理其子门禁列表。 +- `knip.json` 仅在编码真实信息(额外入口文件、被忽略的依赖)时才携带逐包覆盖项,绝不重述默认配置段。 + +## 风险 + +发现脚本可能变得过于精巧。实现应当保持朴素:读取 manifest、按显式字段过滤、打印解析后的列表,并在出错时明确失败。收益在于消除手工清单的漂移,而非发明一套构建系统。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.i18n.yaml b/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.i18n.yaml new file mode 100644 index 0000000000..19915e8383 --- /dev/null +++ b/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-prune-dead-core-spine-surface.md: a6c608617415f3af07de5c95fd20b0bde40bdef3 +2026-07-04-prune-dead-core-spine-surface.zh.md: 83603d8a8432b99d8f42222442b38005e196ac4e diff --git a/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.md b/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.md index 1f52bfac25..a6c6086174 100644 --- a/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.md +++ b/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-07-04-prune-dead-core-spine-surface.zh.md) + ## Problem Several package-root exports, result fields, and convenience methods have no production consumer. They survive because tests import internals through public entry points or because a type anticipated a caller that never arrived. Each item is small in isolation, but together they enlarge the SDK contract, generated catalogs, documentation, and regression matrix without enabling a shipped path. @@ -15,7 +17,7 @@ The production corpus is `packages/*/*/src`, example sources/config, and runtime | `ReactLoopAgent` root export | Outside-package named imports are tests; production programs against `Agent` and creates/resumes through `ctx.agents`. | Return/interface-type `Agent` and make the concrete loop class package-internal; keep the deliberate synchronous config-only `AgentLoop.create()` path. | | `workflow-workerthread` protocol/runtime/session re-exports and named `WorkerWorkflowEngine` | Every package-name consumer uses the default engine; the workflow Agent Note already defines the worker wire protocol as private. | Keep the default plugin class/config contract; drop the duplicate named class export and keep protocol modules source-private. | | `code-runtime-worker` protocol/bootstrap re-exports | Outside-package production/e2e consumers use `WorkerCodeRuntime` and config, not `BootstrapPort`, `PatchableStream`, or worker message/boot types. | Keep the runtime class/config contract and make its wire/bootstrap vocabulary source-private. | -| ACP translation/presenter root exports | `agentOptions`, `streamSessionEventUpdate`, `todosToPlan`, `ToolPresenter`, `nullToolPresenter`, and `TerminalRendering` have only same-file or ACP-test consumers; the sole outside-package production consumer mounts the plugin namespace. | Keep `name`, `inject`, `Config`, `AcpConfig`, and `apply`; make translation/presentation helpers source-private and test them in-package. | +| ACP `agentOptions` root export | The helper has only same-file and ACP-test consumers; the sole outside-package production consumer mounts the plugin namespace. | Keep `name`, `inject`, `Config`, `AcpConfig`, and `apply`; make `agentOptions` source-private and test it through bridge behavior. | | `providerWording` and `completedTurnPrefix` root exports | Each has one same-package production caller; only the balanced-prefix helper has a same-package white-box test. | Make them source-private and test provider behavior. | | `depthOf`, `SubagentDepthError`, `SENSITIVE_ENV_PATTERN`, `waitForExit`, and `exitsWithin` root exports | Production subagent backends consume the in-process runner and subprocess construction/disposal helpers, not these enforcement/test internals. | Keep depth/environment/exit behavior but make the helpers and error/regex source-private; test through spawn and disposal. | | `PersistenceCoordinator.inits`, backend `inits` accessors, `seedCoversPrefix`, and `assertSerializable` | The accessors exist for white-box tests; `seedCoversPrefix` has no outside production importer; `assertSerializable` has no production caller and duplicates the coordinator append boundary's lossless snapshot. | Observe initialization through `session/flush`, make `seedCoversPrefix` source-private, and delete `assertSerializable`. Keep both backends, `SessionHeader`, and SQLite's version contract. | diff --git a/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.zh.md b/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.zh.md new file mode 100644 index 0000000000..83603d8a84 --- /dev/null +++ b/.agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.zh.md @@ -0,0 +1,63 @@ +# Agent Note: 裁剪无用的公开与结果接口 + +Status: proposed + +[English](2026-07-04-prune-dead-core-spine-surface.md) | 中文 + +## 问题 + +若干包(package)根导出、结果字段和便利方法没有生产消费方。它们之所以存活,要么是因为测试通过公开入口导入了内部实现,要么是因为某个类型预期了一个从未出现的调用者。每一项单独看都很小,但合在一起,它们扩大了 SDK 契约、生成的 catalog、文档和回归矩阵,却没有支撑任何已交付的路径。 + +生产语料库是 `packages/*/*/src`、示例源码/配置和运行时脚本。测试、包 README 和 Agent Note(agent 决策记录)行文是发布的证据,但不是固定调用者。`cordis_inspect` 使 `packages/cordis/tool-cordis/src/api-catalog.ts` 对模型可见,`cordis_mount` 可以通过受保护的真实服务代理调用注入的服务,因此 catalog 中的服务方法和返回形状是真正的动态产品接口。下表因此区分「没有固定的仓库调用者」与「不可达」:涉及 catalog 词汇的行有意收缩模型编写的 mount 能发现和调用的内容,而包根实现辅助函数并不通过该服务门面可达。精确符号搜索得出以下清单: + +| 接口 | 生产证据 | 简化方式 | +| --- | --- | --- | +| `SurfaceManager.invalidate()` | 只有其单元测试调用它;seeding 在惰性创建的 manager 存在之前就已完成,且会话从不替换其日志引用。 | 删除它及其不可能触发的整体替换契约。 | +| `ToolExecutionResult.callId` | 每个钩子已经接收不可变的 `ToolExecution`;循环和 ACP(Agent Client Protocol)通过调用/会话事件关联。没有消费方读取这个重复的结果字段。 | 移除该字段、复制/不匹配守卫,以及证明该重复不可能不一致的测试。 | +| `ReactLoopAgent` 根导出 | 包外的命名导入都是测试;生产代码面向 `Agent` 编程,通过 `ctx.agents` 创建/恢复。 | 返回/接口类型为 `Agent`,将具体循环类改为包内部;保留有意设计的同步、仅配置的 `AgentLoop.create()` 路径。 | +| `workflow-workerthread` 的 protocol/runtime/session 再导出与命名的 `WorkerWorkflowEngine` | 每个包名消费方都使用默认引擎;工作流 Agent Note 已将 worker 协议格式(wire format)定义为私有。 | 保留默认插件类/配置契约;移除重复的命名类导出,将协议模块保持为源码私有。 | +| `code-runtime-worker` 的 protocol/bootstrap 再导出 | 包外的生产/e2e 消费方使用 `WorkerCodeRuntime` 和配置,而非 `BootstrapPort`、`PatchableStream` 或 worker 消息/启动类型。 | 保留运行时类/配置契约,将其协议格式/bootstrap 词汇改为源码私有。 | +| ACP 的 `agentOptions` 根导出 | 该辅助函数只有同文件和 ACP 测试消费方;唯一的包外生产消费方挂载的是插件命名空间。 | 保留 `name`、`inject`、`Config`、`AcpConfig` 和 `apply`;将 `agentOptions` 改为源码私有,通过桥接层行为测试。 | +| `providerWording` 与 `completedTurnPrefix` 根导出 | 各有一个同包生产调用者;只有 balanced-prefix 辅助函数有一个同包白盒测试。 | 改为源码私有,测试提供方行为。 | +| `depthOf`、`SubagentDepthError`、`SENSITIVE_ENV_PATTERN`、`waitForExit` 与 `exitsWithin` 根导出 | 生产 subagent 后端消费的是进程内 runner 和子进程构造/dispose(资源释放)辅助函数,而非这些强制/测试内部实现。 | 保留深度/环境/退出行为,但将辅助函数和 error/regex 改为源码私有;通过 spawn 和 dispose 测试。 | +| `PersistenceCoordinator.inits`、后端 `inits` 访问器、`seedCoversPrefix` 与 `assertSerializable` | 访问器为白盒测试而存在;`seedCoversPrefix` 没有包外生产导入者;`assertSerializable` 没有生产调用者,且与 coordinator append 边界的无损快照重复。 | 通过 `session/flush` 观察初始化,将 `seedCoversPrefix` 改为源码私有,删除 `assertSerializable`。保留两个后端、`SessionHeader` 和 SQLite 的版本契约。 | +| `LlmError.status` 与回放 status | 适配器/回放填充它,但生产分支基于稳定的错误码/消息判断,从不读取原始 status。 | 移除未读字段和回放管道,保留错误分类。 | +| `BlockAssembler.push()` 返回值 | 两个生产调用者都忽略返回的已完成块。 | 返回 `void`;保留有意公开的 `blocks()`/`message()` 契约。 | +| `compactRegion` 的独立 `session` 参数 | 固定调用者传入的对象与 `agent.session` 上已有的是同一个;模型可见的 mount API 也能调用该方法,但接受两个身份允许挂载的插件提供不一致的配对。 | 保留手动 region seam,同时有意将其收窄为以 `agent.session` 为唯一真源。 | +| `CompactionResult.startSeq`、`summarySeq`、`endSeq` 与 `summary` | 生产消费方只读取 shadowed range/seq/token 统计;持久日志拥有 summary 和事件标识。 | 移除四个结果回显,保留两个共享的 transcript(文本记录)渲染器。 | +| `BasicCompactService` 的 estimation/summarization 可见性 | 没有包外生产调用者调用这五个方法;已实现的 Agent Note 只将 `estimateContentTokens()` 和 `summarize()` 命名为子类钩子。 | 将这两个方法改为 `protected`,其余三个编排专用的估算器改为 private。 | +| `CodeLogEntry.source`/`level` 与 `RunCodeMeta.dispatches` | 每个生产消费方都将日志映射为文本;没有 presenter/模型路径读取其他字段或持久化的 dispatch 计数。 | 将 code-runtime 日志改为字符串(或纯文本条目),移除 result-meta 的 dispatch 管道;保留用于生成确定性 dispatch id 的本地计数器。 | +| `CodeRuntime.language` 与 `CodeRuntime.isolation` | worker 后端提供唯一的生产值,而 Code Mode 及其他所有生产调用方只调用 `run()`。 | 移除未读描述符,同时保留 worker 的语言、隔离、预算、取消与资源释放行为。 | +| `ToolNotFoundError.toolName`、`SystemPrompt.config` 与 `BashTask.command` | 每个存储的公开值都没有生产读取者。 | 移除未读字段,保留错误消息、已解析的配置行为和任务生命周期。 | +| 后端包根实现辅助函数 | 下方精确清单仅通过相对路径的同包导入调用。生产命名空间导入挂载的是保留的插件契约,不读取这些属性;命名根消费方都是测试。 | 保留每个适配器/提供方/服务及其配置/错误契约;停止在包根导出所列辅助函数/常量。 | +| 消费方包根实现辅助函数 | 下方精确清单只有同包生产调用者。生产命名空间导入挂载的是插件契约,不读取辅助属性;命名根消费方都是测试。 | 保留插件契约和稳定的错误码;将测试迁移到包内模块或公开行为,停止在包根导出所列辅助函数。 | + +### 分组辅助导出清单 + +- `dsh-llm-deepseek`:`httpErrorCode`、`serializeMessages`、`serializeRequest`、`DONE`、`parseSse`、`mapFinishReason`、`mapUsage` 与 `translate`;`dsh-llm-pi-ai`:`buildModel`、`mapStopReason`、`mapUsage`、`toPiContext` 与 `toStreamChunks`。 +- `dsh-bash-local`:`DEFAULT_GRACE_MS`、`ENV_OVERRIDES`、`killGroup`、`OutputCollector` 与 `runBash`;`dsh-bash-sandbox`:`shellQuote`、`classifyDenial` 与 `classifyRunnerFailure`;`dsh-sandbox-local`:`bwrapProfileArgs`、`landlockProfileArgs` 与 `seatbeltProfileArgs`。公开的可变测试注入字段及其类型不在本提案范围内。 +- `dsh-fs-local`:`applyLiteralEdit`、`listDirectory`、`probe`、`readForEdit`、`readTextForDiff`、`readWholeText`、`resolveLocalTarget`、`restoreLineEndings`、`streamWholeText` 与 `writeFileAtomic`。 +- `dsh-web-fetch-local`:`classifyContentType`、`decoderForCharset`、`isSameOrigin`、`parseCharset` 与 `validateFetchUrl`;`dsh-web-search-exa`:`mapExaResponse` 与 `mapExaResult`;`dsh-web-search-deepseek`:`citationSnippets` 与 `mapAnthropicResponse`;`dsh-web-search-perplexity`:`mapPerplexityResponse` 与 `mapPerplexityResult`。 +- `dsh-tool-fs`:`READ_LIMIT`、`STREAM_MIN_SIZE`、`READ_MAX_BYTES`、`READ_MAX_LINE_LENGTH`、`DIFF_CONTEXT`、`applyReadTool`、`parseReadArgs`、`applyWriteTool`、`formatWriteOutput`、`parseWriteArgs`、`applyEditTool`、`formatEditOutput`、`parseEditArgs`、`buildWindow`、`formatReadOutput`、`computeHunkDiffs` 与 `diffsFromMeta`。 +- `dsh-tool-web`:`WEB_SEARCH_MAX_RESULTS`、`applyWebSearchTool`、`formatSearchOutput`、`parseSearchArgs`、`presentSearchCall`、`applyWebFetchTool`、`formatFetchOutput`、`parseFetchArgs`、`presentFetchCall`、`renderBody` 与 `htmlToMarkdown`;`dsh-timeout-policy`:`toolTimeoutResult`;`dsh-compact-basic`:`resolveConfig`;`dsh-tool-bash`:`renderResult`。 + +## 提案 + +以一次有界的、协调的公开接口清理,移除或降级上述每一行。同步更新包 README、JSDoc、生成的 API/事件 catalog、type-equiv 记录、必要的 exports map 以及测试,使测试通过所属的公开 seam 验证行为,而非保留仅为测试而存在的入口。不折叠任何能力 seam、LLM(大语言模型)适配器、持久化后端或生命周期完全停稳契约。 + +## 曾考虑的替代方案 + +**保留测试便利函数和自包含的结果字段为公开。** 公开辅助函数可以让白盒测试更方便,自包含的结果字段看起来更易用,未来的嵌入者可能需要具体循环类或枚举方法。这些好处是假设性的;当前它们让每处实现和文档都要解释没有已交付调用者能观察到的状态。真正的消费方可以引入它所需的最小契约,其所有权和失败语义明确。 + +**保留所有 catalog 成员以供模型编写的 mount 使用。** 自引用工具集是一条真实的通用消费路径,而非生成文档的噪音。然而,它的价值来自准确、可组合的服务接口,而非无限期保留重复字段或不一致的参数对;上述每一项 catalog 收缩都移除了在同一次执行、同一个 agent(智能体)或同一结果中其他位置已可获得的事实,并在同一变更中更新 API 参考。 + +## 验收标准 + +- 精确符号搜索显示:在本 Agent Note 及任何已实现 Agent Note 修正之外,没有被移除的接口。 +- 本 Agent Note 列出的每个接口均按指定方式缺失或降级;清单之外有意保留的扩展/测试契约不变。 +- 工具执行、上下文压缩(context compaction)、两个 LLM 适配器、两个持久化后端、工作流隔离以及 agent 创建/恢复保持其已交付行为。 +- 类型检查、覆盖率、快照、doc-sync(文档同步门禁)、module-graph 校验、构建和 hygiene 通过。 + +## 风险 + +大多数移除在编译时可见但对运行时无影响。上下文压缩参数清理有意禁止会话/上下文不匹配,同时保留手动 region seam。外部预发布嵌入者和现有模型编写的 mount 可能导入更少的辅助函数、传递更少的参数或接收更窄的结果形状;这是有意的产品接口收缩,而非仅仅是生成 catalog 的清理。仓库尚未发布,因此承载不受支持的接口才是更大的基础成本。 diff --git a/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.i18n.yaml b/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.i18n.yaml new file mode 100644 index 0000000000..8ca0473ebe --- /dev/null +++ b/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-deterministic-and-stress-testing.md: d9977be835af05f9ee303b63ec6015bc9e153170 +2026-06-11-deterministic-and-stress-testing.zh.md: eff9eecb699344dff388bafec270f6b6677f71ee diff --git a/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.md b/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.md index c3b17c401a..d9977be835 100644 --- a/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.md +++ b/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-06-11-deterministic-and-stress-testing.zh.md) + ## Problem Several loop tests synchronize with `setTimeout(30)` sleeps — flakiness debt that wastes agent cycles on retries and can mask ordering bugs. Separately, our core architectural promise (any session log replays to identical derived history) is asserted in two tests but is cheap to assert *everywhere*. And the inbox wakeup race was verified by hand exactly once; nothing re-verifies it continuously. diff --git a/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.zh.md b/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.zh.md new file mode 100644 index 0000000000..eff9eecb69 --- /dev/null +++ b/.agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 确定性测试、回放不变式 fixture(测试前置数据)与竞态压力测试 + +Status: proposed + +[English](2026-06-11-deterministic-and-stress-testing.md) | 中文 + +## 问题 + +若干 agent loop(智能体循环)测试通过 `setTimeout(30)` 睡眠来同步——这是一笔不稳定性债务,浪费 agent 的重试周期,还可能掩盖时序 bug。另外,我们的核心架构承诺(任何会话日志回放后都能得到相同的派生历史)目前只在两个测试中断言,但在*所有*测试中断言的成本极低。此外,inbox 唤醒竞态只被手动验证过一次,没有任何机制持续复验。 + +## 提案 + +三项措施: + +1. **测试中禁止挂钟睡眠。** 将 `setTimeout(N)` 等待替换为事件驱动等待(既有的 `waitForIdle` 模式,扩展为 `waitForStatus`、`waitForEvent(n)`),或在需要测试时间本身时使用 vitest 的 fake timer。通过 lint 规则禁止 `setTimeout`,适用范围是 `packages/*/tests`,白名单辅助模块除外。 +2. **通用回放 fixture。** 一个共享测试辅助函数包装 agent loop harness,使每个测试结束后,agent 的会话日志被回放到一个全新的 Session 中,并自动断言 `deriveMessages()` 相等。这样该不变式在每次 CI 运行中会被套件产生的所有场景检查数百次,而非仅两次。 +3. **夜间竞态压力测试。** 一个 CI job 以 `vitest --repeat=200`(加 `--shuffle`)运行 agent-loop 和 inbox 套件,以暴露调度依赖的失败;发现的任何不稳定测试都视为 bug 修复,绝不靠重试掩盖。 + +## 计划 + +措施 1 和 2 一起落地(它们改动相同的辅助模块);在套件消除所有睡眠后再添加夜间 job,以确保重复运行速度快。 + +## 验收标准 + +- 不再使用 `setTimeout`;lint 规则在 `packages/*/tests` 中强制执行,白名单辅助模块除外。 +- 共享 harness 将每个测试的会话日志回放到全新的 `Session` 中,并自动断言 `deriveMessages()` 相等,覆盖整个套件。 +- 夜间 job 以 `--repeat` 和 `--shuffle` 运行 agent-loop 和 inbox 套件;发现的不稳定测试作为 bug 分诊,绝不靠重试掩盖。 + +## 风险 + +Fake timer 与 agent loop 中的 Promise 调度存在微妙交互——优先使用事件驱动等待;仅在测试 timer 服务行为本身时才使用 fake timer。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/proposed/testing/2026-06-11-mutation-testing.i18n.yaml b/.agents/notes/proposed/testing/2026-06-11-mutation-testing.i18n.yaml new file mode 100644 index 0000000000..d593656c04 --- /dev/null +++ b/.agents/notes/proposed/testing/2026-06-11-mutation-testing.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-mutation-testing.md: 591d9012644a19ee2c67a916b63092d79f78db1f +2026-06-11-mutation-testing.zh.md: 9c22ed2f42e5c44e6be98f132614886bbdb188fd diff --git a/.agents/notes/proposed/testing/2026-06-11-mutation-testing.md b/.agents/notes/proposed/testing/2026-06-11-mutation-testing.md index 35df228b85..591d901264 100644 --- a/.agents/notes/proposed/testing/2026-06-11-mutation-testing.md +++ b/.agents/notes/proposed/testing/2026-06-11-mutation-testing.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-06-11-mutation-testing.zh.md) + ## Problem The per-file 100% coverage gate ([the quality-gates decision](../../implemented/process/2026-06-11-quality-gates.md)) proves every line *executes* under test — not that any assertion would notice if the line were wrong. Under agent-written tests, coverage pressure can produce execution-without-assertion. Mutation testing measures what coverage cannot: whether the suite *kills* deliberately injected bugs. diff --git a/.agents/notes/proposed/testing/2026-06-11-mutation-testing.zh.md b/.agents/notes/proposed/testing/2026-06-11-mutation-testing.zh.md new file mode 100644 index 0000000000..9c22ed2f42 --- /dev/null +++ b/.agents/notes/proposed/testing/2026-06-11-mutation-testing.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 变异测试作为覆盖率的制衡手段 + +Status: proposed + +[English](2026-06-11-mutation-testing.md) | 中文 + +## 问题 + +逐文件 100% 覆盖率门禁([质量门禁决策](../../implemented/process/2026-06-11-quality-gates.md))证明每一行代码在测试中都被*执行*了,但不能证明如果该行出错,任何断言会注意到。在 agent(智能体)编写测试的场景下,覆盖率压力可能产出「执行但不断言」的测试。变异测试衡量的正是覆盖率无法衡量的:测试套件是否能*杀死*被刻意注入的缺陷。 + +## 提案 + +使用 Stryker(`@stryker-mutator/vitest-runner`)对 `packages/*/src` 运行变异测试: + +- **PR(Pull Request)范围的增量运行**(仅变更文件),作为一个 CI job。调优后速度足以作为合并门禁。 +- **每夜全量运行**,跟踪变异分数;先记录基线,再将阈值设为观测到的基线并只升不降(与覆盖率策略一致:阈值只收紧)。 +- 存活的变异体是待办项:agent 选取一个存活体、编写杀死它的测试、循环往复——一个形态良好的自主循环。 +- 等价变异体(可证明不改变行为的)加注释排除并附理由,与 `/* v8 ignore */` 策略一致。 + +## 计划 + +1. 添加 Stryker 配置,范围限定在一个包(package),即 llm(最小、最具算法性),并测量运行时间。 +2. 扩展到所有包;在配置中记录基线分数。 +3. 接入每夜 job;运行时间可接受后再添加 PR 范围的增量 job。 + +## 验收标准 + +- Stryker 配置在 `packages/*/src` 上以 vitest runner 运行;每夜 job 记录变异分数,当分数低于记录的基线时,通过只升不降的阈值使运行失败。 +- PR 范围的增量运行在运行时间可接受后作为合并门禁;或者明确保持仅每夜运行,并将该结论记录于此。 +- 等价变异体带有注释排除及理由,与 `/* v8 ignore */` 策略一致。 + +## 风险 + +运行时间:变异测试开销大;逐文件 100% 覆盖率有所帮助(每个变异体至少会被执行到)。如果 PR 范围的运行始终过慢,则保持仅每夜运行,依赖分数只升不降的机制。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.i18n.yaml b/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.i18n.yaml new file mode 100644 index 0000000000..6201a380e7 --- /dev/null +++ b/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-11-immutable-public-surfaces.md: c9009ad923720efaecb25e2017ceab6e3eb0dbf4 +2026-06-11-immutable-public-surfaces.zh.md: 4ef67734d712e538c5858fbc05efbc6dd983c704 diff --git a/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.md b/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.md index 0c6652a94d..c9009ad923 100644 --- a/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.md +++ b/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.md @@ -2,6 +2,8 @@ Status: rejected — the pervasive `DeepReadonly<T>` type flip is replaced by source-owned runtime immutability in `Session` plus relational development assertions. See [source-owned session immutability and dev-mode invariants](../../implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md). +English | [中文](2026-06-11-immutable-public-surfaces.zh.md) + ## Problem The rejected proposal targeted an ownership hole that a `readonly SessionEvent[]` type alone cannot close: its elements remain mutable at runtime, so a cast or plain JavaScript can rewrite nested history. The implemented design closes that hole in `Session` by materializing and deep-freezing every accepted event and returning frozen array snapshots. In-flight prompt waterfalls remain intentionally transformable, so immutability is an ownership boundary rather than a blanket type rule. diff --git a/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.zh.md b/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.zh.md new file mode 100644 index 0000000000..4ef67734d7 --- /dev/null +++ b/.agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 深度只读的公开接口 + +Status: rejected — 普遍采用 `DeepReadonly<T>` 的类型翻转已由 `Session` 中归属源的运行时不可变性与关系型开发断言取代。见[归属源的会话不可变性与开发模式不变式](../../implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md)。 + +[English](2026-06-11-immutable-public-surfaces.md) | 中文 + +## 问题 + +被否决的提案针对的是一个所有权漏洞:仅靠 `readonly SessionEvent[]` 类型无法封堵该漏洞,因为其元素在运行时仍然可变,类型强制转换或纯 JavaScript 代码可以改写嵌套的历史记录。已实现的设计在 `Session` 中封堵了这一漏洞:对每个被接受的事件进行物化并深度冻结,返回冻结的数组快照。进行中的提示词 waterfall(瀑布式事件)有意保持可变换,因此不可变性是一条所有权边界,而非一条全局类型规则。 + +## 提案 + +> **实际采用了不同的实现方式——见 Status 行与[源拥有的会话不可变性与开发模式不变式](../../implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md)。** 下文的 `DeepReadonly<T>` 设计已被否决:它仅在编译期生效、对消费方噪音大、且可被强制转换绕过。`Session` 改为在每次组合中对已接受的事件和公开日志快照进行快照与深度冻结;`deriveMessages()` 返回分离的冻结投影;开发插件检查跨记录与跨 seam 的关系。 + +在类型层面为「突变即损坏」的场景引入不可变性: + +- `SessionEvent` 数据在从会话输出时(`events`、`session/event` 监听器)变为 `DeepReadonly`;`append()` 仍接受普通可变输入。一个 `DeepReadonly<T>` 工具类型放在 dsh-llm 中,与 brand/never 辅助类型相邻。 +- `deriveMessages()` 返回深度只读的消息;agent loop(智能体循环)在将可变请求交给 `agent/request` waterfall 之前先克隆(该处的突变是被允许的——克隆使边界显式且代价低廉,每个步骤仅一次)。 +- `PromptAssembly` 在其 waterfall 流经期间保持可变(被允许),但注册表内部的 section 列表在每次组装时被克隆(已有此行为)。 + +## 计划 + +引入 `DeepReadonly`,翻转会话的读取路径,并修复消费方中由此产生的编译错误。 + +## 风险 + +`DeepReadonly` 类型在 waterfall 边界处(突变本身就是 API 的地方)可能产生噪音较大的错误。应将可变/只读边界精确地划在「已记录 vs 进行中」,并在会话 README 中加以说明。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.i18n.yaml b/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.i18n.yaml new file mode 100644 index 0000000000..6a1baa8a80 --- /dev/null +++ b/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-providerless-example-base.md: 2f41476a487775e6f9da2f113efe566e44786ff3 +2026-06-20-providerless-example-base.zh.md: e767d6b3a35dcfd52194f8a59edc496b86414b6e diff --git a/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.md b/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.md index 81dbe40ee4..2f41476a48 100644 --- a/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.md +++ b/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.md @@ -2,6 +2,8 @@ Status: rejected — superseded by [Extract example apps into packages](../../implemented/architecture/2026-06-20-extract-example-app-packages.md), which moves the spine into a `dsh-agent-spine-demo` bundle and deletes the `base*.yml` files, so there is no shared base YAML left to rename. +English | [中文](2026-06-20-providerless-example-base.zh.md) + ## Problem The examples had two shared base files: `examples/base-core.yml` was providerless, while `examples/base.yml` included that core plus the real `llm-deepseek` adapter. Snapshot replay needs the providerless core with `llm-replay`, because loading the real adapter without a key throws. The normal demos need the real adapter. The result was a naming inversion: the file named `base.yml` was not the reusable base for all examples, while the true base was `base-core.yml`. diff --git a/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.zh.md b/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.zh.md new file mode 100644 index 0000000000..e767d6b3a3 --- /dev/null +++ b/.agents/notes/rejected/architecture/2026-06-20-providerless-example-base.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 使共享示例基础配置与提供方无关 + +Status: rejected — 已由[将示例应用提取到 packages 中](../../implemented/architecture/2026-06-20-extract-example-app-packages.md)取代;后者把主干移入 `dsh-agent-spine-demo` bundle 并删除 `base*.yml` 文件,因此已不存在可重命名的共享基础 YAML。 + +[English](2026-06-20-providerless-example-base.md) | 中文 + +## 问题 + +示例曾有两个共享基础文件:`examples/base-core.yml` 与提供方无关,而 `examples/base.yml` 在该核心基础上加入了真实的 `llm-deepseek` 适配器。快照回放需要与提供方无关的核心配合 `llm-replay` 使用,因为在没有密钥的情况下加载真实适配器会抛出异常。常规演示则需要真实适配器。结果是命名与实际含义倒挂:名为 `base.yml` 的文件并非所有示例可复用的基础,而真正的基础反倒是 `base-core.yml`。 + +这种拆分可以理解,但它让每次解释配置都变得更冗长。它还导致了别扭的测试搭建方式,例如无密钥冒烟测试不得不携带一个虚拟 API key,仅仅为了让适配器能启动——尽管模型根本不会被调用。 + +## 提案 + +将与提供方无关的核心重命名为 `examples/base.yml`,让适配器选择在每个具体示例中显式声明。编码和 ACP(Agent Client Protocol)真实配置添加一小段 `llm-deepseek` include 或本地块;快照配置添加 `llm-replay`。删除 `examples/base-core.yml`。 + +共享基础应仅包含提供方无关的服务与工具:`llm`、会话、系统提示词、工具、agent(智能体)、不变式、bash 执行器和 bash 工具 schema。任何涉及模型提供方选择的内容都应放在叶子配置中。 + +## 验收标准 + +- `examples/base.yml` 与提供方无关。 +- `examples/base-core.yml` 已删除。 +- 真实演示配置显式添加 DeepSeek 适配器。 +- 快照回放配置 include 同一个与提供方无关的基础,并加入其回放适配器。 +- [examples README](../../../../examples/README.md)、各示例 README 及 Agent Note(agent 决策记录)引用不再解释「base = base-core 加适配器」。 + +## 放弃了什么 + +真实演示失去了一层便利:每个演示都必须显式引入适配器。对于示例而言这是正确的默认行为,因为适配器选择是可变部分,而与提供方无关的接线才是共享的产品核心。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.i18n.yaml b/.agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.i18n.yaml new file mode 100644 index 0000000000..0ee4dd2632 --- /dev/null +++ b/.agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-13-stream-workflow-progress-through-tool-calls.md: 1b299ec323d32745cc504a90948b63a4dcaae64f +2026-07-13-stream-workflow-progress-through-tool-calls.zh.md: f84ff3bb22a19ed7ad2f9fc262a6702e254972ad diff --git a/.agents/notes/proposed/feature/2026-07-13-stream-workflow-progress-through-tool-calls.md b/.agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.md similarity index 97% rename from .agents/notes/proposed/feature/2026-07-13-stream-workflow-progress-through-tool-calls.md rename to .agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.md index 0c6516080a..1b299ec323 100644 --- a/.agents/notes/proposed/feature/2026-07-13-stream-workflow-progress-through-tool-calls.md +++ b/.agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.md @@ -1,6 +1,8 @@ # Agent Note: Stream workflow progress through tool calls -Status: proposed +Status: rejected — ACP is automation-only; live workflow presentation needs a human-interface owner and a fresh design. + +English | [中文](2026-07-13-stream-workflow-progress-through-tool-calls.zh.md) ## Problem diff --git a/.agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.zh.md b/.agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.zh.md new file mode 100644 index 0000000000..f84ff3bb22 --- /dev/null +++ b/.agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.zh.md @@ -0,0 +1,43 @@ +# Agent Note: 通过工具调用流式传输工作流进度 + +Status: rejected — ACP 仅面向自动化;实时工作流展示需要一个面向人类界面的归属方和全新设计。 + +[English](2026-07-13-stream-workflow-progress-through-tool-calls.md) | 中文 + +## 问题 + +工作流引擎有意为 run、phase、narration 和子 agent(智能体)进度发出成对的 `workflow/*` observation 事件,但目前没有生产消费方呈现这些事件。因此,编辑器在最终结果返回之前只显示一张 pending 状态的工作流工具卡片,尽管引擎已经报告了当前活跃的 phase、脚本日志内容以及哪些子 agent 已启动或已结束。[动态工作流决策](../../implemented/feature/2026-07-05-dynamic-workflows.md)明确将 ACP(Agent Client Protocol)进度 UI 保留给这一事件流。 + +如果让 `dsh-acp` 直接监听工作流事件,就会反转能力边界:通用的 UI 桥接层将依赖一个可选的工作流包(package),并对一个工具名做特殊处理。工具流水线已经拥有实时更新所需的路由信息(agent 和 call id),但只暴露了纯粹的 pending/final 展示器,因此长时间运行的工具没有提供方无关的方式在二者之间报告瞬态 UI 状态。 + +## 提案 + +为 `dsh-tools` 添加一条实时进度通道。注册表所有的 `ToolExecution` 新增 `reportProgress(view): boolean`,其中 `view` 是一个独立的、提供方无关的通用进度快照,包含可选的替换标题和面向 UI 的内容块。进度不能更改调用的 args 派生卡片标签、kind、原始输入、locations、terminal intent 或 diff intent;它只更新在最初选定的展示方式内的实时标题/内容。当执行处于活跃状态时,该方法校验并快照 view,然后分发一个受限的、agent 作用域的 `tools/progress` observation,携带权威的执行标识与快照。一旦 final-result 处理开始,方法返回 `false` 且不再分发,因此迟到的异步报告者无法覆盖终态卡片。观察者异常会被记录日志,不会导致工具失败。 + +`dsh-acp` 以通用方式消费 `tools/progress`。它通过既有的 agent 到会话映射解析执行所属的 agent,并为同一 call id 发出 in-progress 的 `tool_call_update`。由于报告仅在工具执行流水线内可用,持久化的 `tool/call` 及其 ACP `tool_call` 始终先于第一条 update;在 `tools/result` 之前关闭报告者,确保进度更新不会出现在 completed/failed 卡片之后。进度是实时 UI 状态,而非模型输入或持久历史:会话回放继续从 `tool/call` 和 `tool/result` 重建 pending 与 final 卡片,无需重放瞬态更新。 + +`dsh-tool-workflow` 成为第一个生产者。每次工具执行在调用 `ctx.workflows.start()` 之前安装一个紧凑的事件捕获器,因为合法的引擎可能在 `start()` 内部同步发出进度。在调用返回之前,捕获器将观察到的事件按 `WorkflowRunInfo.id` 归约为候选状态;随后选取返回的 `WorkflowRun.id`,丢弃其他候选,报告累积的快照,并将后续匹配事件直接路由。如果 `start()` 抛出异常,捕获器被 dispose(资源释放),其候选状态被丢弃。这在不向 `WorkflowStartRequest` 添加观察者关联、也不要求进度等到 `start()` 返回的前提下,保持了引擎的可替换性。 + +归约器消费既有的 start、phase、log、agent-start、agent-end 和 end 事件,报告一个替换快照,包含当前 phase、最新日志行、活跃子 agent 标签以及 completed/failed/cancelled 计数。它不累积 narration transcript(文本记录);已结束的子 agent 离开活跃集合,变为计数器。`workflow/end`、工具结算或插件 dispose 移除归约器条目和事件捕获器。六种工作流事件及其元数据、成对的子 agent 生命周期、run handle、取消通道和观察者隔离保持不变;第三方观察者可继续直接消费这些事件。 + +更新工具执行/展示文档、生成的事件与 API 目录、工作流包文档以及工作流数据结构目录。ACP 集成覆盖率必须使用脚本化的模型边界测试真实的工作流工具和 worker seam;主 ACP 快照套件新增一个 workflow-progress 场景,因为这改变了面向编辑器的 transcript。 + +## 曾考虑的替代方案 + +**删除工作流 observation 表面。** 在[折叠工作流简化提案](../../rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.md)中被否决:这些事件及其成对生命周期是有意设计的,缺少的是消费方。 + +**让 ACP 直接了解工作流。** 这可以将 `WorkflowRunInfo` 映射到会话和卡片,但会使通用桥接层依赖一个可选能力,并绕过「工具拥有展示意图」的规则。工具进度通道为每个长时间运行的工具解决了相同的路由问题。 + +**将每条进度更新持久化为会话事件。** 这会使实时 narration 可回放,但会用一种状态永久膨胀日志,而该状态的权威持久结果已经是工具调用/结果对。如果可恢复的工作流进度成为产品需求,需要一个工作流日志化设计,而非伪装成持久事实的 UI 快照。 + +## 验收标准 + +- `ToolExecution.reportProgress()` 由注册表所有、agent 作用域、快照化、观察者隔离,且在终态处理开始后返回 `false` 而不分发。 +- ACP 将进度路由到正确的实时会话中的正确调用;不同会话中的并发工作流不能串扰,且 `tool_call_update` 不会出现在其 `tool_call` 之前或终态更新之后。 +- 工作流进度显示当前 phase、最新日志行、活跃子 agent 和结果计数,同时保留所有既有 `workflow/*` 事件和 run 语义;一个在 `start()` 内部同步发出 start、phase、log、child 和 end 事件的 seam 测试引擎不会丢失任何归约器状态。 +- 取消、worker 死亡、工具失败、会话关闭和插件 dispose 释放归约器状态;回放仅发出持久的 pending/final 卡片对。 +- 单元测试、工作流集成测试、ACP 集成测试、快照、类型检查、覆盖率、doc-sync(文档同步门禁)、module-graph、构建和 hygiene 门禁全部通过。 + +## 风险 + +本提案向工具 seam 添加了一个公开的实时进度方法和事件,因此实现方必须精确维护 active/terminal 边界,并在观察者看到快照之前将其分离。pre-start 捕获器可能短暂观察到无关的工作流 run,因此它仅按 run id 持有紧凑的候选状态,并在 `start()` 返回后立即丢弃所有不匹配的候选。一个工作流可能发出大量进度变更;有界归约器避免了 transcript 增长,但在关联完成后仍会为每个有意义的事件发送一条 UI 更新。如果经测量的客户端需要合并更新,这必须是一个带默认值的、经过校验的桥接配置,而非硬编码的节流。瞬态进度在回放时有意消失,因此最终工具结果仍是唯一持久的工作流卡片内容。 diff --git a/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.i18n.yaml b/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.i18n.yaml new file mode 100644 index 0000000000..449f33cbff --- /dev/null +++ b/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-generate-agent-note-index-tables.md: 6e5221f018942a0629f30b6e6f22cedfb9f4145e +2026-07-04-generate-agent-note-index-tables.zh.md: f8ebcd51933b3ad91e0197fc71c0d8aae568bbcf diff --git a/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.md b/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.md index 90c942411d..6e5221f018 100644 --- a/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.md +++ b/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.md @@ -2,6 +2,8 @@ Status: rejected — a centralized generated list is merge-prone and adds little discovery value +English | [中文](2026-07-04-generate-agent-note-index-tables.zh.md) + ## Problem Per-lifecycle/per-class tables would list facts that are fully derivable: an Agent Note's path encodes lifecycle and class, its filename encodes the first-proposed date, and its H1 carries the title. A hand-maintained copy of those facts would also be a high-contention docs hotspot because concurrent Agent Note branches append rows to the same few lines. [The classification Agent Note](../../implemented/process/2026-06-20-agent-note-classification.md) makes the tree itself authoritative. diff --git a/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.zh.md b/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.zh.md new file mode 100644 index 0000000000..f8ebcd5193 --- /dev/null +++ b/.agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.zh.md @@ -0,0 +1,38 @@ +# Agent Note: 生成 Agent Note 索引表 + +Status: rejected — 集中生成的列表容易产生合并冲突,且几乎不增加发现价值 + +[English](2026-07-04-generate-agent-note-index-tables.md) | 中文 + +## 问题 + +按生命周期和分类划分的表格只会列出完全可推导的事实:Agent Note(agent 决策记录)的路径编码其生命周期和分类,文件名编码首次提出日期,H1 承载标题。手工维护这些事实的副本还会成为高冲突文档热点,因为并发的 Agent Note 分支会向相同的几行追加条目。[分类 Agent Note](../../implemented/process/2026-06-20-agent-note-classification.md) 将目录树本身定为权威来源。 + +## 提案 + +保留策展文本,并将列表生成为完全生成的 `.agents/notes/INDEX.md`。共享的 `scripts/agent-note-index.ts` 模块将同时负责目录树遍历器和渲染器。两个轻量消费方会共用它: + +- `scripts/gen-agent-note-index.ts`(`pnpm run gen-agent-note-index`)将根据目录树完整重写 INDEX.md。 +- `scripts/verify-agent-note-classification.ts` 将检查结构,并断言已提交的 INDEX.md 与新鲜渲染结果逐字节一致。 + +添加、移动或删除 Agent Note 时,只需编辑 Agent Note 文件并运行生成器。 + +## 曾考虑的替代方案 + +### 为什么不在 README.md 中使用标记分隔区域? + +README.md 中由标记分隔的表格会混合生成内容与策展文本,因而需要拼接机制并保护周围的契约。专用生成文件至少能将这些关注点分开。 + +### 为什么不采用纯校验器模式? + +它能捕获错误,但每次提案编辑仍然要在手工维护的表格中触碰共享热点。作者已经命名并放置了文件,因此索引副本不增加任何信息。这与[包(package)清单提案](../../proposed/process/2026-06-20-discover-package-inventory.md)对 tsconfig 引用和 knip 配置段所做的手写列表与推导之间的判断相同。 + +## 后果 + +- 生成文件将是显式的,且不包含任何策展区域。 +- H1 格式错误或缺失将是硬错误,因为 H1 为每一行提供标题。 +- 即使可以通过重新运行生成器解决冲突,并发分支仍会修改同一个已提交产物。 + +## 相关 + +已落地的[不建立索引决策](../../implemented/process/2026-07-19-remove-generated-agent-note-index.md)保留目录树和仓库搜索作为发现机制。 diff --git a/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.i18n.yaml new file mode 100644 index 0000000000..6685685e24 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-assembled-assistant-messages-only.md: ba8135a3d63f292cfedd23de8b4b9d43b4455e8c +2026-06-20-assembled-assistant-messages-only.zh.md: 9a42a202425158edd85d7a3f2ef4b0b97e00da90 diff --git a/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.md b/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.md index 62dd7609e8..ba8135a3d6 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.md +++ b/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.md @@ -2,6 +2,8 @@ Status: rejected — high-fidelity chunk replay, partial failed streams, and snapshot replay currently depend on persisted `assistant/chunk` events. Dropping chunks is only viable with a no-information-loss replay/artifact replacement. +English | [中文](2026-06-20-assembled-assistant-messages-only.zh.md) + ## Problem The canonical session log currently persists every `assistant/chunk` exactly as streamed by the model. The [session persistence Agent Note](../../implemented/architecture/2026-06-14-session-persistence.md) chose this for token-level replay fidelity and contiguous `seq`, but the cost has grown: JSONL fixtures are dominated by tiny delta records, snapshot scenarios replay the model by grouping chunk events, ACP load reconstructs prior assistant output from chunks, and any future log reader must distinguish durable message history from token-level trace. diff --git a/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.zh.md b/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.zh.md new file mode 100644 index 0000000000..9a42a20242 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 仅持久化组装后的 assistant 消息,不存储流式分片 + +Status: rejected — 高保真分片回放、部分失败流与快照回放目前依赖持久化的 `assistant/chunk` 事件。只有具备不丢失信息的回放/产物替代方案后,才能删除分片。 + +[English](2026-06-20-assembled-assistant-messages-only.md) | 中文 + +## 问题 + +当前的规范会话日志会持久化模型流式输出的每一个 `assistant/chunk`。[会话持久化 Agent Note(agent 决策记录)](../../implemented/architecture/2026-06-14-session-persistence.md)选择这一方案是为了 token 级别的回放保真度和连续的 `seq`,但其代价日益增长:JSONL fixture(测试前置数据)被大量微小的 delta 记录占据,快照场景通过对分片事件分组来回放模型,ACP(Agent Client Protocol)加载时从分片重建先前的 assistant 输出,而任何未来的日志读取方都必须区分持久的消息历史与 token 级别的追踪。 + +对于成功组装出完整内容的步骤,agent loop(智能体循环)已经追加了一条 `assistant/message`。这正是 `deriveMessages()` 用来构造下一次模型请求的事件。换言之,正常的可恢复会话状态无需分片即已具备;分片是实时渲染和确定性测试的产物,不是必需的会话历史。失败或中止的流则不同:部分 assistant 输出可能仅以分片形式存在,而空的 max-token 步骤可能根本不产生 `assistant/message`。 + +## 提案 + +停止在规范会话日志中存储 `assistant/chunk`。持久日志保留 `assistant/message`、`tool/call`、`tool/result`、`usage`(如保留)以及轮次边界。实时 UI 仍可通过一个刻意设计为瞬态的流事件接收 token 增量。快照回放应将其模型脚本移入显式的 fixture 伴随文件,或从记录的适配器产物中派生,而非将规范的用户会话当作 token 磁带。需要部分失败流输出的场景必须在回放 fixture 中记录该输出。 + +ACP `session/load` 可以将先前的 assistant 消息作为完整内容块回放,而非模拟原始的 token 流。加载后的 transcript(文本记录)无需重现每一个历史 delta;它必须展示相同的已完成 assistant 内容,并以有效的提供方历史恢复运行。 + +## 验收标准 + +- `SessionEventMap` 移除 `assistant/chunk`,或在需要过渡性实时事件时将其标记为非持久化。 +- [会话持久化文档](../../../../packages/session-persistence/session-persistence/README.md)不再要求逐字存储每个流式分片。 +- `llm-replay` 和 ACP 快照使用显式的回放 fixture 格式或伴随文件来存储模型分片。 +- `session/load` 从 `assistant/message` 渲染已完成的 assistant 消息。 +- 存储的日志大幅缩小,且在没有分片缺口的情况下保持 `seq` 连续。 +- 会话格式版本与已记录的 fixture 一并刷新;按预发布格式策略拒绝非当前版本的存储日志。 + +## 放弃了什么 + +规范的用户会话不再能重建旧轮次的精确 token 流。它也会丢失失败或中止流的部分 assistant 输出,除非另有事件或 fixture 记录。对于当前的恢复、加载和快照契约而言,这是过大的信息损失。需要精确确定性流的测试应当直接拥有该 fixture,前提是生产会话日志为用户可见的恢复保留了足够的保真度。 + +## 相关 + +本 Agent Note 取代 [会话持久化](../../implemented/architecture/2026-06-14-session-persistence.md) 中关于分片持久化的决策,并影响 [ACP 快照测试](../../implemented/testing/2026-06-19-acp-snapshot-tests.md)——其当前的回放插件从 `assistant/chunk` 事件派生脚本。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.i18n.yaml new file mode 100644 index 0000000000..e4e6a6613b --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-drop-acp-session-load.md: bae71ba2968bbb10503619e764694a6712572efd +2026-06-20-drop-acp-session-load.zh.md: cdf49039e889f8528f488b53ad01cc13eab2b9d6 diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.md b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.md index b8b9b29987..bae71ba296 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.md +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.md @@ -2,6 +2,8 @@ Status: rejected — Zed is the current target ACP client, advertises and exercises load-capable sessions, and keeps pending-load state for concurrent `session/load`. The bridge should keep `session/load` and make the resume contract solid. +English | [中文](2026-06-20-drop-acp-session-load.zh.md) + ## Problem ACP advertises `loadSession: true` and implements `session/load` by injecting persistence into the bridge, validating cwd against stored metadata, reconstructing an agent from the persisted log, and replaying prior transcript updates to the client. That path has its own race handling, loading-id guard, replay presenter logic, and tests. It also depends on the canonical log retaining enough UI data to reconstruct old chunks and tool presentations. @@ -18,7 +20,7 @@ For now, ACP starts fresh sessions only. `initialize` advertises `loadSession: f - `initialize` does not advertise load support. - The `session/load` handler, loading-id tracking, cwd preflight for loaded sessions, and load replay tests are removed. - Snapshot fixtures no longer rely on load replay presentation. -- [ACP docs](../../../../packages/ui/acp/README.md) describe fresh-session support only. +- [ACP docs](../../../../packages/acp/acp/README.md) describe fresh-session support only. ## What we give up diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.zh.md b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.zh.md new file mode 100644 index 0000000000..cdf49039e8 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 移除 ACP(Agent Client Protocol)session/load,直到恢复具备产品形态 + +Status: rejected — Zed 是当前目标 ACP 客户端,它声明并实际使用支持加载的会话,还为并发的 `session/load` 保留待加载状态。桥接层应保留 `session/load` 并巩固恢复契约。 + +[English](2026-06-20-drop-acp-session-load.md) | 中文 + +## 问题 + +ACP 声明 `loadSession: true` 并实现 `session/load`:向 bridge 注入持久化能力、校验 cwd 与存储元数据的一致性、从持久化日志重建 agent(智能体),并向客户端回放先前的 transcript(文本记录)更新。该路径有自己的竞态处理、loading-id 守卫、回放展示逻辑和测试。它还依赖规范日志保留足够的 UI 数据,以重建旧的分片和工具展示。 + +持久化仍然是基础能力,但编辑器可见的恢复尚未经过产品流程设计。目前没有会话选择器、没有标题/预览元数据,也没有明确的加载失败或部分加载的用户体验。bridge 正在为一个仅被测试、文档和当前目标客户端的会话模型所使用的功能付出复杂度代价。 + +## 提案 + +当前阶段,ACP 仅启动全新会话。`initialize` 声明 `loadSession: false` 或省略该能力,`session/load` 不予支持。持久化仍可供 agent loop(智能体循环)和测试使用;如果其他消费方需要,恢复仍可作为底层工厂存在。编辑器 bridge 应在具备真正的会话选择 UX 和稳定的 load transcript 契约后,再重新引入 `session/load`。 + +## 验收标准 + +- ACP 不再注入 `sessionPersistence`;它原本仅供 `session/load` 使用。 +- `initialize` 不再声明 load 支持。 +- `session/load` handler、loading-id 追踪、已加载会话的 cwd 预检以及 load 回放测试均被移除。 +- 快照 fixture(测试前置数据)不再依赖 load 回放展示。 +- [ACP 文档](../../../../packages/acp/acp/README.md)仅描述全新会话的支持。 + +## 放弃的能力 + +编辑器无法通过 ACP 重新打开先前持久化的会话。这确实是一项产品功能,但当前实现超前于 UX 设计,且将 bridge 绑定到 token 级别的日志回放。保留持久化但移除编辑器 load,可将 bridge 收窄到它当前能干净呈现的工作流。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.i18n.yaml new file mode 100644 index 0000000000..45949d3fcf --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-drop-acp-terminal-meta.md: 79da387ac1a7a0e6767e3bf24baa6039e39ef90d +2026-06-20-drop-acp-terminal-meta.zh.md: d29fd54618611f56fd071a0ee4a63bc207895d89 diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.md b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.md index 8ce4803f73..79da387ac1 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.md +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.md @@ -2,6 +2,8 @@ Status: rejected — Zed is the current target client, and the terminal `_meta` convention is intentional Zed UX with a plain ACP fallback for other clients. +English | [中文](2026-06-20-drop-acp-terminal-meta.zh.md) + ## Problem The ACP bridge implements a Zed-specific terminal-card convention through `_meta.terminal_info`, `_meta.terminal_output`, and `_meta.terminal_exit`. The implemented [rich ACP bash rendering Agent Note](../../implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md) deliberately avoided ACP's client-side `terminal/create` because bash execution belongs in the harness, but still adopted the reference agents' display-only `_meta` convention. That gives a nicer Zed card at the cost of bridge state, capability negotiation, terminal ids, special update mapping, text fallback tests, and exit-pill parsing in `dsh-tool-bash`. diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.zh.md b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.zh.md new file mode 100644 index 0000000000..d29fd54618 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 移除 ACP(Agent Client Protocol)终端 `_meta` 渲染 + +Status: rejected — Zed 是当前目标客户端,terminal `_meta` 约定是有意设计的 Zed UX,同时为其他客户端保留普通 ACP 回退。 + +[English](2026-06-20-drop-acp-terminal-meta.md) | 中文 + +## 问题 + +ACP 桥接层通过 `_meta.terminal_info`、`_meta.terminal_output` 和 `_meta.terminal_exit` 实现了一套 Zed 特有的终端卡片约定。已实现的[富 ACP bash 渲染 Agent Note(agent 决策记录)](../../implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md)刻意回避了 ACP 客户端侧的 `terminal/create`(因为 bash 执行属于 harness 职责),但仍采用了参考 agent(智能体)的纯展示 `_meta` 约定。这在 Zed 中带来了更好的卡片效果,代价是桥接状态、能力协商、终端 id、特殊的 update 映射、文本回退测试,以及 `dsh-tool-bash` 中的 exit-pill 解析。 + +回退路径已经存在:将工具调用和完成输出渲染为普通 ACP 内容块。非 Zed 客户端本来就依赖这条路径,但 Zed 终端卡片是当前目标客户端的功能特性,而非推测性装饰。 + +## 提案 + +忽略 `clientCapabilities._meta.terminal_output`,通过纯 ACP 内容路径渲染 bash 结果。执行仍由 agent 侧的 `dsh-bash` 完成;仅移除展示相关的终端元数据。如果 ACP 日后标准化了 agent 执行的终端,或产品决定 Zed 特有展示值得其维护成本,终端卡片可以再回来。 + +本提案比[收拢工具自有 UI 展示](2026-06-20-generic-tool-rendering.md)更窄:如果通用的 `presentCall`/`presentResult` 保留,本提案不影响它们,只移除终端子形态与 `_meta` 映射。 + +## 验收标准 + +- ACP 不再读取或存储 `_meta.terminal_output` 能力状态。 +- `TerminalRendering`、终端 id、终端 cwd 解析与 `_meta.terminal_*` update 映射从 `@deepseek-ai/dsh-acp` 中消失。 +- `ToolTerminal` 从 `@deepseek-ai/dsh-tools` 中消失,或在展示清理中因未使用而删除。 +- Bash 结果展示不再为终端 pill 解析退出状态。 +- 已实现的[富 ACP bash 渲染 Agent Note](../../implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md) 作为已交付历史保留在 `implemented/` 中;如被本提案取代,则加上交叉链接。 + +## 放弃的内容 + +Zed 用户将失去专用终端卡片:没有 cwd 头部、终端展示或 exit pill。他们仍能以纯内容形式看到命令和输出。在 ACP 桥接层尚未发布、`_meta` 键只是约定而非标准的阶段,这是合理的简化。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.i18n.yaml new file mode 100644 index 0000000000..e09db8fbbf --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-drop-bash-output-spill-files.md: b2bd1a04ee1524bab29814ffa7c22712a83ee5f7 +2026-06-20-drop-bash-output-spill-files.zh.md: c1b5670fac28a90cc4eb229ba0013e39067af8eb diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.md b/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.md index 939255f91e..b2bd1a04ee 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.md +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.md @@ -2,6 +2,8 @@ Status: rejected — full-output recovery is a real bash behavior. A future artifact/blob service may generalize it, but dropping spill files before that replacement would lose useful command output. +English | [中文](2026-06-20-drop-bash-output-spill-files.zh.md) + ## Problem `dsh-bash-local` keeps bounded in-memory output and spills large stdout/stderr streams into private temp files. That requires a private directory, random owner-only file creation, close-failure handling, byte-offset incremental reads, lossy read reporting, path rendering in model-facing text, and cleanup discipline. The tool then tells the model to read a local spill path when output was truncated. diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.zh.md b/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.zh.md new file mode 100644 index 0000000000..c1b5670fac --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 移除 bash 完整输出溢出文件 + +Status: rejected — 完整输出恢复是真实的 bash 行为。未来的产物/blob 服务或许能将其泛化,但在替代方案就位前删除溢出文件会丢失有用的命令输出。 + +[English](2026-06-20-drop-bash-output-spill-files.md) | 中文 + +## 问题 + +`dsh-bash-local` 在内存中保留有界的输出,并将大体量的 stdout/stderr 流溢出到私有临时文件。这要求一个私有目录、仅所有者可写的随机文件创建、关闭失败处理、基于字节偏移的增量读取、有损读取报告、在面向模型的文本中渲染路径,以及清理纪律。当输出被截断时,该工具会告知模型去读取一个本地溢出路径。 + +这解决了一个真实问题,但方式狭隘且有泄漏。溢出路径是一个暴露在模型输出中的进程级文件系统产物,而非具有作用域访问控制、保留策略或 UI 支持的持久化 harness 产物。它还使后台任务的读取变得复杂,因为有损增量读取必须指向一个或两个溢出文件。 + +## 提案 + +保留尾部截断,移除完整输出溢出文件。bash 结果包含有界的尾部内容加一个明确的截断标记;不输出路径。如果用户需要恢复完整输出,则添加一个通用的产物/blob 服务(具有明确的所有权、清理和 UI 渲染),然后让 bash 将大体量输出附加到该服务。 + +本提案可以独立于[通用长时间运行工具运行时](../../implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md)落地。如果后台任务保留,`bash_output` 仍应报告输出已被丢弃,但不再提供溢出路径。 + +## 验收标准 + +- `CollectedOutput` 不再携带溢出路径。 +- `OutputCollector` 仅保留有界缓冲区,删除临时文件机制。 +- `renderResult()` 报告截断时不包含文件系统路径。 +- 测试覆盖尾部截断,不再断言完整输出文件的内容。 +- [docs/defensive-patterns.md](../../../../docs/defensive-patterns.md) 中的安全指导不再将私有溢出文件视为面向模型的接口。 + +## 放弃的能力 + +模型或用户无法再从临时文件恢复大体量命令输出中被省略的前缀。在真正的产物服务出现之前,这是可以接受的。当前的溢出路径为一个生命周期和权限均未经设计的功能引入了过多的定制机制。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.i18n.yaml new file mode 100644 index 0000000000..698d5a5ad6 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-drop-durable-step-boundaries.md: c5c4f269a378e334c4dc509d1288146d77d9a520 +2026-06-20-drop-durable-step-boundaries.zh.md: f2150699c74b16557d936d6833fcba02e7d76e69 diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.md b/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.md index b2bf42a348..c5c4f269a3 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.md +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.md @@ -2,6 +2,8 @@ Status: rejected — `step/end` is the durable indication that a model step finished, and keeping the symmetric `step/start` / `step/end` pair makes crash repair, invariants, and transcript inspection clearer than inferring completion from adjacent step-scoped events. +English | [中文](2026-06-20-drop-durable-step-boundaries.zh.md) + ## Problem The session log stores `step/start` and `step/end` events even though every step-scoped event already carries `{ turn, step }`: assistant chunks, assistant messages, tool calls, tool results, usage, and errors. `deriveMessages()` ignores step boundaries, ACP ignores them for UI, and the main consumers are invariants, tests, snapshot expected outputs, and crash repair. diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.zh.md b/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.zh.md new file mode 100644 index 0000000000..f2150699c7 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.zh.md @@ -0,0 +1,32 @@ +# Agent Note: 移除持久化的步骤边界事件 + +Status: rejected — `step/end` 是模型步骤已完成的持久信号;保留对称的 `step/start` / `step/end` 对,比从相邻的步骤作用域事件推断完成状态更便于理解崩溃修复、不变式与 transcript(文本记录)检查。 + +[English](2026-06-20-drop-durable-step-boundaries.md) | 中文 + +## 问题 + +会话日志存储了 `step/start` 和 `step/end` 事件,尽管每个步骤作用域的事件本身已经携带 `{ turn, step }`:assistant 分片、assistant 消息、工具调用、工具结果、用量和错误。`deriveMessages()` 忽略步骤边界,ACP(Agent Client Protocol)在 UI 层面也忽略它们,主要消费方是不变式检查、测试、快照预期输出和崩溃恢复。 + +被否决的论点是:边界事件使日志更像仪式而非信息。实际上,`step/end` 是具体信息:读者无需从下一个事件推导状态,就能判断一次模型请求是已完成、已崩溃还是正在修复。同样,一个孤立的 `step/start` 对于「模型请求已发起但在产生任何分片之前就失败了」的场景也有价值。 + +## 提案 + +将轮次作为唯一的持久化边界。`step/start` 和 `step/end` 将从 `SessionEventMap` 中移除;在需要分组的事件上保留数值型 `step` 字段。agent loop(智能体循环)递增步骤计数器并以该编号记录步骤作用域的事件,但不再追加开/关边界事件。消费方通过共享 `(turn, step)` 的连续事件推断步骤分组。 + +不变式插件应当强制步骤作用域的事件在一个已打开的轮次内具有有效的正整数步骤编号,而非要求独立的边界记录包围它们。崩溃恢复不应合成 `step/end`;如果一个被中断的轮次被保留,修复路径仍然可以关闭该轮次而无需捏造步骤边界记录。 + +## 验收标准 + +- `SessionEventMap` 不再包含 `step/start` 或 `step/end`。 +- agent loop 中不再有 `closeStep()` 终结路径。 +- ACP 快照和持久化契约 fixture(测试前置数据)不再期望步骤边界行。 +- `deriveMessages()` 和回放从步骤作用域的事件推导出相同的消息历史。 +- [事件分类体系文档](../../../../docs/architecture.md)将轮次描述为持久化边界,将步骤描述为步骤作用域记录上的一个字段。 +- 会话格式版本和已记录的 fixture 被刷新;按预发布格式策略,非当前版本的已存储日志被拒绝。 + +## 放弃了什么 + +日志不再将「一次模型请求已发起但进程死亡前未产生任何事件」记录为持久化事实,也不再有显式的「此步骤已完成」标记。在会话日志仍是持久化回放与审计表面的当下,这一损失不可接受。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.i18n.yaml new file mode 100644 index 0000000000..a9913a8849 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-drop-unused-session-lineage.md: 605f1949999435b24404e0c5a72320416303ae52 +2026-06-20-drop-unused-session-lineage.zh.md: 981f44189f4b8f11f513261db7094afdc650dffa diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.md b/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.md index c85e943476..605f194999 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.md +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.md @@ -2,6 +2,8 @@ Status: rejected — `parentSession` is part of the documented fork/sub-agent seam and is already preserved by the agent/session resume path. The field is future-facing, but it is not accidental dead state. +English | [中文](2026-06-20-drop-unused-session-lineage.zh.md) + ## Problem `SessionHeader.parentSession` records the session a new session was forked from. It is defined in `dsh-session`, preserved by persistence backends, copied through resume, documented as lineage metadata, and covered by round-trip tests. The repo has no production fork UI or sub-agent flow that reads it. The planned sub-agent/fork seam is still a TODO, so the field is currently stored future shape. diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.zh.md b/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.zh.md new file mode 100644 index 0000000000..981f44189f --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 移除未使用的会话血缘元数据 + +Status: rejected — `parentSession` 是已记录的 fork/subagent seam 的一部分,并已由 agent(智能体)/会话恢复路径保留。该字段面向未来,但并非意外遗留的死状态。 + +[English](2026-06-20-drop-unused-session-lineage.md) | 中文 + +## 问题 + +`SessionHeader.parentSession` 记录新会话从哪个会话 fork 而来。它在 `dsh-session` 中定义,被持久化后端保留,在恢复流程中复制,作为血缘元数据被文档记录,并有往返测试覆盖。然而仓库中没有任何生产环境的 fork UI 或 subagent 流程读取它。计划中的 subagent/fork seam 仍是 TODO,因此该字段目前只是预存的未来形状。 + +单个文件的成本虽小,但在格式层面影响面广:每个后端 schema 和元数据序列化器都在保留一个尚无已完成功能读取的值。由于 header 是磁盘契约,即使是占位字段也会成为未来重构必须维护、迁移或有意打破的东西。 + +## 提案 + +移除 `parentSession`,使其不再属于 `SessionHeader`,直到真正的 fork/恢复功能需要血缘信息时再引入。如果存在相应 API,fork 仍然可以用先前事件来初始化新会话,但持久化的父指针应当与读取它的功能和解释它的 UX 一同引入。 + +如果血缘信息回归,届时再决定它应放在不可变 header 中、会话图索引中,还是作为一等事件。当前字段不应预先锁定那个设计。 + +## 验收标准 + +- `SessionHeader` 仅包含 version、id、createdAt 和可选的 cwd。 +- JSONL 与 SQLite 元数据 schema 不再存储父会话 id。 +- 恢复与列表 API 不再往返传递 `parentSession`。 +- 文档和测试移除没有生产消费方支撑的 fork 血缘声明。 +- 会话格式版本、后端 schema 版本与记录的 fixture(测试前置数据)按需刷新;按预发布格式策略,非当前版本的存储数据将被拒绝,不提供迁移路径。 + +## 放弃了什么 + +代码库失去了一个为未来 fork/subagent UX 预备的现成血缘钩子。这是有意为之。该字段在功能存在时很容易重新引入,而未发布的立场允许格式变更无需迁移。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.i18n.yaml new file mode 100644 index 0000000000..5f3e15ee98 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-fold-session-persistence-interface.md: 895b868b2a80d8655284bae1364a85e19e174da7 +2026-06-20-fold-session-persistence-interface.zh.md: c124b16531f904eb72cb8ac3842642d819309e14 diff --git a/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.md b/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.md index 8e5d59172f..895b868b2a 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.md +++ b/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.md @@ -2,6 +2,8 @@ Status: rejected — the separate persistence interface package is the intended modular capability seam for durable backends. Folding it into `dsh-session` would reduce package count at the cost of a cleaner backend boundary. +English | [中文](2026-06-20-fold-session-persistence-interface.zh.md) + ## Problem `dsh-session-persistence` is an interface package whose main concepts are already owned by `dsh-session`: `SessionHeader`, `SessionEvent`, `SessionId`, `session/event`, and `session/flush`. The package adds the abstract `SessionPersistence` service, the shared write coordinator, and contract helpers. Backend packages depend on it, and `agent-loop` has to optionally find a sibling service for resume. diff --git a/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.zh.md b/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.zh.md new file mode 100644 index 0000000000..c124b16531 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 将持久化接口合并进 dsh-session + +Status: rejected — 独立的持久化接口包是为持久后端设计的模块化能力 seam。将其折叠进 `dsh-session` 虽能减少包数量,却会牺牲更清晰的后端边界。 + +[English](2026-06-20-fold-session-persistence-interface.md) | 中文 + +## 问题 + +`dsh-session-persistence` 是一个接口包(package),其核心概念已经由 `dsh-session` 拥有:`SessionHeader`、`SessionEvent`、`SessionId`、`session/event` 与 `session/flush`。该包额外添加了抽象的 `SessionPersistence` 服务、共享写入协调器和契约辅助工具。后端包依赖它,`agent-loop`(智能体循环)也需要可选地查找一个同级服务来实现恢复。 + +当持久化还是一个全新的可替换后端设计时,能力 seam 的拆分是合理的。但在可变摘要被移除之后,这个接口包基本上只是包装了会话日志自身的存储关切。继续保持独立可能带来的仪式感多于清晰度。 + +## 提案 + +将抽象的 `SessionPersistence` 服务、协调器和持久化契约辅助工具移入 `dsh-session`。JSONL 和 SQLite 仍作为独立的后端包,注册由会话包拥有的服务。这样既保留了后端可替换性,又删除了一个支撑包和一条跨包 seam。 + +实施 PR(Pull Request)应更新[能力 seam](../../implemented/architecture/2026-06-13-capability-seams.md) 指南,补充此例外:持久化不同于 bash 或 LLM(大语言模型),因为它的词汇和生命周期事件本就属于会话包的核心领域。 + +## 验收标准 + +- `@deepseek-ai/dsh-session-persistence` 作为包被移除。 +- `dsh-session` 导出持久化服务类型、协调器和契约辅助工具。 +- JSONL 和 SQLite 后端包直接依赖 `dsh-session`。 +- `agent-loop` 的恢复功能使用会话包拥有的服务键。 +- [会话持久化](../../implemented/architecture/2026-06-14-session-persistence.md)、[共享持久化写入协调器](../../implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md)与[包文档](../../../../packages/session-persistence/session-persistence/README.md)说明后端实现为何仍保持独立。 + +## 放弃了什么 + +`dsh-session` 变得更重:它同时拥有内存日志和持久化接口。这就是代价。如果第三方持久化后端已经形成公开生态,独立的接口包会是更清晰的 SDK 边界;但在预发布阶段,在尚无外部消费方时,多出的包看起来更像是过早的抽象。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.i18n.yaml new file mode 100644 index 0000000000..da93063670 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-generic-tool-rendering.md: 6fc610546da04e7d1e16fc17ada87483a142aa3c +2026-06-20-generic-tool-rendering.zh.md: 11386b87d845129950a8473eb1cf4ea6ce697ac8 diff --git a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.md b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.md index dbc6ffed44..6fc610546d 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.md +++ b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.md @@ -2,6 +2,8 @@ Status: rejected — tool-owned presentation should wait for more real tools before being generalized or deleted. Bash and ACP currently need the existing richer presentation path. +English | [中文](2026-06-20-generic-tool-rendering.zh.md) + ## Problem Tools can define `presentCall()` and `presentResult()` callbacks that return `ToolCallPresentation`, `ToolResultPresentation`, and optional `ToolTerminal` fields. The code itself flags the design as muddy: title, kind, raw input, content, terminal cwd, terminal output, exit code, and signal grew incrementally into a bag of optional fields. ACP then maintains pending call state to pair a result with the original args, creates replay-only presenters on `session/load`, and maps terminal subfields into Zed-specific `_meta`. `dsh-tool-bash` even parses exit status back out of rendered text because the pure replay-safe presenter no longer has the structured `BashRunResult`. diff --git a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.zh.md b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.zh.md new file mode 100644 index 0000000000..11386b87d8 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 收拢工具自有的 UI 展示逻辑 + +Status: rejected — 工具拥有的呈现机制应等到出现更多真实工具后再进行泛化或删除。Bash 与 ACP(Agent Client Protocol)目前仍需要现有的丰富呈现路径。 + +[English](2026-06-20-generic-tool-rendering.md) | 中文 + +## 问题 + +工具可以定义 `presentCall()` 和 `presentResult()` 回调,返回 `ToolCallPresentation`、`ToolResultPresentation` 以及可选的 `ToolTerminal` 字段。代码本身就标记了这个设计的混乱:title、kind、raw input、content、terminal cwd、terminal output、exit code 和 signal 逐步增长为一堆可选字段。ACP 随后维护 pending call 状态以将 result 与原始 args 配对,在 `session/load` 时创建仅用于回放的 presenter,并将 terminal 子字段映射为 Zed 特有的 `_meta`。`dsh-tool-bash` 甚至从渲染后的文本中反向解析退出状态,因为纯回放安全的 presenter 已经拿不到结构化的 `BashRunResult`。 + +真正的第一方用途是为 ACP 提供 bash 展示。这不足以作为冻结一个跨包(package)UI 展示 API 的依据。 + +## 提案 + +暂时移除工具自有的 UI 展示回调。规范的工具事件已经携带工具名、原始参数字符串、结果内容和错误状态。UI 从这些字段渲染一个通用的工具卡片。工具特有的富展示可以在至少有两个真实工具和两个真实消费方来验证词汇之后,以带标签的 render-intent union 形式回归。 + +## 曾考虑的替代方案 + +作为更小的替代方案,可以在一个 PR(Pull Request)中将当前的可选字段集合替换为一个显式 union;但如果目标是简化,更彻底的做法是删除回调、保留通用路径。 + +## 验收标准 + +- `ToolDefinition` 移除 `presentCall` 和 `presentResult`。 +- `ToolCallPresentation`、`ToolResultPresentation`、`ToolTerminal` 和 `ToolCallKind` 消失,除非一个最小的通用 UI 类型仍需要其中之一。 +- ACP 不再维护 presenter pending 状态,也不再在实时流式输出/加载回放期间调用工具回调。 +- `dsh-tool-bash` 不再解析渲染文本来恢复退出状态以供 UI pill 使用。 +- 快照预期输出展示通用工具卡片和文本结果。 + +## 放弃了什么 + +Bash 失去其自定义的终端风格卡片和模型生成描述的放置位置。回退方案仍然合理:命令作为工具输入展示,输出作为文本展示。富展示应当在产品拥有足够的 UI/工具多样性、足以支撑一份稳定的展示契约时再行设计。 + +## 相关 + +这是[移除 ACP terminal 元数据](2026-06-20-drop-acp-terminal-meta.md)的宽泛版本。如果本 Agent Note(agent 决策记录)被接受,那个更窄的 Agent Note 就不再必要。 diff --git a/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.i18n.yaml new file mode 100644 index 0000000000..3ca6a50ef7 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-retire-mid-turn-steering.md: a8812b3222739244d77f4d4dab60cf7c0cd6907d +2026-06-20-retire-mid-turn-steering.zh.md: 81a211a167daeb8c57b98f2a1c1451dbc54d09e4 diff --git a/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.md b/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.md index b26243f197..a8812b3222 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.md +++ b/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.md @@ -2,6 +2,8 @@ Status: rejected — mid-turn steering is an intentional agent capability for between-step user/plugin input and future goal/loop workflows. It is complexity with a product direction, not an accidental duplicate of `send()`. +English | [中文](2026-06-20-retire-mid-turn-steering.zh.md) + ## Problem The agent exposes two user-message paths that look close but have different lifecycle semantics: `send()` queues a normal user turn, while `steer()` injects a message between steps of the currently running turn and falls back to `send()` when idle. That distinction leaks through the whole stack: `Agent.steer()` is public API, the session log has a durable `steering/message` event, the agent event taxonomy has `agent/steering`, the loop maintains a steering FIFO beside the queued-message FIFO, cancellation clears both queues, and `deriveMessages()` has to render steering as a tagged synthetic user message rather than a normal prompt. diff --git a/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.zh.md b/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.zh.md new file mode 100644 index 0000000000..81a211a167 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 移除轮次中途引导 + +Status: rejected — 轮次中途 steering(中途引导)是一项有意设计的 agent(智能体)能力,用于接收步骤之间的用户/插件输入以及未来的 goal/loop 工作流。它是面向产品方向的复杂度,而非 `send()` 的意外重复。 + +[English](2026-06-20-retire-mid-turn-steering.md) | 中文 + +## 问题 + +agent 暴露了两条用户消息路径,外观相近但生命周期语义不同:`send()` 将一条普通用户轮次排入队列,而 `steer()` 在当前运行轮次的步骤之间注入一条消息,空闲时则回退为 `send()`。这一区分贯穿整个栈:`Agent.steer()` 是公开 API;会话日志有持久化的 `steering/message` 事件;agent 事件分类体系有 `agent/steering`;agent loop(智能体循环)在排队消息 FIFO 之外还维护一个 steering FIFO;取消操作需要清空两个队列;`deriveMessages()` 必须将 steering 渲染为带标签的合成用户消息,而非普通提示词。 + +续行 seam 进一步放大了成本。`agent/turn-continuation` 默认条件为 `hadToolCalls || steeringInjected`,因此同一轮次内的 steering 消息即使模型未请求工具调用,也会强制循环再次调用模型。注释中提到了未来 `/goal`、`/loop` 和预算守卫的用途,但当前仓库没有生产级监听器;只有测试注册了该 waterfall(瀑布式事件)。另外,唯一调用 `steer()` 的生产 UI 是 stdio 演示。ACP(Agent Client Protocol)在轮次运行期间已经通过普通队列发送提示词。 + +## 提案 + +暂时删除轮次中途的用户 steering。`Agent.send()` 成为提交用户内容的唯一公开方式;当 agent 正在运行时,内容等待下一个轮次。循环仅因工具调用而在轮次内继续,不因用户在某个步骤运行期间输入内容而继续。调用方若要中断当前轮次,使用 `cancel()` 后再 `send()`。 + +移除 `Agent.steer()`、steering FIFO、`steering/message`、`agent/steering`、由 steering 驱动的续行逻辑,以及取消操作中区分排队消息与 steering 消息的逻辑。除非实现 PR(Pull Request)发现了生产级监听器,否则在同一变更中一并移除 `agent/turn-continuation`;没有 steering 后,当前仓库不再有具体的续行消费方。如果将来真正的预算或目标插件需要强制续行,应以该插件为具体消费方重新引入一个更窄的 seam。 + +## 验收标准 + +- `Agent` 暴露唯一的用户消息入口 `send()`。 +- 持久化会话事件词汇不再包含 `steering/message`。 +- `deriveMessages()` 渲染普通用户消息和上下文注入,不存在 steering 标签路径。 +- 循环只有一个排队消息 FIFO,没有同轮次用户消息续行路径。 +- `agent/turn-continuation` 被移除,或收窄到有具名的生产级消费方。 +- stdio UI 和文档将运行期间的输入描述为「排入下一轮次的输入」。 +- 会话格式版本和已录制的 fixture(测试前置数据)已刷新;非当前版本的存储日志按预发布格式策略被拒绝。 + +## 放弃了什么 + +用户无法在模型处于工具步骤之间时添加同轮次 steering 内容。这种行为在理论上对「你已经在工作了,也考虑一下 X」的场景有用,但它不是 ACP 当前暴露的行为,且使轮次边界更难推理。更简单的行为是合理的:用户输入成为下一条提示词,取消操作仍是替换进行中工作的显式手段。 + +## 相关 + +本提案与[移除持久化步骤边界](2026-06-20-drop-durable-step-boundaries.md)天然配对,因为移除同轮次 steering 和 `agent/turn-continuation` 后,工具调用成为一个轮次包含多个模型步骤的唯一原因。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.i18n.yaml new file mode 100644 index 0000000000..66138d0995 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-single-session-acp-bridge.md: e99de76854390a0979d1b66866d1d48aacbc0036 +2026-06-20-single-session-acp-bridge.zh.md: 660e4ccf6f2fba8672315bfed30872870f401554 diff --git a/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.md b/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.md index 83c6f598d4..e99de76854 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.md +++ b/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.md @@ -2,6 +2,8 @@ Status: rejected — Zed is the current target ACP client and its ACP implementation is explicitly multi-session: it stores live sessions in a `HashMap<SessionId, AcpSession>`, tracks `pending_sessions`, joins concurrent loads for the same id, and tests close-during-load behavior. +English | [中文](2026-06-20-single-session-acp-bridge.zh.md) + ## Problem The ACP bridge now supports multiple live sessions on one JSON-RPC connection. That capability brings multi-entry session maps, reverse session/agent lookups, per-session prompt state, loading ids, demux for every event, cross-session teardown, and isolation concerns for future permission prompts and background tasks. The older [multi-session ACP proposal](../../implemented/feature/2026-06-14-acp-multi-session.md) still tracks the unfinished permission-ownership piece; this Agent Note is the competing simplification path. diff --git a/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.zh.md b/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.zh.md new file mode 100644 index 0000000000..660e4ccf6f --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 将 ACP(Agent Client Protocol)桥接恢复为每连接一个活跃会话 + +Status: rejected — Zed 是当前目标 ACP 客户端,其 ACP 实现明确支持多会话:它把活跃会话存入 `HashMap<SessionId, AcpSession>`,跟踪 `pending_sessions`,合并同一 id 的并发加载,并测试加载期间关闭的行为。 + +[English](2026-06-20-single-session-acp-bridge.md) | 中文 + +## 问题 + +ACP 桥接现在支持在一条 JSON-RPC 连接上承载多个活跃会话。这一能力带来了多条目会话映射、反向会话/agent(智能体)查找、逐会话的提示词状态、加载中 id、每条事件的解复用、跨会话拆除,以及未来权限提示与后台任务的隔离问题。较早的[多会话 ACP 提案](../../implemented/feature/2026-06-14-acp-multi-session.md)仍在追踪未完成的权限归属部分;本 Agent Note(agent 决策记录)是与之竞争的简化路径。 + +产品目标已经证明它需要在一个 harness 进程上承载并发的编辑器对话:Zed 的 ACP 连接拥有多个会话和加载状态。快照回放层仍然避免并发模型流,因为其回放条目是位置相关的;这是测试 fixture(测试前置数据)的局限,而非移除桥接多路复用的理由。 + +## 提案 + +将 ACP 的范围收回到每连接一个活跃会话。`session/new` 或 `session/load` 创建唯一的会话记录;在现有会话被 dispose(资源释放)或连接关闭之前,第二个活跃会话请求将被拒绝。如果编辑器需要多个聊天标签页,可以启动多个 agent 子进程,直到桥接具备具体的多会话 UX 和权限模型。 + +移除多会话映射和解复用逻辑,改用单一的 `SessionRecord | undefined` 即可。桥接仍可保留使 dispose 正确的 agent/会话生命周期 seam;简化仅针对在同一传输层上多路复用多个活跃会话这一点。 + +## 验收标准 + +- ACP 每连接只有一条活跃会话记录。 +- 当该记录存在时,`session/new` 和 `session/load` 拒绝请求。 +- 事件处理器不再在 `Map<sessionId, record>` 上做解复用。 +- 多会话测试被移除,或移至继续支持多路复用的提案下。 +- 既有的[多会话 ACP 提案](../../implemented/feature/2026-06-14-acp-multi-session.md)更新为链接本 Agent Note,并继续作为当前方向。 + +## 放弃了什么 + +ACP 客户端无法在一个服务器进程上承载多个并发对话。这是一项有实质意义的能力削减。对于一个尚未发布的 harness 而言,更简单的模型仍然合理:一个编辑器对话对应一个 agent 进程,跨会话的权限/后台任务隔离不再是活跃的正确性负担。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.i18n.yaml new file mode 100644 index 0000000000..98845d7e03 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-06-20-truncate-interrupted-turns.md: af18618ad4c41af125e37c51b9fd971dd8eae64e +2026-06-20-truncate-interrupted-turns.zh.md: a20d0169f7735aa7a9437c10c958580c00704171 diff --git a/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.md b/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.md index a685765197..af18618ad4 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.md +++ b/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.md @@ -2,6 +2,8 @@ Status: rejected — a single turn can contain substantial real work, including many steps and large tool output. Preserving interrupted turns is preferable to silently dropping that tail on load. +English | [中文](2026-06-20-truncate-interrupted-turns.zh.md) + ## Problem The current persistence contract preserves a final turn that was durably written but never closed. On load, `interruptedTurnClosers()` scans the tail, synthesizes error `tool/result` events for unanswered tool calls, appends a `step/end` when a step is open, appends `turn/end { kind: 'interrupted' }`, and asks the backend to durably commit that repair. The coordinator, JSONL backend, SQLite backend, session event vocabulary, invariants, docs, and tests all model this synthetic close path. diff --git a/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.zh.md b/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.zh.md new file mode 100644 index 0000000000..a20d0169f7 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 加载时截断被中断的最终轮次 + +Status: rejected — 单个轮次可以包含大量真实工作,包括多个步骤和大量工具输出。保留被中断的轮次,优于在加载时静默丢弃这段尾部。 + +[English](2026-06-20-truncate-interrupted-turns.md) | 中文 + +## 问题 + +当前的持久化契约会保留已持久写入但从未关闭的最终轮次。加载时,`interruptedTurnClosers()` 扫描尾部,为未应答的工具调用合成 error `tool/result` 事件,在步骤处于打开状态时追加 `step/end`,追加 `turn/end { kind: 'interrupted' }`,并要求后端持久提交这次修复。协调器、JSONL 后端、SQLite 后端、会话事件词汇、不变式、文档和测试都对这条合成关闭路径进行了建模。 + +这是一套庞大的机制,只为保留上次崩溃轮次中的部分工作。它还会凭空创造从未发生过的事件。合成的工具结果虽然有用(因为它使提供方历史保持合法),但也意味着恢复后的日志中包含了模型可见、却并非任何工具产出的文本。当前设计在尚无已发布产品、也没有真实恢复 UX 来证明部分轮次恢复确有价值的情况下,就优化了最大化尾部保留。 + +## 提案 + +加载时只保留最后一个已完成的轮次。后端仍然容忍并截断撕裂的最终记录,但如果解析出的持久前缀止于一个打开的 `turn/start` 之后,规范的修复方式是丢弃上一个 `turn/end` 之后的所有事件。不合成 `tool/result`,不合成 `step/end`,不追加 `turn/end { interrupted }`,也不引入 `interrupted` 轮次结束原因。 + +这使持久化的轮次边界变得简单:一个已完成的 `turn/end` 就是检查点。最后一个检查点之后的内容都是崩溃尾部。下一次提示词从最后一个已知合法的提供方 transcript(文本记录)恢复,而不是从部分重建的最终轮次恢复。 + +## 验收标准 + +- `TurnEndReasonMap` 移除 `interrupted` 变体。 +- `interruptedTurnClosers()` 及其测试删除。 +- 持久化协调器的修复钩子截断后端特有的撕裂/打开尾部状态,不追加关闭事件。 +- [会话持久化文档](../../../../packages/session-persistence/session-persistence/README.md)说明加载返回最后一个已完成的轮次,不包含部分最终轮次。 +- 快照与契约测试随其所固定的行为一同更新。 +- 会话格式版本与记录的 fixture(测试前置数据)刷新;按预发布格式策略,非当前版本的存储日志被拒绝,不提供迁移路径。 + +## 放弃的内容 + +崩溃可能丢失最终轮次中的真实工作:上一个 `turn/end` 之后追加的助手文本、工具调用和工具输出。这是有意为之的简化。产品尚未发布,最终轮次恢复的语义未经用户验证,而一个干净的「已完成轮次即检查点」模型在解释、测试和实现上都容易得多。未来若需「恢复部分崩溃工作」功能,应设计为面向用户的显式恢复视图,而非静默插入规范 transcript 的合成事件。 + +## 相关 + +本提案是对[会话持久化](../../implemented/architecture/2026-06-14-session-persistence.md)与[轮次封闭不变式](../../implemented/architecture/2026-06-15-turn-enclosure-invariant.md)的直接简化。它还移除了持久化步骤边界事件的大部分动机,使[移除持久化步骤边界事件](2026-06-20-drop-durable-step-boundaries.md)的改动更小。 + +<!-- agent-note-format: alternatives-not-recorded (pre-format Agent Note) --> diff --git a/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.i18n.yaml b/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.i18n.yaml new file mode 100644 index 0000000000..9720d3c114 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-04-prune-unimplemented-subagent-vocabulary.md: 890aca31f09f97ab6d9bf7c00f738d894695d9ad +2026-07-04-prune-unimplemented-subagent-vocabulary.zh.md: 7837759604a30ee8f58d922bb5f55f6730d1ddcb diff --git a/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.md b/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.md index 1f07492c9c..890aca31f0 100644 --- a/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.md +++ b/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.md @@ -2,6 +2,8 @@ Status: rejected — the deferred capability vocabulary (`outputSchema`/`structured`, `toolFilter`, `sendMessage`/`resume`) is intentionally reserved surface: the seam advertises the full intended contract ahead of its implementations by design, so providers and consumers grow into a stable shape rather than re-negotiating it per capability. The consumer-evidence analysis below records the decision-time state. +English | [中文](2026-07-04-prune-unimplemented-subagent-vocabulary.zh.md) + ## Problem The [subagent seam](../../implemented/feature/2026-06-21-subagent-capability-seam.md) shipped a two-tier capability design: start-time capability flags checked by the service, and optional runtime methods on `SubagentRun`. Three start-time features and both optional runtime methods have zero implementations and zero callers: diff --git a/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.zh.md b/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.zh.md new file mode 100644 index 0000000000..7837759604 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 裁剪未实现的 subagent seam 词汇 + +Status: rejected — 延后的能力词汇(`outputSchema`/`structured`、`toolFilter`、`sendMessage`/`resume`)是有意保留的接口面:该 seam 按设计先于实现声明完整的预期契约,使提供方与消费方沿稳定形状演进,而非针对每项能力重新协商。下方的消费方证据分析记录了决策时的状态。 + +[English](2026-07-04-prune-unimplemented-subagent-vocabulary.md) | 中文 + +## 问题 + +[subagent seam](../../implemented/feature/2026-06-21-subagent-capability-seam.md) 交付了一套两层能力设计:启动时由服务检查的能力 flag,以及 `SubagentRun` 上的可选运行时方法。三个启动时功能和两个可选运行时方法的实现数与调用数均为零: + +- **`outputSchema`/`structured` 与 `toolFilter`**(`SubagentCapabilities`、`SubagentStartRequest`、`SubagentResult`,位于 `packages/subagent/subagent/src/types.ts`):在作出决策时,每个真实提供方都声明 `outputSchema: false, toolFilter: false`(`packages/subagent/subagent-spawn/src/index.ts`、`packages/subagent/subagent-fork/src/index.ts`、`packages/subagent/subagent-acp/src/index.ts`);唯一的生产环境 `ctx.subagents.start` 调用方(`packages/subagent/tool-subagent/src/index.ts`)构造 `{ prompt, parent, signal?, agentOptions? }`,结构上无法设置这两个字段;`structured` 仅出现在脚本化测试 fixture(测试前置数据)中。服务的能力检查包含两行 assert,其唯一执行者是拒绝测试。 +- **`SubagentRun.sendMessage` / `SubagentRun.resume`**(同一文件):没有任何提供方实现——包括 mock 也没有;spawn spec 断言的正是它们的*缺失*。 + +在作出决策时,`dsh-subagent` 依赖 `dsh-tools` 的唯一原因是 `outputSchema` 的 schema 类型(现为 `ObjectJsonSchema`)。三个后续 subagent 工作流(按会话快照回放、fork seed 边界、ACP(Agent Client Protocol)后端)都围绕这块接口面落地,却没有增长出哪怕一个消费方。 + +## 提案 + +从 seam 中移除 `outputSchema`/`structured`、`toolFilter`、`sendMessage` 与 `resume`;将 `SubagentCapabilities` 缩减为 `{ depthLimit }`;删除两行能力 assert、三个提供方上的 all-false flag、脚本化 fixture 的 structured 分支和能力旋钮,以及为固定被移除接口面而存在的测试。`dsh-tools` 的 peer/dev 依赖应从 `packages/subagent/subagent/package.json` 中删除。更新 [subagent.md](../../../../docs/core-data-structures/subagent.md) 中的粘贴内容与 type-equiv manifest(元数据清单),以及受影响的提供方 README。实现 PR(Pull Request)按照 [implemented/AGENTS.md](../../implemented/AGENTS.md) 修订 seam Agent Note(agent 决策记录)的能力目录。 + +**保留** `depthLimit`/`maxDepth` 与能力检查。进程内后端已强制执行该限制,尽管当前发布的工具尚未设置它。递归是已知的 seam 风险,因此恰当的后续工作是提供一个工具默认值,而非删除正在工作的强制逻辑。 + +审视过但有意不动的相邻接口面:`SubagentService.getProvider()`/`list()` 仅有测试 harness 消费方,但 [prune-dead-seam-methods 实现说明](../../implemented/simplification/2026-06-20-prune-dead-seam-methods.md)恰好记录了这种形态从 bash 执行器中被移除后又被回退的经过——对于一个基于已跟踪 map 的单行访问器而言,测试 harness 就是消费方。`SubagentRunEndInfo.lastAssistantMessage` 是一个已记录的保留项([subagent 观测/丰富化 Agent Note](../../implemented/feature/2026-06-30-subagent-observe-enrich.md)的评审删除了 `agentType` 但有意保留了它,因为它是进程外子 agent(智能体)唯一的最终消息通道);它当前未接通的桥接转发是一个待补的缺口或待记录的消费方,不是本 Agent Note 要裁剪的接口面。 + +这是[从持久化 seam 裁剪死方法](../../implemented/simplification/2026-06-20-prune-dead-seam-methods.md)在 seam 词汇层面的回响:每个实现都必须为无人声明的成员,甚至更弱,因为这里连一个实现都没有。 + +## 曾考虑的替代方案 + +### 为什么不保留? + +两类能力的设计是 seam Agent Note 的核心亮点,日后重新添加 `outputSchema` 会涉及多个文件。但该设计以 `depthLimit` 作为活跃示例、以 Agent Note 作为记录仍然成立;而且 seam Agent Note 本身承认已交付的 `toolFilter` 形态是错误的(真正的强制需要在子 agent 上下文中实施 `tools/pre-execute` deny,而非 schema 过滤)——该 deny 原语已存在于拦截 seam 上,因此基于真实实现提供方重新添加时,将固定出一份比当前推测性契约更好的契约。 + +## 验收标准 + +- 被移除的拼写仅出现在本 Agent Note 和修订后的 seam Agent Note 中;`SubagentCapabilities` 为 `{ depthLimit: boolean }`;`dsh-tools` 依赖边已消除(`hygiene` 绿色)。 +- 深度强制测试不变且绿色。 + +## 风险 + +subagent 生命周期事件在结束载荷上携带 `lastAssistantMessage`——该增强位于服务模块中,不在本 Agent Note 缩减的 seam 词汇范围内;observe-enrich Agent Note 记录了因缺少消费方而删除 `agentType` 兄弟字段的判断,本 Agent Note 延续了这一判断。CC 钩子桥接是这些生命周期事件的第一个外部消费方,它只读取事件载荷,不涉及本文移除的任何接口面;observe-enrich Agent Note 推迟的控制流重设计将实现 `resume` 列为自身的未来工作——恰好是本 Agent Note 模式所预期的重新添加触发点。 diff --git a/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.i18n.yaml b/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.i18n.yaml new file mode 100644 index 0000000000..1b4e9c4b54 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-12-collapse-workflow-to-foreground-core.md: 629e2140523c3ae7caf533de99821206d05f1b8e +2026-07-12-collapse-workflow-to-foreground-core.zh.md: 3ae5e026a0b123a6b695b339010bf14a99515912 diff --git a/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.md b/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.md index dcfdfa13e6..629e214052 100644 --- a/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.md +++ b/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.md @@ -2,6 +2,8 @@ Status: rejected — Workflow progress is an intentional observation surface; make it useful through a consumer instead of deleting it. +English | [中文](2026-07-12-collapse-workflow-to-foreground-core.zh.md) + ## Problem The workflow capability executes foreground JavaScript that composes subagents, but it also carries an unconsumed progress-observation system. No production listener subscribes to any of the six `workflow/*` events; listeners exist only in workflow tests. Nevertheless the seam defines run/phase/agent outcome payloads, the worker sends phase/log/agent lifecycle protocol messages, the host forwards them through a `liveAgents` pairing ledger, and the engine maintains run ids solely to correlate those notifications. diff --git a/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.zh.md b/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.zh.md new file mode 100644 index 0000000000..3ae5e026a0 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 将工作流收缩至已使用的前台核心 + +Status: rejected — 工作流进度是有意设计的观测接口面;应通过消费方使其发挥作用,而非删除它。 + +[English](2026-07-12-collapse-workflow-to-foreground-core.md) | 中文 + +## 问题 + +工作流能力执行前台 JavaScript 来编排 subagent,但它同时携带了一套无人消费的进度观测系统。没有任何生产环境的监听器订阅六个 `workflow/*` 事件中的任何一个;监听器仅存在于工作流测试中。尽管如此,seam 定义了 run/phase/agent(智能体) outcome 载荷,worker 发送 phase/log/agent 生命周期协议消息,host 通过一个 `liveAgents` 配对账本转发它们,引擎维护 run id 仅仅是为了关联这些通知。 + +这套进度词汇不仅仅是未被使用;它在不经重新设计的情况下也无法服务于其唯一已命名的未来消费方。`WorkflowRunInfo` 包含 `{id, meta}` 但没有父 agent、会话或工具调用标识,而面向模型的工具也从不暴露 run id。一个全局 ACP(Agent Client Protocol)监听器无法将事件路由到正确的客户端会话。`meta.phases` 从未被查询,`phase(title)` 不对其做校验,phase 的 `detail`/`model` 和 agent 的 `label`/`phase` 仅供事件消费,`whenToUse` 被校验和复制但从未被渲染或用于选择。`phase()` 和 `log()` 仍然跨越 worker 边界,尽管没有接收方。 + +live handle 在观测者消失后仍重复事件时代的数据。`WorkflowRun.id` 没有非事件消费方,而工具读取 `run.meta.name` 只是为了渲染一个它已经以 `args.meta.name` 形式持有的值;两者都不属于执行/取消 handle。 + +取消机制也为一个同步启动提供了两条公开通道。`WorkflowStartRequest.signal` 被传递给 worker host,而唯一的生产调用方另外将同一个 signal 桥接到 `WorkflowRun.cancel()`。因为 `start()` 在控制权让出之前就返回了 run,不存在需要请求时取消的就绪窗口;重复的 signal 增加了 host 的 listener/disarm 状态却没有封堵任何竞态。 + +`WorkflowError.fatal` 是同一种推测性分支的微缩版:所有生产环境的构造都是 fatal 的,`fatal: false` 仅存在于测试中,组合子已经通过 `instanceof` 区分工作流失败。 + +## 提案 + +保留已使用的核心:`agent(prompt, { schema, model })`、`parallel`、`pipeline`、`args`、并发/agent 上限、取消、有界 dispose(资源释放)、结构化结果、worker 隔离与前台工具收集。移除所有 `workflow/*` 事件及其仅供事件使用的 info/outcome 类型;移除 `phase()`、`log()`、agent 的 `label`/`phase`、phase 声明、`whenToUse` 及其 worker 消息/host 观测者;将工作流元数据收缩为工具实际使用的 name;移除仅供事件使用的 run id/meta 快照与合成的 agent-end 账本。将 `WorkflowRun` 收缩为 `result`、`cancel()` 和 `dispose()`;工具渲染请求方持有的 name。移除 `WorkflowStartRequest.signal` 及 worker host 的 input-signal listener/disarm 状态,保留调用方从其 abort signal 到 `run.cancel()` 的桥接。将 `WorkflowError` 变为单一的 fatal 错误类,不再有布尔模式或 `isFatalWorkflowError()` 辅助函数。 + +修订已实施的动态工作流 Agent Note(agent 决策记录),并更新 seam/工具/worker README、工具 schema、生成的 catalog 与包(package)依赖图、worker type-equiv 记录、单元测试以及工作流快照/header fixture(测试前置数据)。如果进度 UI 工作被立项,应从一份命名了父 agent/会话/工具调用的关联契约出发,而非原样复活这套协议。 + +## 曾考虑的替代方案 + +**为未来 UI 保留预建的观测词汇。** 当前形态类似 Claude Code 的动态工作流元数据,host 有意地将每个转发的 agent start 与 worker 的 end 或一个合成的终止 end 配对。移除它意味着放弃形态兼容性,使进度 UI 成为一项全新的设计任务;但现有载荷仍缺少可路由的归属信息,因此仅靠平衡的生命周期也无法在不重新设计的情况下让已命名的 ACP 消费方可行。 + +## 验收标准 + +- 工作流公开 seam 仅包含有生产消费方的执行、取消、结果与 dispose 契约。 +- 不再保留任何工作流事件、phase/log 协议消息、run-id 生成器、仅供进度使用的元数据、host 配对账本或 fatal 模式分支。 +- run handle 不再有 id/meta 回显,取消在同步 `start()` 返回后只有一条持有者拥有的通道。 +- parallel/pipeline 行为、上限、取消后的完全停稳、worker 隔离、结构化输出与面向模型的工作流场景保持测试覆盖。 +- 类型检查、覆盖率、快照、doc-sync(文档同步门禁)、module-graph 校验、构建与 hygiene 全部通过。 + +## 风险 + +这是对工作流 DSL、事件分类体系、handle 与 start request 的编译可见收缩。现有提供描述性元数据的工作流调用,以及使用 `phase`、`log` 或 label 的脚本,都必须相应精简;程序化调用方需自行将 abort source 桥接到返回的 handle;未来的观测者必须添加一个关联性更好的 seam。使工作流有用的执行语义不变。 diff --git a/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.i18n.yaml b/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.i18n.yaml new file mode 100644 index 0000000000..3b97a7fb1e --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +2026-07-12-prune-unused-skill-registry-surface.md: 5a13effa04a6cd9954741a0a33ebc6fc3512fab8 +2026-07-12-prune-unused-skill-registry-surface.zh.md: 46d49a02c294c492abdd6e7e611a5c92eb317c12 diff --git a/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.md b/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.md index e96215a651..5a13effa04 100644 --- a/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.md +++ b/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.md @@ -2,6 +2,8 @@ Status: rejected — Direct runtime skill registration is an intentional extension path for third-party plugins. +English | [中文](2026-07-12-prune-unused-skill-registry-surface.zh.md) + ## Problem The skill service's embedded-runtime subsystem has zero production caller of `ctx.skills.register()`. It adds a reserved `runtime` provider name, a runtime map/rank/source, duplicate policy, a second revision in cache keys, normalization, disposers, and tests alongside the provider seam every shipped skill already uses. `SkillSummary.whenToUse` and candidate/definition `path` are parsed and copied but never read by a production consumer: the model catalog renders name/description, resource loading uses `resourceBase`, and providers own their locator. The deliberately open `metadata` extension point stays. diff --git a/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.zh.md b/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.zh.md new file mode 100644 index 0000000000..46d49a02c2 --- /dev/null +++ b/.agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 裁剪 skill(技能)注册表中未使用的接口 + +Status: rejected — 直接在运行时注册 skill 是为第三方插件保留的有意扩展路径。 + +[English](2026-07-12-prune-unused-skill-registry-surface.md) | 中文 + +## 问题 + +skill 服务的嵌入式运行时子系统中,`ctx.skills.register()` 没有任何生产调用方。它引入了一个保留的 `runtime` 提供方名称、一套运行时 map/rank/source、重复策略、缓存键中的第二个 revision、规范化逻辑、dispose(资源释放)器以及相应测试——而所有已交付的 skill 都只使用提供方 seam。`SkillSummary.whenToUse` 和 candidate/definition 的 `path` 被解析和复制,但没有任何生产消费方读取它们:模型目录只渲染 name/description,资源加载使用 `resourceBase`,提供方自行管理其定位器。有意开放的 `metadata` 扩展点保留不动。 + +## 提案 + +移除 `SkillService.register()`、`SkillRegistration`、运行时伪提供方及保留名称规则、运行时 revision/缓存分支,以及仅用于运行时的 source/rank 规范化逻辑。需要嵌入式 skill 的测试改为注册一个小型真实提供方。保留 `providerRevision` 作为进行中的发现 epoch,但已完成的目录缓存仅以 cwd 为键:每次提供方变更同步清除缓存,await 之后的 revision 比较已能阻止插入陈旧结果。从 skill 契约和本地提供方副本中移除 `whenToUse`、`SkillCandidate.path` 与 `SkillDefinition.path`,同时保留提供方的 locator/root 路径;保留 `metadata`、`disableModelInvocation`、`source`、`provider`、`locator` 和 `resourceBase`,因为它们要么是有意开放的扩展词汇,要么是生产消费的字段。 + +同步修订 skill 系统 Agent Note(agent 决策记录)、README、JSDoc、目录文件与测试。agent(智能体)作用域的系统提示词段、工具提供方和变量明确不在本提案范围内:[agent 作用域贡献者契约](../../implemented/architecture/2026-07-08-agent-scope-contexts.md)有意允许在 `setup(agentCtx)` 期间通过 agent 拥有的上下文注册这三者,因此仓库内没有固定的作用域注册并不能证明它们未被使用。 + +## 曾考虑的替代方案 + +**保留面向嵌入方的运行时 skill 注册。** 这是已实现的 skill Agent Note 中有意提供的同步直接定义便利接口。一个小型提供方包装层可以在 effect 拥有的生命周期下暴露相同的嵌入数据,但它必须实现异步 `list()`/`get()`、携带提供方身份,并接受提供方的重复语义。本提案选择只保留一条统一的提供方路径,而非维护第二套排序、校验、缓存失效与查找路径。 + +## 验收标准 + +- skill 收集只有一条提供方驱动的路径,已完成缓存仅以 cwd 为键,revision epoch 仅用于进行中的失效检测;保留的 skill 字段要么有生产读取方,要么有记录在案的有意扩展契约。 +- agent 作用域的提示词段、变量、工具提供方、工具守卫,以及原生模式和 Code Mode 下的 structured-output 提交行为保持不变。 +- 类型检查、覆盖率、快照、doc-sync(文档同步门禁)、module-graph 校验、构建与 hygiene 全部通过。 + +## 风险 + +这是对预发布 skill 注册表的编译可见收缩。外部编程式 `list()`/`get()` 消费方将失去 `whenToUse` 路由提示和 candidate/definition 的 `path`;已交付的模型目录从未渲染它们,资源解析保留了显式的 `resourceBase` 加上提供方自有的不透明 locator,但这些字段并非观测等价。skill 本地 frontmatter 解析必须继续保留并校验所支持的 metadata schema,外部提供方仍可提供嵌入式、文件系统、远程或其他 skill 来源。 diff --git a/.agents/skills/dsh-find-simplifications/SKILL.md b/.agents/skills/dsh-find-simplifications/SKILL.md index 2e1ccdc3c8..43e2218085 100644 --- a/.agents/skills/dsh-find-simplifications/SKILL.md +++ b/.agents/skills/dsh-find-simplifications/SKILL.md @@ -34,7 +34,7 @@ Thin candidates are usually not enough for an Agent Note: deleting one typo, run Use parallel subagents when the user asks for breadth or many candidates. Give each agent a domain and require evidence, not guesses. Useful domains: - Agent loop and session log: turn/step boundaries, steering, abort/cancel, durable events, replay, load/resume. -- ACP and UI surfaces: `session/*` methods, terminal `_meta`, transcript rendering, single vs multi-session state. +- ACP automation and human UI surfaces: prompt settlement and teardown on the protocol side; transcript rendering and interaction state on the UI side. - LLM/tools/system prompt: stream/generate surfaces, assemblers, registries, tool schema defaults, presentation hooks. - Bash and tool execution: foreground/background split, task ownership, output spill files, executor methods. - Packages/examples/scripts/tests: package boundaries, static inventories, redundant snapshot expected outputs, support packages. diff --git a/AGENTS.md b/AGENTS.md index 8007f32b90..64259784fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,7 +30,8 @@ packages/ @deepseek-ai/dsh-<pkg> workspaces at packages/<group>/<pkg>/ cordis/ self-referential toolset: the agent inspects/mounts plugins in its own runtime hooks/ Claude Code / Codex hook bridges + shared wire-protocol library session-persistence/ persistence seam + JSONL/SQLite backends - ui/ ACP/TUI/JSON-RPC bridges; boot, approval, interaction plugins + acp/ automation-only Agent Client Protocol server + ui/ TUI/JSON-RPC bridges; boot, approval, interaction plugins examples/ demo bundles (agent-spine + TUI/CLI/ACP/JSON-RPC bins) leaves load support/ dev/test infrastructure packages util/ zero-dependency utilities @@ -64,7 +65,7 @@ pnpm run website:build # VitePress build (doubles as the site's dead-link check pnpm run demo:headless "task" # one-shot agent (needs DEEPSEEK_API_KEY) pnpm run demo:tui # full-screen TUI coding agent (needs DEEPSEEK_API_KEY) pnpm run demo:cordis # self-referential demo: the agent modifies its own runtime (needs key) -pnpm run demo:acp # ACP server agent (needs DEEPSEEK_API_KEY) +pnpm run demo:acp # ACP automation server (needs DEEPSEEK_API_KEY) ``` ### Host sandbox failures @@ -107,7 +108,7 @@ Real-API tests and demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, - **Tests describe behavior, not correctness.** Change obsolete behavior with its tests; explain why in the PR. - **Every non-trivial change MUST include at least one Agent Note in the same PR.** Update the owning note or add one, validate its premises against code, and exempt only mechanical/local edits ([scope](.agents/notes/README.md#when-to-write-one)). - **Testing policy** — [docs/testing.md](docs/testing.md). Every non-trivial model- or product-user-visible behavior change adds or updates a keyless snapshot through a real runnable example in the same PR; package tests, e2e-only assertions, and mock-only fixtures do not substitute for the assembled application transcript. Fixtures must replay on macOS/Linux; fix fixtures, not normalizers. -- **A tool's ACP render intent is part of its design**, decided up front (`generic`/`terminal`/`diff`, `locations`); presentation methods are pure functions of `args` ([cookbook](docs/cookbook/adding-a-tool.md)). +- **A tool's UI render intent is part of its design**, decided up front (`generic`/`terminal`/`diff`, `locations`); presentation methods are pure functions of `args` ([cookbook](docs/cookbook/adding-a-tool.md)). - **Plan unit, e2e, and snapshot coverage** for new seams, lifecycle shapes, and transcript surfaces; missing snapshot-harness support is part of the implementation, not deferred follow-up. - **Keep PRs coherent and merge with merge commits.** Split an independently meaningful feature or design decision into a separate or stacked PR when combining it obscures ownership, intent, or verification. Never squash/rebase or rewrite pushed branches; put a review fix on its introducing PR, then merge down the stack ([guide](docs/cookbook/responding-to-pr-review-on-a-stack.md)). - TODO markers: `FIXME`/`TODO`/`XXX` by urgency ([semantics](docs/development.md)). diff --git a/apps/cli/README.md b/apps/cli/README.md index e6a33247ca..4172eca836 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -20,4 +20,4 @@ Symlink the source-running launcher onto your PATH; it resolves the checkout thr ln -sf "$(pwd)/bin/dsh" ~/.local/bin/dsh ``` -`pnpm run demo:tui` runs the same entry from the repo root. The built form (`lib/bin.js`, via `pnpm run build`) boots the same config under plain Node. +`pnpm run dsh` runs the same entry from the repo root and forwards arguments directly, for example `pnpm run dsh -p "task"`. The built form (`lib/bin.js`, via `pnpm run build`) boots the same config under plain Node. diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml new file mode 100644 index 0000000000..a85f2eaf2c --- /dev/null +++ b/apps/cli/cordis.yml @@ -0,0 +1,224 @@ +# dsh web — the full web-shape composition: host runtime (layer 1), the +# transport/service layer (layer 2), and the browser plugin roster (dshClient +# rows the modules node half scans into window.__DSH_BOOT__). Row order +# carries no load semantics (activation is service-availability driven); the +# grouping below is for readers. `--dev` appends the dsh-client-hmr row in +# code (AppCLIEntry) — prod and dev differ by exactly that one row. +# AppCLIEntry patches this tree before boot: profile json + CLI flags + +# distIndex land as config patches over the rows below (yaml = engineering +# defaults, json = user config, user wins per field). + +# ── layer 1: runtime ──────────────────────────────────────────────────────── + +- id: timer + name: '@cordisjs/plugin-timer' + +- id: llm + name: '@deepseek-ai/dsh-llm' + +- id: session + name: '@deepseek-ai/dsh-session' + +- id: session-title + name: '@deepseek-ai/dsh-session-title' + config: + fallbackMaxWords: 5 + fallbackMaxBytes: 40 + maxTitleBytes: 80 + +# Model-made titles on the first-message cadence (the web sidebar renders +# session/title). Same values as the TUI composition. +- id: session-title-llm + name: '@deepseek-ai/dsh-session-title-first-message-llm' + config: + targetWords: 5 + targetCjkCharacters: 10 + maxInputBytes: 4096 + maxOutputTokens: 64 + timeoutMs: 60000 + +- id: system-prompt + name: '@deepseek-ai/dsh-system-prompt' + config: + persona: '' + +- id: tools + name: '@deepseek-ai/dsh-tools' + +- id: user-interaction + name: '@deepseek-ai/dsh-user-interaction' + +- id: agent + name: '@deepseek-ai/dsh-agent' + +- id: tasks + name: '@deepseek-ai/dsh-tasks' + +- id: agent-loop + name: '@deepseek-ai/dsh-agent-loop' + config: + agents: [] + +# The native DeepSeek adapter; reads the key/base-url the boot's layered +# .env loading (cwd then $DSH_HOME) left in the environment. +- id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek' + config: + apiKey: !!js process.env.DEEPSEEK_API_KEY + baseURL: !!js process.env.DEEPSEEK_BASE_URL + +- id: session-persistence-jsonl + name: '@deepseek-ai/dsh-session-persistence-jsonl' + config: + root: './.sessions' + +- id: bash-local + name: '@deepseek-ai/dsh-bash-local' + +- id: tool-bash + name: '@deepseek-ai/dsh-tool-bash' + +- id: tool-todo + name: '@deepseek-ai/dsh-tool-todo' + +- id: tool-tasks + name: '@deepseek-ai/dsh-tool-tasks' + +# fs cwd stays the package default (process.cwd()) — the same value the +# gateway injects into session.cwd, so paths and sessions agree. +- id: fs-local + name: '@deepseek-ai/dsh-fs-local' + +- id: fs-policy + name: '@deepseek-ai/dsh-fs-policy' + +- id: tool-fs + name: '@deepseek-ai/dsh-tool-fs' + +- id: tool-fs-search + name: '@deepseek-ai/dsh-tool-fs-search' + +- id: workspace-context + name: '@deepseek-ai/dsh-workspace-context' + config: + maxBytes: 65536 + +- id: skill + name: '@deepseek-ai/dsh-skill' + +- id: skill-local + name: '@deepseek-ai/dsh-skill-local' + +- id: tool-skill + name: '@deepseek-ai/dsh-tool-skill' + +# token-meter rejects unknown config keys — keep this row bare. +- id: token-meter + name: '@deepseek-ai/dsh-token-meter' + +- id: compact-basic + name: '@deepseek-ai/dsh-compact-basic' + +- id: subagent + name: '@deepseek-ai/dsh-subagent' + +- id: subagent-spawn + name: '@deepseek-ai/dsh-subagent-spawn' + config: + providerName: spawn + +- id: subagent-fork + name: '@deepseek-ai/dsh-subagent-fork' + config: + providerName: fork + +- id: tool-subagent + name: '@deepseek-ai/dsh-tool-subagent' + config: + provider: spawn + toolName: subagent + +- id: tool-subagent-fork + name: '@deepseek-ai/dsh-tool-subagent' + config: + provider: fork + toolName: subagent_fork + +- id: workflow-workerthread + name: '@deepseek-ai/dsh-workflow-workerthread' + config: + provider: spawn + +- id: tool-workflow + name: '@deepseek-ai/dsh-tool-workflow' + +- id: timeout-policy + name: '@deepseek-ai/dsh-timeout-policy' + +- id: spill-local + name: '@deepseek-ai/dsh-spill-local' + +# Omitting maxInlineBytes makes the whole policy a silent no-op — always +# state it explicitly. +- id: spill-policy + name: '@deepseek-ai/dsh-spill-policy' + config: + maxInlineBytes: 50000 + +# The API gateway: the transport-agnostic dispatch face every client shape +# shares. provider/model are the host default routing — the profile json's +# mapping target (user config overrides these engineering defaults). +- id: api-gateway + name: '@deepseek-ai/dsh-host-apiproxy' + config: + provider: deepseek + model: deepseek-v4-flash + +# ── layer 2: transport/service ────────────────────────────────────────────── + +# Plain route-registration carrier. distIndex is an assembly fact, not user +# config — AppCLIEntry resolves the frontend dist and patches it in; host and +# port arrive as CLI-flag patches over these defaults. +- id: webserver + name: '@deepseek-ai/dsh-host-webserver' + config: + host: 127.0.0.1 + port: 3080 + +# ── browser plugin roster (dshClient rows; node halves are layer-2 hosts) ── + +# Dual-face: node half scans this very tree for dshClient rows, composes +# window.__DSH_BOOT__, serves /plugins/<id>/client.js; browser half is the +# module table the shell kernel constructs before cordis exists (§4.7 — +# adopted as a plugin entry by the kernel, never fetched). +- id: modules + name: '@deepseek-ai/dsh-client-modules' + +# Owns both ends of the web transport: node half binds the gateway to the +# webserver under /api; browser half is the fetch/SSE client. +- id: connection + name: '@deepseek-ai/dsh-client-connection' + +- id: client-runtime + name: '@deepseek-ai/dsh-client-runtime' + +- id: ui-theme + name: '@deepseek-ai/dsh-client-ui-theme' + +- id: i18n + name: '@deepseek-ai/dsh-client-i18n' + +- id: ui-layout + name: '@deepseek-ai/dsh-client-ui-layout' + +- id: ui-sidebar + name: '@deepseek-ai/dsh-client-ui-sidebar' + +- id: ui-conversation + name: '@deepseek-ai/dsh-client-ui-conversation' + +- id: ui-question + name: '@deepseek-ai/dsh-client-ui-question' + +- id: ui-trajectory + name: '@deepseek-ai/dsh-client-ui-trajectory' diff --git a/apps/cli/package.json b/apps/cli/package.json index 8557965d34..a39ce726bb 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -9,14 +9,22 @@ }, "files": [ "lib/bin.js", + "cordis.yml", "src" ], "license": "BSD-3-Clause", "dependencies": { + "@cordisjs/plugin-include": "workspace:*", + "@cordisjs/plugin-loader": "workspace:*", + "@cordisjs/plugin-timer": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-app-boot": "workspace:^", + "@deepseek-ai/dsh-bash-local": "workspace:^", "@deepseek-ai/dsh-client-connection": "workspace:^", "@deepseek-ai/dsh-client-hmr": "workspace:^", "@deepseek-ai/dsh-client-i18n": "workspace:^", + "@deepseek-ai/dsh-client-modules": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-conversation": "workspace:^", "@deepseek-ai/dsh-client-ui-layout": "workspace:^", @@ -24,13 +32,48 @@ "@deepseek-ai/dsh-client-ui-sidebar": "workspace:^", "@deepseek-ai/dsh-client-ui-theme": "workspace:^", "@deepseek-ai/dsh-client-ui-trajectory": "workspace:^", + "@deepseek-ai/dsh-compact-basic": "workspace:^", "@deepseek-ai/dsh-frontend": "workspace:^", + "@deepseek-ai/dsh-fs-local": "workspace:^", + "@deepseek-ai/dsh-fs-policy": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-host-runtime": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-llm-deepseek": "workspace:^", "@deepseek-ai/dsh-paths": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", + "@deepseek-ai/dsh-session-title-first-message-llm": "workspace:^", + "@deepseek-ai/dsh-skill": "workspace:^", + "@deepseek-ai/dsh-skill-local": "workspace:^", + "@deepseek-ai/dsh-spill-local": "workspace:^", + "@deepseek-ai/dsh-spill-policy": "workspace:^", + "@deepseek-ai/dsh-subagent": "workspace:^", + "@deepseek-ai/dsh-subagent-fork": "workspace:^", + "@deepseek-ai/dsh-subagent-spawn": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-tasks": "workspace:^", + "@deepseek-ai/dsh-timeout-policy": "workspace:^", + "@deepseek-ai/dsh-token-meter": "workspace:^", + "@deepseek-ai/dsh-tool-bash": "workspace:^", + "@deepseek-ai/dsh-tool-fs": "workspace:^", + "@deepseek-ai/dsh-tool-fs-search": "workspace:^", + "@deepseek-ai/dsh-tool-skill": "workspace:^", + "@deepseek-ai/dsh-tool-subagent": "workspace:^", + "@deepseek-ai/dsh-tool-tasks": "workspace:^", + "@deepseek-ai/dsh-tool-todo": "workspace:^", + "@deepseek-ai/dsh-tool-workflow": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/dsh-tui": "workspace:^", - "cordis": "^4.0.0-rc.7" + "@deepseek-ai/dsh-user-interaction": "workspace:^", + "@deepseek-ai/dsh-workflow-workerthread": "workspace:^", + "@deepseek-ai/dsh-workspace-context": "workspace:^", + "cordis": "^4.0.0-rc.7", + "js-yaml": "^4.2.0" + }, + "devDependencies": { + "@types/js-yaml": "^4.0.9" } } diff --git a/apps/cli/src/app-cli-entry.ts b/apps/cli/src/app-cli-entry.ts new file mode 100644 index 0000000000..52df4203b1 --- /dev/null +++ b/apps/cli/src/app-cli-entry.ts @@ -0,0 +1,231 @@ +/** + * AppCLIEntry — the pre-cordis boot glue every dsh surface shape shares + * (config-tree boot wired for `dsh web` this round; TUI/headless migrate + * later). Everything here is what must exist before the Loader runs: layered + * env, the patch composition over the shipped cordis.yml (profile json + CLI + * flags + the resolved frontend dist), and the fail-loud triple after the + * tree settles. + */ + +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { Context } from 'cordis' +import type { FiberState } from 'cordis' +import Loader from '@cordisjs/plugin-loader' +import Include, { type PatchOptions } from '@cordisjs/plugin-include' +import yaml from 'js-yaml' +import { assertEntriesLoaded, installFailLoud, loadEnv } from '@deepseek-ai/dsh-app-boot' +import { resolveDshHome } from '@deepseek-ai/dsh-paths' +// Empty type import carries the httpServer Context merge for the port read below. +import type {} from '@deepseek-ai/dsh-host-webserver' + +/** Profile file under the invoking directory (read-only this round; never created — see the design's profile ruling). */ +const PROFILE_DIR = '.dsh-tmp-profile' +const PROFILE_FILE = 'config.json' + +/** One profile-json key mapped onto a yml row's config field. */ +interface ProfileMapping { + jsonPath: string + entryId: string + configKey: string +} + +/** + * The static profile→row mapping table. json is user config and wins over the + * yml engineering default per field; a json key absent from this table fails + * loud (a typo silently ignored would read as "setting has no effect"). + * Developers extend deployments by adding rows here. + */ +const PROFILE_MAPPINGS: ProfileMapping[] = [ + { jsonPath: 'provider', entryId: 'api-gateway', configKey: 'provider' }, + { jsonPath: 'model', entryId: 'api-gateway', configKey: 'model' }, + { jsonPath: 'persistenceRoot', entryId: 'session-persistence-jsonl', configKey: 'root' }, +] + +// The include's YAML dialect: `!!js` scalars become expression nodes the +// Loader evaluates at entry activation. The bypass parse below must accept +// them (and passing one through a patch unchanged is legal). +const jsExprType = new yaml.Type('tag:yaml.org,2002:js', { + kind: 'scalar', + resolve: data => typeof data === 'string', + construct: data => ({ __jsExpr: String(data) }), +}) +const includeYamlSchema = yaml.JSON_SCHEMA.extend(jsExprType) + +/** + * Value mirror of cordis's `FiberState` const enum members the sweep needs + * (a const enum has no runtime object to import; same rationale as the + * client-side mirror in dsh-client-web). + */ +const FIBER_ACTIVE = 2 as FiberState.ACTIVE +const FIBER_PENDING = 0 as FiberState.PENDING + +/** Constructor facts for one `dsh web` invocation (argv already parsed by web.ts). */ +export interface AppCLIEntryOptions { + /** Absolute path of the shipped cordis.yml. */ + configPath: string + /** Whether to append the HMR row (the whole prod/dev difference). */ + dev: boolean + /** --host when explicitly passed; undefined keeps the yml engineering default. */ + host?: string + /** --port when explicitly passed; undefined keeps the yml engineering default. */ + port?: number +} + +/** + * Boot driver for the config-tree `dsh web` shape: holds only what exists + * independently of (and prior to) cordis — argv facts, the composed patch + * set, and finally the root ctx. + */ +export class AppCLIEntry { + /** The root context, set by {@link run}. */ + ctx!: Context + + private patches: PatchOptions[] = [] + + constructor(private readonly options: AppCLIEntryOptions) {} + + /** + * Run the boot chain: layered env → patch composition → Loader include + * boot (dev row before await) → fail-loud triple. + * @returns the settled root context and the listening port. + */ + async run(): Promise<{ ctx: Context; port: number }> { + this.loadEnvLayers() + this.composePatches() + await this.bootTree() + this.assertBoot() + const port = this.ctx.get('httpServer')?.port + /* v8 ignore next -- the sweep above guarantees an ACTIVE webserver row */ + if (port === undefined) throw new Error('dsh web: httpServer service missing after settled boot') + return { ctx: this.ctx, port } + } + + /** Layered .env: ambient > cwd (bin already loaded) > $DSH_HOME (loadEnvFile never overrides). */ + private loadEnvLayers(): void { + loadEnv('dsh web', resolveDshHome()) + } + + /** + * Compose the patch set from the three non-yml config sources: profile + * json (user config), CLI flags, and the resolved frontend dist. Patches + * replace a row's config wholesale, so each patched row's yml static + * values are re-read here (bypass parse) and merged under the overrides. + */ + private composePatches(): void { + const rows = this.parseYmlRows() + const overrides = new Map<string, Record<string, unknown>>() + const put = (entryId: string, key: string, value: unknown): void => { + const bag = overrides.get(entryId) ?? {} + bag[key] = value + overrides.set(entryId, bag) + } + + // Source 1: profile json (missing file = empty; unmapped key = loud). + for (const [key, value] of Object.entries(this.readProfile())) { + const mapping = PROFILE_MAPPINGS.find(m => m.jsonPath === key) + if (mapping === undefined) { + throw new Error(`dsh web: profile key "${key}" has no mapping (known: ${PROFILE_MAPPINGS.map(m => m.jsonPath).join(', ')})`) + } + put(mapping.entryId, mapping.configKey, value) + } + + // Source 2: CLI flags (field set disjoint from the json mappings). + if (this.options.host !== undefined) put('webserver', 'host', this.options.host) + if (this.options.port !== undefined) put('webserver', 'port', this.options.port) + + // Source 3: the frontend dist — an assembly fact of this app, never yml + // user config. Workspace knowledge stays here. + put('webserver', 'distIndex', this.resolveDistIndex()) + + this.patches = [...overrides.entries()].map(([id, bag]) => { + const yml = rows.get(id) + if (yml === undefined) throw new Error(`dsh web: patch target row "${id}" not found in ${this.options.configPath}`) + return { id, config: { ...(yml.config ?? {}) as Record<string, unknown>, ...bag } } + }) + } + + /** Loader include boot; the dev HMR row mounts before await so the fail-loud triple covers it. */ + private async bootTree(): Promise<void> { + const ctx = new Context() + ctx.baseUrl = pathToFileURL(join(resolve(this.options.configPath), '..')).href + '/' + await ctx.plugin(Loader) + ctx.loader.builtins.include = Include + await ctx.loader.create({ + name: 'cordis:include', + config: { + path: pathToFileURL(resolve(this.options.configPath)).href, + ...this.patches.length > 0 ? { patches: this.patches } : {}, + }, + }) + if (this.options.dev) { + await ctx.loader.create({ name: '@deepseek-ai/dsh-client-hmr' }) + } + this.ctx = ctx + await ctx.loader.await() + } + + /** + * Fail-loud triple: assertEntriesLoaded catches import failures, + * installFailLoud catches late apply rejections, and the all-ACTIVE sweep + * below catches PENDING fibers (cordis inject waiting has no timeout). + */ + private assertBoot(): void { + installFailLoud('dsh web') + assertEntriesLoaded(this.ctx, 'dsh web') + const failures: string[] = [] + for (const entry of this.ctx.loader.entries()) { + if (entry.fiber === undefined || entry.disabled) continue + const state = entry.fiber.state + if (state === FIBER_ACTIVE) continue + if (state === FIBER_PENDING) { + const missing = Object.keys(entry.fiber.inject).filter(service => this.ctx.get(service) === undefined) + failures.push(`${entry.options.name}: pending (waiting for service${missing.length === 1 ? '' : 's'}: ${missing.join(', ') || 'unknown'})`) + } else { + failures.push(`${entry.options.name}: fiber state ${String(state)}`) + } + } + if (failures.length > 0) { + throw new Error(`dsh web: ${String(failures.length)} entr${failures.length === 1 ? 'y' : 'ies'} did not activate\n${failures.join('\n')}`) + } + } + + /** Bypass parse of the shipped yml (id → row) for patch-merge inputs; Loader still reads the file itself. */ + private parseYmlRows(): Map<string, { config?: unknown }> { + const doc = yaml.load(readFileSync(this.options.configPath, 'utf8'), { schema: includeYamlSchema }) + if (!Array.isArray(doc)) throw new Error(`dsh web: ${this.options.configPath} is not a top-level entry list`) + const rows = new Map<string, { config?: unknown }>() + for (const row of doc as { id?: string; config?: unknown }[]) { + if (typeof row.id === 'string') rows.set(row.id, row) + } + return rows + } + + /** Profile json under cwd; read-only — never created here, absent = no user config. */ + private readProfile(): Record<string, unknown> { + let raw: string + try { + raw = readFileSync(join(process.cwd(), PROFILE_DIR, PROFILE_FILE), 'utf8') + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {} + throw error + } + const parsed: unknown = JSON.parse(raw) + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`dsh web: ${PROFILE_DIR}/${PROFILE_FILE} must hold a JSON object`) + } + return parsed as Record<string, unknown> + } + + /** Dist location is workspace knowledge of this app: resolved through the frontend package exports, not configured. */ + private resolveDistIndex(): string { + const require = createRequire(import.meta.url) + try { + return require.resolve('@deepseek-ai/dsh-frontend/dist/index.html') + } catch { + throw new Error('dsh web: frontend dist not built; run pnpm --filter @deepseek-ai/dsh-frontend build first') + } + } +} diff --git a/apps/cli/src/web.ts b/apps/cli/src/web.ts index 7518804ebb..bcd1482df3 100644 --- a/apps/cli/src/web.ts +++ b/apps/cli/src/web.ts @@ -1,160 +1,66 @@ /** - * `dsh web` — the web-shape assembly: startHost + dist resolution + - * startWebServer + the URL line + signal wiring. Mixing host and carrier - * concerns is this app module's job (packages stay single-sided). + * `dsh web` — thin bin over the config-tree boot: parse argv, run + * AppCLIEntry, print the URL line, wire signals. All composition lives in + * cordis.yml; all boot glue lives in AppCLIEntry. */ import { parseArgs } from 'node:util' import { networkInterfaces } from 'node:os' -import { createRequire } from 'node:module' -import { mountWebPlugins, startHost } from '@deepseek-ai/dsh-host-runtime' -import { createHostWebPluginRegistry, startWebServer } from '@deepseek-ai/dsh-host-webserver' +import { fileURLToPath } from 'node:url' +import { AppCLIEntry } from './app-cli-entry.ts' const LOOPBACK_HOST = '127.0.0.1' const ALL_INTERFACES_HOST = '0.0.0.0' -// --- Client composition (composition decisions live in the composing app) --- -// The composition layer owns one decision: which plugin packages mount (the -// roster). Dependency edges and the boot prefetch tier live in each package's -// dshClient declaration. - -/** - * Dev-only plugin: the client HMR driver. Whether it composes in is a - * deployment decision — the dev graph includes its row, the prod graph does - * not mount it at all. - */ -const CLIENT_HMR_ID = '@deepseek-ai/dsh-client-hmr' - -/** Bundle stat-poll interval for --dev (held here so the startup log states the real value). */ -const CLIENT_BUNDLE_POLL_MS = 500 - -/** The client plugin roster (flat; per-row boot behavior comes from manifests). */ -const CLIENT_PACKAGES = [ - '@deepseek-ai/dsh-client-connection', - '@deepseek-ai/dsh-client-runtime', - '@deepseek-ai/dsh-client-ui-theme', - '@deepseek-ai/dsh-client-i18n', - '@deepseek-ai/dsh-client-ui-layout', - '@deepseek-ai/dsh-client-ui-sidebar', - '@deepseek-ai/dsh-client-ui-conversation', - '@deepseek-ai/dsh-client-ui-question', - '@deepseek-ai/dsh-client-ui-trajectory', -] as const +const CONFIG_PATH = fileURLToPath(new URL('../cordis.yml', import.meta.url)) export async function runWeb(argv: string[]): Promise<void> { const { values } = parseArgs({ args: argv, options: { - host: { type: 'string', default: LOOPBACK_HOST }, - port: { type: 'string', default: '3080' }, + host: { type: 'string' }, + port: { type: 'string' }, dev: { type: 'boolean', default: false }, }, allowPositionals: false, }) - if (values.host !== LOOPBACK_HOST && values.host !== ALL_INTERFACES_HOST) { + if (values.host !== undefined && values.host !== LOOPBACK_HOST && values.host !== ALL_INTERFACES_HOST) { process.stderr.write( `dsh web: invalid --host ${values.host}; expected ${LOOPBACK_HOST} or ${ALL_INTERFACES_HOST}\n`, ) process.exit(1) } - const hostAddress = values.host - const port = Number(values.port) - if (!Number.isInteger(port) || port < 0 || port > 65535) { - process.stderr.write(`dsh web: invalid --port ${values.port}\n`) - process.exit(1) - } - - // A missing DEEPSEEK_API_KEY throws here (plugin load is fail-loud, uncaught by design). - const host = await startHost({ - boot: { - persistenceRoot: './.sessions', - workspaceContext: { maxBytes: 65_536 }, - sessionTitleLlm: true, - }, - }) - - // Client plugin chain: in-memory Loader tree over the composed roster, then - // the registry that feeds the __DSH_BOOT__ entry graph and - // /plugins/<id>/client.js. All row content comes from dshClient discovery - // over the mounted roster (dev adds the HMR driver row and turns on the - // bundle watch that drives rebuilt frames). - const roster = [...CLIENT_PACKAGES, ...values.dev ? [CLIENT_HMR_ID] : []] - const mounted = await mountWebPlugins(host.ctx, roster, import.meta.url) - const webPlugins = createHostWebPluginRegistry({ - ctx: host.ctx, - loader: mounted.loader, - resolvePkgJson: mounted.resolvePkgJson, - onError: (err: Error) => { process.stderr.write(`dsh web: plugin rescan: ${String(err)}\n`) }, - ...values.dev ? { watch: { intervalMs: CLIENT_BUNDLE_POLL_MS } } : {}, - }) - if (values.dev) { - // Dev visibility (the registry is a library and never prints): list what - // the bundle watch covers, then log every observed rebuild. This is a - // second onRebuilt subscription — the SSE relay inside the webserver is - // unaffected (multicast). - const revs = new Map(webPlugins.graph().entries.map(row => [row.id, row.rev])) - const bundlePaths = [...revs.keys()] - .map(id => webPlugins.clientPath(id)) - .filter((path): path is string => path !== undefined) - console.log( - `dsh web: watching ${String(bundlePaths.length)} plugin bundles (${String(CLIENT_BUNDLE_POLL_MS)}ms poll):\n ${bundlePaths.join('\n ')}`, - ) - webPlugins.onRebuilt((id, rev) => { - console.log(`dsh web: plugin rebuilt: ${id} rev ${revs.get(id) ?? '?'} -> ${rev}`) - revs.set(id, rev) - }) - } - // Published so the webserver invariant companion can audit manifest/bundle - // consistency; nothing else reads this key. - host.ctx.reflect.provide('webPlugins', webPlugins) - - // Dist location is workspace knowledge of this app: resolved through - // @deepseek-ai/dsh-frontend's package exports, not configured. - const require = createRequire(import.meta.url) - let distIndex: string - try { - distIndex = require.resolve('@deepseek-ai/dsh-frontend/dist/index.html') - } catch { - process.stderr.write('dsh web: frontend dist not built; run pnpm --filter @deepseek-ai/dsh-frontend build first\n') - await host.dispose() - process.exit(1) - } - - let exiting = false - async function shutdown(code: number): Promise<void> { - if (exiting) return - exiting = true - try { - await server.close() - await host.dispose() - } finally { - process.exit(code) + let port: number | undefined + if (values.port !== undefined) { + port = Number(values.port) + if (!Number.isInteger(port) || port < 0 || port > 65535) { + process.stderr.write(`dsh web: invalid --port ${values.port}\n`) + process.exit(1) } } - let server: Awaited<ReturnType<typeof startWebServer>> - try { - server = await startWebServer( - { host: hostAddress, port, distIndex, apiHandler: host.handler, webPlugins }, - (err: Error) => { - process.stderr.write(`dsh web: ${String(err)}\n`) - void shutdown(1) - }, - ) - } catch (error: unknown) { - // listen failed (EADDRINUSE…): no server to close, dispose the host directly. - process.stderr.write(`dsh web: ${String(error)}\n`) - await host.dispose() - process.exit(1) + const entry = new AppCLIEntry({ + configPath: CONFIG_PATH, + dev: values.dev, + ...values.host !== undefined ? { host: values.host } : {}, + ...port !== undefined ? { port } : {}, + }) + const { ctx, port: boundPort } = await entry.run() + + let exiting = false + const shutdown = (code: number): void => { + if (exiting) return + exiting = true + void Promise.resolve(ctx.fiber.dispose()).finally(() => { process.exit(code) }) } - const lan = hostAddress === ALL_INTERFACES_HOST + const lanCandidate = values.host === ALL_INTERFACES_HOST ? Object.values(networkInterfaces()).flat() .find(iface => iface !== undefined && iface.family === 'IPv4' && !iface.internal) : undefined - const localUrl = `http://${LOOPBACK_HOST}:${server.port}` - console.log(`dsh web: ${localUrl}${lan === undefined ? '' : ` (LAN: http://${lan.address}:${server.port})`}`) + const localUrl = `http://${LOOPBACK_HOST}:${boundPort}` + console.log(`dsh web: ${localUrl}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate.address}:${boundPort})`}`) - process.on('SIGTERM', () => { void shutdown(0) }) - process.on('SIGINT', () => { void shutdown(130) }) + process.on('SIGTERM', () => { shutdown(0) }) + process.on('SIGINT', () => { shutdown(130) }) } diff --git a/apps/web/package.json b/apps/web/package.json index a6b5a9b43f..3c8f90b6a0 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -24,7 +24,6 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-client-web-react": "workspace:^", - "@deepseek-ai/dsh-host-webserver": "workspace:^", "@types/node": "^22.0.0", "@types/react": "~18.3.1", "@types/react-dom": "~18.3.0", diff --git a/apps/web/src/main.ts b/apps/web/src/main.ts index 16ae6e9ed9..feb85db15a 100644 --- a/apps/web/src/main.ts +++ b/apps/web/src/main.ts @@ -3,8 +3,8 @@ * loader holding, module-table seeding, AppRoot gate, plugin assembly — lives * in @deepseek-ai/dsh-client-web; this file only finds the mount point. */ -import { bootWebShell } from '@deepseek-ai/dsh-client-web' +import { AppWebEntry } from '@deepseek-ai/dsh-client-web' const el = document.getElementById('root') if (el === null) throw new Error('web app: missing #root') -bootWebShell(el) +void new AppWebEntry(el).run() diff --git a/apps/web/tests/session-title.snapshot.ts b/apps/web/tests/session-title.snapshot.ts index 78023d5455..673e92f9ce 100644 --- a/apps/web/tests/session-title.snapshot.ts +++ b/apps/web/tests/session-title.snapshot.ts @@ -3,8 +3,8 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { act, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { WebBootEntry } from '@deepseek-ai/dsh-client-modules' -import { bootWebShell } from '@deepseek-ai/dsh-client-web' +import type { WebBootEntry } from '@deepseek-ai/dsh-client-modules/client' +import { AppWebEntry } from '@deepseek-ai/dsh-client-web' const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [ { id: '@deepseek-ai/dsh-client-connection', dir: 'connection', url: '/plugins/connection.js', rev: 'fx', inject: [], immediately: true }, @@ -81,13 +81,15 @@ it('projects initial and revised durable titles through the built eight-plugin f const root = document.querySelector<HTMLElement>('#root') if (root === null) throw new Error('snapshot root missing') act(() => { - unmount = bootWebShell(root, { + const entry = new AppWebEntry(root, { fetchBundle: (url) => { const code = bundles.get(url) return code === undefined ? Promise.reject(new Error(`missing built bundle ${url}`)) : Promise.resolve(code) }, executeBundle: (code) => { (0, eval)(code) }, }) + void entry.run() + unmount = () => { entry.dispose() } }) const projectLabel = await screen.findByText('fixture', {}, { timeout: 10_000 }) diff --git a/apps/web/tests/smoke-fixture.e2e.ts b/apps/web/tests/smoke-fixture.e2e.ts deleted file mode 100644 index 0726d14c8b..0000000000 --- a/apps/web/tests/smoke-fixture.e2e.ts +++ /dev/null @@ -1,291 +0,0 @@ -// Keyless boot-chain smoke over the REAL carrier: startWebServer + entry -// graph (__DSH_BOOT__ web2 shape) injection + built shell dist in a real -// chromium. First describe: graph injection + the fail-loud half. Second -// describe: the settled success pass — all nine REAL tsdown bundles load -// through the module system + vendored Loader chain in ?fixture mode (the -// infrastructure four ride the immediately prefetch tier, the UI rows fetch -// on demand), the three-column frame appears in one flip, and the resident -// question completes through the real UI stack. The full model round lands -// in smoke-real under the W5 real-host standard. -import { existsSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import type { Browser, Page } from 'playwright' -import { chromium } from 'playwright' -import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' -import { startWebServer } from '@deepseek-ai/dsh-host-webserver' -import type { WebBootEntry, WebBootGraph } from '@deepseek-ai/dsh-host-webserver' -import { DIST_INDEX, probeFreePort, requireDist, saveFailureShot } from './support.ts' - -const bundlePath = (dir: string): string => - fileURLToPath(new URL(`../../../packages/client/${dir}/lib/client.js`, import.meta.url)) - -const LAYOUT_ID = '@deepseek-ai/dsh-client-ui-layout' -const SIDEBAR_ID = '@deepseek-ai/dsh-client-ui-sidebar' - -/** id ↔ bundle table for the success pass (the complete Web UI assembly). */ -const REAL_PLUGINS: { id: string; dir: string; inject?: string[]; immediately?: boolean }[] = [ - { id: '@deepseek-ai/dsh-client-connection', dir: 'connection', immediately: true }, - { id: '@deepseek-ai/dsh-client-runtime', dir: 'runtime', inject: ['@deepseek-ai/dsh-client-connection'], immediately: true }, - { id: '@deepseek-ai/dsh-client-ui-theme', dir: 'ui-theme', immediately: true }, - { id: '@deepseek-ai/dsh-client-i18n', dir: 'i18n', immediately: true }, - { id: LAYOUT_ID, dir: 'ui-layout', inject: ['@deepseek-ai/dsh-client-runtime'] }, - { id: SIDEBAR_ID, dir: 'ui-sidebar', inject: [LAYOUT_ID] }, - { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', inject: [LAYOUT_ID] }, - { id: '@deepseek-ai/dsh-client-ui-question', dir: 'ui-question', inject: ['@deepseek-ai/dsh-client-ui-conversation'] }, - { id: '@deepseek-ai/dsh-client-ui-trajectory', dir: 'ui-trajectory', inject: ['@deepseek-ai/dsh-client-ui-conversation'] }, -] - -const BUNDLE_PATHS = new Map(REAL_PLUGINS.map(p => [p.id, bundlePath(p.dir)])) - -const row = (id: string, extra?: Partial<WebBootEntry>): WebBootEntry => - ({ id, url: `/plugins/${id}/client.js?rev=e2e`, rev: 'e2e', ...extra }) - -const graphRows: WebBootEntry[] = REAL_PLUGINS.map(p => row(p.id, { - ...(p.inject !== undefined ? { inject: p.inject } : {}), - ...(p.immediately === true ? { immediately: true } : {}), -})) - -/** Graph for the fail-loud half: the immediately tier, one live UI row, one missing row. */ -const FAIL_GRAPH: WebBootGraph = { - rev: 'e2e-fail', - entries: [...graphRows.filter(r => r.immediately === true), row(LAYOUT_ID), row('@probe/absent')], -} - -/** Graph for the success pass: the complete assembly. */ -const OK_GRAPH: WebBootGraph = { rev: 'e2e-ok', entries: graphRows } - -/** Registry stub over a fixed graph (the real HostWebPluginRegistry is webserver-side production code). */ -function fixedRegistry(graph: WebBootGraph, byId: ReadonlyMap<string, string>) { - return { - graph: () => graph, - clientPath: (id: string) => byId.get(id), - onRebuilt: () => () => undefined, - } -} - -describe('web boot chain (keyless, real carrier)', () => { - let server: Awaited<ReturnType<typeof startWebServer>> - let browser: Browser - let page: Page - const pageErrors: string[] = [] - - beforeAll(async () => { - requireDist() - const port = await probeFreePort() - const apiHandler = { fetch: () => Promise.resolve(new Response('boot smoke must not call /api', { status: 500 })) } - server = await startWebServer({ - host: '127.0.0.1', - port, - distIndex: DIST_INDEX, - apiHandler, - webPlugins: fixedRegistry(FAIL_GRAPH, BUNDLE_PATHS), - }, (err) => { pageErrors.push(`server: ${String(err)}`) }) - browser = await chromium.launch() - page = await browser.newPage() - page.on('pageerror', e => pageErrors.push(String(e))) - await page.goto(`http://127.0.0.1:${port}/`, { waitUntil: 'load' }) - }) - - afterAll(async () => { - await browser?.close() - await server?.close() - }) - - it('GET / injects the entry graph verbatim', async () => { - onTestFailed(() => saveFailureShot(page, 'smoke-boot-manifest')) - const boot = await page.evaluate(() => (window as { __DSH_BOOT__?: unknown }).__DSH_BOOT__) - expect(boot).toEqual(FAIL_GRAPH) - }) - - it('serves a real bundle through the plugins endpoint', async () => { - const res = await page.request.get(`${new URL(page.url()).origin}/plugins/${LAYOUT_ID}/client.js`) - expect(res.status()).toBe(200) - expect(await res.text()).toContain('window.__ModuleLoader__.load') - }) - - it('boots to the loading page and fail-louds the absent entry', async () => { - onTestFailed(() => saveFailureShot(page, 'smoke-boot-fail-loud')) - await page.waitForSelector('text=HARNESS', { timeout: 10_000 }) - await page.waitForSelector('text=Failed to load plugins', { timeout: 10_000 }) - await page.waitForSelector('text=@probe/absent', { timeout: 2000 }) - // The real UI must not have flipped in: the gate opens only on settled. - expect(await page.locator('[class*="frame"]').count()).toBe(0) - }) - - it('applies the token sheets before any plugin CSS', async () => { - const family = await page.evaluate(() => getComputedStyle(document.body).getPropertyValue('--dsw-font-family')) - expect(family.trim().length).toBeGreaterThan(0) - }) -}) - -describe('web boot chain success pass (keyless, nine real bundles, ?fixture)', () => { - let server: Awaited<ReturnType<typeof startWebServer>> - let browser: Browser - let page: Page - const pageErrors: string[] = [] - - beforeAll(async () => { - requireDist() - const missing = REAL_PLUGINS.filter(p => !existsSync(bundlePath(p.dir))) - if (missing.length > 0) throw new Error(`client bundles not built (pnpm --filter <pkg> bundle): ${missing.map(m => m.dir).join(', ')}`) - const port = await probeFreePort() - // ?fixture never opens HTTP streams; /api is a tripwire like the first describe. - const apiHandler = { fetch: () => Promise.resolve(new Response('fixture mode must not call /api', { status: 500 })) } - server = await startWebServer({ - host: '127.0.0.1', - port, - distIndex: DIST_INDEX, - apiHandler, - webPlugins: fixedRegistry(OK_GRAPH, BUNDLE_PATHS), - }, (err) => { pageErrors.push(`server: ${String(err)}`) }) - browser = await chromium.launch() - page = await browser.newPage() - page.on('pageerror', e => pageErrors.push(String(e))) - await page.goto(`http://127.0.0.1:${port}/?fixture`, { waitUntil: 'load' }) - }) - - afterAll(async () => { - await browser?.close() - await server?.close() - }) - - it('settles and flips to the three-column frame in one pass', async () => { - onTestFailed(() => saveFailureShot(page, 'smoke-boot-settled')) - await page.waitForSelector('[class*="frame"]', { timeout: 15_000 }) - // Loading page is gone; the grid carries the three tracks. - expect(await page.locator('text=Failed to load plugins').count()).toBe(0) - const template = await page.locator('[class*="frame"]').evaluate(el => getComputedStyle(el).gridTemplateColumns) - expect(template.split(' ').length).toBe(3) - }) - - it('every plugin CSS landed with its ownership tag', async () => { - const owners = await page.evaluate(() => - [...document.querySelectorAll('style[data-plugin]')].map(s => (s as HTMLElement).dataset['plugin'])) - expect(owners).toContain(LAYOUT_ID) - expect(owners).toContain(SIDEBAR_ID) - }) - - it('collapsed sidebar animates to a 56px rail with the four controls', async () => { - onTestFailed(() => saveFailureShot(page, 'smoke-boot-collapsed-rail')) - const frame = page.locator('[class*="frame"]') - const firstTrack = async (): Promise<string> => (await frame.evaluate( - el => getComputedStyle(el).gridTemplateColumns)).split(' ')[0]! - // The tracks transition on the deepsuite curve; assert the animated - // settle rather than an instant jump. - const settledTrack = async (px: string): Promise<void> => { - await expect.poll(firstTrack, { timeout: 2000 }).toBe(px) - } - // The brand wordmark is decorative svg (aria-hidden) — presence tracks the wide chrome. - const brand = () => page.locator('[class*="brand"]').count() - await page.getByRole('button', { name: 'Collapse sidebar' }).click() - // Mid-collapse the wide chrome is still mounted, fading — not swapped out. - expect(await brand()).toBe(1) - await settledTrack('56px') - await expect.poll(brand, { timeout: 2000 }).toBe(0) - for (const name of ['Open sidebar', 'New session', 'New workspace', 'Search sessions', 'Settings']) { - await expect(page.getByRole('button', { name }).isVisible(), name).resolves.toBe(true) - } - await page.getByRole('button', { name: 'Open sidebar' }).click() - await settledTrack('280px') - await expect(page.getByRole('button', { name: 'Collapse sidebar' }).isVisible()).resolves.toBe(true) - // Rail search: collapse again, the search control expands and lands in the box. - await page.getByRole('button', { name: 'Collapse sidebar' }).click() - await settledTrack('56px') - await page.getByRole('button', { name: 'Search sessions' }).click() - await settledTrack('280px') - // Focus is deferred past the slide (EXPAND_SLIDE_MS) — poll for it. - await expect.poll(() => page.evaluate(() => - (document.activeElement as HTMLInputElement | null)?.placeholder ?? ''), { timeout: 2000 }).toContain('Search') - }) - - it('renders file tool rows and expands fixture reasoning from either click target', async () => { - onTestFailed(() => saveFailureShot(page, 'smoke-think-disclosure')) - await page.locator('[role="treeitem"]').first().click() - await page.locator('[role="treeitem"][aria-selected]').first().click() - - const thinkRoot = page.locator('[data-variant="think"]').first() - const think = thinkRoot.getByRole('button') - await think.waitFor({ state: 'visible', timeout: 10_000 }) - expect(await think.getAttribute('aria-expanded')).toBe('false') - - await thinkRoot.getByText(/^思考过程 .*reasoning 内容。$/).click() - expect(await think.getAttribute('aria-expanded')).toBe('true') - expect(await thinkRoot.locator(':scope > div').count()).toBe(2) - - await think.getByText('Think', { exact: true }).click() - expect(await think.getAttribute('aria-expanded')).toBe('false') - - const editRoot = page.locator('[data-variant="edit"]').first() - await editRoot.waitFor({ state: 'visible', timeout: 10_000 }) - expect(await editRoot.getByText('Edit', { exact: true }).count()).toBe(1) - expect(await editRoot.getByText('notes/demo.txt', { exact: true }).count()).toBe(1) - - const writeRoot = page.locator('[data-variant="write"]').first() - await writeRoot.waitFor({ state: 'visible', timeout: 10_000 }) - expect(await writeRoot.getByText('Write', { exact: true }).count()).toBe(1) - expect(await writeRoot.getByText('notes/new-demo.txt', { exact: true }).count()).toBe(1) - }) - - it('keeps Markdown semantic while a fixture reply streams and finalizes', async () => { - onTestFailed(() => saveFailureShot(page, 'smoke-markdown-stream')) - await page.getByRole('button', { name: 'New session', exact: true }).click() - const input = page.locator('textarea[placeholder]') - await input.waitFor({ timeout: 15_000 }) - await input.fill('render markdown') - await page.getByRole('button', { name: '发送' }).click() - - const streaming = page.locator('[data-streaming="true"]') - await streaming.getByRole('heading', { name: 'Markdown fixture' }).waitFor({ timeout: 15_000 }) - await streaming.waitFor({ state: 'detached', timeout: 15_000 }) - - const finalHeading = page.getByRole('heading', { name: 'Markdown fixture' }) - expect(await finalHeading.evaluate(element => element.tagName)).toBe('H1') - expect(await page.locator('pre code').filter({ hasText: 'const markdown = true' }).count()).toBe(1) - const external = page.getByRole('link', { name: 'DeepSeek' }) - expect(await external.getAttribute('target')).toBe('_blank') - expect(await external.getAttribute('rel')).toBe('noopener noreferrer') - }) - - it('renders and completes the resident question through the composer slot', async () => { - onTestFailed(() => saveFailureShot(page, 'smoke-question-composer')) - const sessionTree = page.getByRole('tree', { name: 'Sessions' }) - const projectRow = sessionTree.getByRole('treeitem').filter({ hasText: '3 sessions' }) - if (await projectRow.getAttribute('aria-expanded') === 'false') await projectRow.click() - await sessionTree.getByText('Fixture 历史会话', { exact: true }).click() - const composer = page.locator('[data-question-key]') - await composer.waitFor({ timeout: 15_000 }) - expect({ - question: await composer.getByRole('heading').innerText(), - progress: await composer.getByText('1 / 3', { exact: true }).innerText(), - options: await composer.getByRole('radio').allTextContents(), - custom: await composer.getByRole('button', { name: '其他,请填写自定义答案' }).innerText(), - }).toMatchInlineSnapshot(` - { - "custom": "其他,请填写自定义答案", - "options": [ - "1工程落地型推荐更看重能直接做 runtime、tool executor、sandbox、trace 和线上问题排查。", - "2研究潜力型更看重 Agent 理解、训练评测思路和长期成长空间。", - "3均衡型同时要求工程能力和 Agent 认知,但可能筛选门槛更高。", - ], - "progress": "1 / 3", - "question": "你现在更想招哪类 Agent/Harness 候选人?", - } - `) - - await composer.getByRole('radio', { name: '工程落地型' }).click() - await composer.getByText('2 / 3', { exact: true }).waitFor() - await composer.getByRole('button', { name: '跳过本题', exact: true }).click() - await composer.getByRole('checkbox', { name: '系统设计' }).click() - await composer.getByRole('checkbox', { name: 'Agent 产品判断' }).click() - await composer.getByRole('checkbox', { name: 'Agent 产品判断' }).press('Enter') - - await composer.waitFor({ state: 'detached' }) - const restoredInput = page.locator('textarea[placeholder]') - await restoredInput.waitFor() - expect(await restoredInput.getAttribute('placeholder')).toBe('回复生成中,可停止后再输入') - }) - - it('stayed clean: no page errors across the whole load chain', () => { - expect(pageErrors).toEqual([]) - }) -}) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index f4fbbb265f..ce0a6db799 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -16,10 +16,7 @@ export function requireDist(): void { } } -/** - * OS-assigned free port, released before use. startWebServer echoes - * options.port instead of the bound one, so passing 0 directly is unusable. - */ +/** OS-assigned free port, released before use (the spawned `dsh web` needs a concrete --port). */ export function probeFreePort(): Promise<number> { return new Promise((resolvePort, reject) => { const probe = createServer() diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 998996304e..d0af0d4641 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -21,9 +21,6 @@ { "path": "../../packages/client/web" }, - { - "path": "../../packages/host/webserver" - }, { "path": "../../packages/client/modules" } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 5a805cbeb3..7043de4911 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -22,7 +22,7 @@ export default defineConfig({ { find: /^@deepseek-ai\/dsh-client-web-react$/, replacement: src('../../packages/client/web-react/src/index.ts') }, { find: /^@deepseek-ai\/dsh-client-ui-slots$/, replacement: src('../../packages/client/ui-slots/src/index.ts') }, { find: /^@deepseek-ai\/dsh-client-ui-primitives$/, replacement: src('../../packages/client/ui-primitives/src/index.ts') }, - { find: /^@deepseek-ai\/dsh-client-modules$/, replacement: src('../../packages/client/modules/src/index.ts') }, + { find: /^@deepseek-ai\/dsh-client-modules\/client$/, replacement: src('../../packages/client/modules/src/client/index.ts') }, ], }, define: { diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 272a6ade66..1798b46908 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.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 -architecture.md: 06d454f1c7da602c06de8062c10303a6178b728e -architecture.zh.md: 02c704d4270df60d596184e326515fca09841c71 +architecture.md: b426891c0483f42a64b597632cf1871aff79ca2d +architecture.zh.md: 13feefb6854e79ddee38602902d325a789fd7744 diff --git a/docs/architecture.md b/docs/architecture.md index 06d454f1c7..b426891c04 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -167,7 +167,7 @@ Exceptions combine layers: LLM interface/consumer; filesystem policy; web regist ### Bundles And Apps -`dsh-agent-spine-demo` bundles a spine and optional goals. App packages own the TUI, one-shot CLI, and ACP/JSON-RPC front doors ([README](../packages/examples/agent-spine-demo/README.md), [ui/](../packages/ui/README.md)). `dsh-jsonrpc-agent` boots external `cordis.yml`; the Python SDK supplies a default only without explicit config ([Python SDK](../python/README.md)). Thin deployments use swappable backends and optional tools ([examples/](../examples/AGENTS.md), [runnable wirings](cookbook/extension-cookbook.md#runnable-wirings), [graph atlas](graph-atlas.md)). +`dsh-agent-spine-demo` bundles a spine and optional goals. App packages own TUI, CLI, ACP automation, and JSON-RPC front doors ([README](../packages/examples/agent-spine-demo/README.md), [acp/](../packages/acp/README.md), [ui/](../packages/ui/README.md)). `dsh-jsonrpc-agent` boots external `cordis.yml`; the Python SDK supplies a default only without explicit config ([Python SDK](../python/README.md)). Thin deployments use swappable backends and optional tools ([examples/](../examples/AGENTS.md), [runnable wirings](cookbook/extension-cookbook.md#runnable-wirings), [graph atlas](graph-atlas.md)). ### Where New Behavior Goes diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 02c704d427..13feefb685 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -167,7 +167,7 @@ forever: ### 组合包与应用 -`dsh-agent-spine-demo` 组合一套主干和可选目标。应用包负责 TUI、单次运行的 CLI(命令行界面)以及 ACP/JSON-RPC 入口([README](../packages/examples/agent-spine-demo/README.md)、[ui/](../packages/ui/README.md))。`dsh-jsonrpc-agent` 启动外部 `cordis.yml`;Python SDK 仅在没有显式配置时提供默认项([Python SDK](../python/README.md))。轻量部署使用可替换后端和可选工具([examples/](../examples/AGENTS.md)、[可运行接线](cookbook/extension-cookbook.md#runnable-wirings)、[图谱](graph-atlas.md))。 +`dsh-agent-spine-demo` 组合一套主干和可选目标。应用包负责 TUI、CLI(命令行界面)、ACP 自动化入口和 JSON-RPC 入口([README](../packages/examples/agent-spine-demo/README.md)、[acp/](../packages/acp/README.md)、[ui/](../packages/ui/README.md))。`dsh-jsonrpc-agent` 启动外部 `cordis.yml`;Python SDK 仅在没有显式配置时提供默认项([Python SDK](../python/README.md))。轻量部署使用可替换后端和可选工具([examples/](../examples/AGENTS.md)、[可运行接线](cookbook/extension-cookbook.md#runnable-wirings)、[图谱](graph-atlas.md))。 ### 新行为的归属位置 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 4806a86e72..451e373044 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -35,7 +35,13 @@ flowchart LR pkg_tool_bash["tool-bash"] pkg_hooks_claude["hooks-claude"] pkg_hooks_codex["hooks-codex"] - pkg_acp["acp"] + pkg_storage["storage"] + svc_storage["ctx.storage<br/>Non-session storage hub"] + pkg_storage_json["storage-json"] + pkg_storage_sqlite["storage-sqlite"] + pkg_storage_domain["storage-domain"] + pkg_workspace["workspace"] + svc_workspace["ctx.workspace<br/>Workspace entity registry"] svc_sessionQuery["ctx.sessionQuery<br/>Session reads, traces, filters, and search"] pkg_session_reference["session-reference"] pkg_tool_session_query["tool-session-query"] @@ -68,6 +74,7 @@ flowchart LR svc_skills["ctx.skills<br/>Skill provider registry"] pkg_skill_local["skill-local"] svc_agents["ctx.agents<br/>Agent service"] + pkg_acp["acp"] pkg_tui_demo["tui-demo"] svc_agentLoop["ctx.agentLoop<br/>Concrete loop driver"] pkg_agent_spine_demo["agent-spine-demo"] @@ -119,12 +126,17 @@ flowchart LR svc_spillStore["ctx.spillStore<br/>Spill storage seam"] pkg_spill_local["spill-local"] pkg_spill_policy["spill-policy"] + pkg_webserver["webserver"] + svc_httpServer["ctx.httpServer<br/>HTTP route registration"] + pkg_connection["connection"] + pkg_modules["modules"] + pkg_hmr["hmr"] + svc_clientModuleHost["ctx.clientModuleHost<br/>Client plugin graph host"] pkg_workflow["workflow"] svc_workflows["ctx.workflows<br/>Workflow script engine"] pkg_workflow_workerthread["workflow-workerthread"] pkg_tool_workflow["tool-workflow"] pkg_acp --> svc_approval - pkg_acp --> svc_userInteraction pkg_agent --> svc_agents pkg_agent_loop --> svc_agentLoop pkg_approval --> svc_approval @@ -146,6 +158,7 @@ flowchart LR pkg_llm_deepseek --> svc_llm pkg_llm_pi_ai --> svc_llm pkg_llm_replay --> svc_llm + pkg_modules --> svc_clientModuleHost pkg_permission --> svc_permission pkg_plan_mode --> svc_planMode pkg_pty --> svc_pty @@ -167,6 +180,9 @@ flowchart LR pkg_skill_local --> svc_skills pkg_spill --> svc_spillStore pkg_spill_local --> svc_spillStore + pkg_storage --> svc_storage + pkg_storage_json --> svc_storage + pkg_storage_sqlite --> svc_storage pkg_subagent --> svc_subagents pkg_subagent_acp --> svc_subagents pkg_subagent_fork --> svc_subagents @@ -184,8 +200,10 @@ flowchart LR pkg_web_search_deepseek --> svc_web pkg_web_search_exa --> svc_web pkg_web_search_perplexity --> svc_web + pkg_webserver --> svc_httpServer pkg_workflow --> svc_workflows pkg_workflow_workerthread --> svc_workflows + pkg_workspace --> svc_workspace svc_agentLoop --> pkg_agent_spine_demo svc_agents --> pkg_acp svc_agents --> pkg_agent_loop @@ -197,26 +215,26 @@ flowchart LR svc_bash --> pkg_hooks_claude svc_bash --> pkg_hooks_codex svc_bash --> pkg_tool_bash + svc_clientModuleHost --> pkg_hmr svc_codeRuntime --> pkg_tools - svc_commands --> pkg_acp svc_commands --> pkg_tui svc_compact --> pkg_compact_basic svc_fs --> pkg_tool_fs + svc_httpServer --> pkg_connection + svc_httpServer --> pkg_hmr + svc_httpServer --> pkg_modules svc_invariants --> pkg_agent svc_invariants --> pkg_agent_loop svc_invariants --> pkg_scope svc_invariants --> pkg_session svc_llm --> pkg_agent_loop svc_llm --> pkg_compact_basic - svc_permission --> pkg_acp - svc_planMode --> pkg_acp svc_pty --> pkg_tool_pty svc_sandbox --> pkg_bash_sandbox svc_sandbox --> pkg_pty_local svc_sandboxPolicy --> pkg_bash_sandbox svc_sandboxPolicy --> pkg_fs_sandbox svc_sandboxPolicy --> pkg_pty_local - svc_sessionPersistence --> pkg_acp svc_sessionPersistence --> pkg_agent_loop svc_sessionPersistence --> pkg_hooks_claude svc_sessionPersistence --> pkg_hooks_codex @@ -225,7 +243,6 @@ flowchart LR svc_sessionPersistence --> pkg_tool_bash svc_sessionQuery --> pkg_session_reference svc_sessionQuery --> pkg_tool_session_query - svc_sessionReferences --> pkg_acp svc_sessionReferences --> pkg_tui svc_sessions --> pkg_agent svc_sessions --> pkg_agent_loop @@ -237,6 +254,8 @@ flowchart LR svc_sessions --> pkg_subagent_inprocess svc_skills --> pkg_tool_skill svc_spillStore --> pkg_spill_policy + svc_storage --> pkg_storage_domain + svc_storage --> pkg_workspace svc_subagents --> pkg_tool_ralph svc_subagents --> pkg_tool_subagent svc_systemPrompt --> pkg_agent_loop @@ -250,7 +269,6 @@ flowchart LR svc_tasks --> pkg_tool_tasks svc_tokenMeter --> pkg_compact_basic svc_toolResultPrune --> pkg_compact_basic - svc_tools --> pkg_acp svc_tools --> pkg_agent_loop svc_tools --> pkg_tool_ask_user svc_tools --> pkg_tool_bash @@ -261,7 +279,6 @@ flowchart LR svc_tools --> pkg_tool_subagent svc_tools --> pkg_tool_todo svc_tools --> pkg_tool_web - svc_userInteraction --> pkg_acp svc_userInteraction --> pkg_tool_ask_user svc_userInteraction --> pkg_tui svc_web --> pkg_tool_web @@ -277,18 +294,20 @@ flowchart LR | `ctx.toolResultPrune` | `core` | [`compact-tool-result-prune`](../packages/compact/compact-tool-result-prune) | - | [`compact-basic`](../packages/compact/compact-basic) | - | Rewrites oversized current tool results through replayable single-node surface replacements before summary compaction. | | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`cli-demo`](../packages/examples/cli-demo), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`invariants`](../packages/support/invariants) | - | Owns append-only Session instances and emits the durable session event feed. | | `ctx.invariants` | `core` | [`invariants`](../packages/support/invariants) | - | [`session`](../packages/core/session), [`agent`](../packages/core/agent), [`scope`](../packages/core/scope), [`agent-loop`](../packages/core/agent-loop) | - | Companion subpaths register owner-local checks; the service owns selection, uniqueness, child fibers, and package-attributed failures. | -| `ctx.sessionPersistence` | `seam` | [`session-persistence`](../packages/session-persistence/session-persistence) | [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session-persistence/session-persistence-sqlite) | [`agent-loop`](../packages/core/agent-loop), [`tool-bash`](../packages/bash/tool-bash), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`acp`](../packages/ui/acp), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | - | Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time. | +| `ctx.sessionPersistence` | `seam` | [`session-persistence`](../packages/session-persistence/session-persistence) | [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session-persistence/session-persistence-sqlite) | [`agent-loop`](../packages/core/agent-loop), [`tool-bash`](../packages/bash/tool-bash), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | - | Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time. | +| `ctx.storage` | `seam` | [`storage`](../packages/storage/storage) | [`storage-json`](../packages/storage/storage-json), [`storage-sqlite`](../packages/storage/storage-sqlite) | [`storage-domain`](../packages/storage/storage-domain), [`workspace`](../packages/workspace/workspace) | - | Backends register side by side under names; data forms (domain first) mount on the hub and translate typed operations into opaque KV-unit primitives. | +| `ctx.workspace` | `core` | [`workspace`](../packages/workspace/workspace) | - | - | - | Owns WorkspaceId-branded records over the domain form; sessionIds is the single source of ownership truth. RPC and GUI consumers arrive next phase. | | `ctx.sessionQuery` | `seam` | [`session-query`](../packages/session-query/session-query) | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | [`session-reference`](../packages/context/session-reference), [`tool-session-query`](../packages/session-query/tool-session-query) | - | The interface supplies exact reads, filters, and traces; its concrete backend adds full-text reconciliation, ranking, snippets, and cursor generations, while the model consumer owns workspace authority and cursor-free rendering. | -| `ctx.sessionReferences` | `core` | [`session-reference`](../packages/context/session-reference) | - | [`tui`](../packages/ui/tui), [`acp`](../packages/ui/acp) | - | Projects bounded current-surface conversation snapshots into durable untrusted message context; host adapters own mention syntax. | +| `ctx.sessionReferences` | `core` | [`session-reference`](../packages/context/session-reference) | - | [`tui`](../packages/ui/tui) | - | Projects bounded current-surface conversation snapshots into durable untrusted message context; host adapters own mention syntax. | | `ctx.sessionTitle` | `seam` | [`session-title`](../packages/session-title/session-title) | [`session-title-first-message-llm`](../packages/session-title/session-title-first-message-llm), [`session-title-all-messages-llm`](../packages/session-title/session-title-all-messages-llm) | - | - | Owns the deterministic fallback, latest-title fold, and sole optional asynchronous provider registration. | | `ctx.systemPrompt` | `core` | [`system-prompt`](../packages/core/system-prompt) | - | [`agent-loop`](../packages/core/agent-loop), [`tools`](../packages/core/tools), [`tool-fs`](../packages/fs/tool-fs), [`tool-pty`](../packages/pty/tool-pty), [`tool-web`](../packages/web/tool-web) | - | Collects prompt sections and model-facing tool schemas for each step. | -| `ctx.tools` | `core` | [`tools`](../packages/core/tools) | - | [`agent-loop`](../packages/core/agent-loop), [`tool-ask-user`](../packages/ui/tool-ask-user), [`tool-bash`](../packages/bash/tool-bash), [`tool-cordis`](../packages/cordis/tool-cordis), [`tool-fs`](../packages/fs/tool-fs), [`tool-pty`](../packages/pty/tool-pty), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-todo`](../packages/todo/tool-todo), [`tool-web`](../packages/web/tool-web), [`acp`](../packages/ui/acp) | - | Registers capabilities, owns Code Mode transport, and routes calls through pre-policy, monotonic guards, around dispatch, post-policy, and final-result observation. | -| `ctx.userInteraction` | `seam` | [`user-interaction`](../packages/ui/user-interaction) | [`tui`](../packages/ui/tui), [`acp`](../packages/ui/acp) | [`tool-ask-user`](../packages/ui/tool-ask-user), [`tui`](../packages/ui/tui), [`acp`](../packages/ui/acp) | - | UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise. | -| `ctx.planMode` | `core` | [`plan-mode`](../packages/plan/plan-mode) | - | [`acp`](../packages/ui/acp) | - | Folds logged plan/mode state, flushes user selections at turn boundaries, renders deployment-owned guidance, registers /plan, and keeps the plan-exit schema stable across transitions. | -| `ctx.commands` | `core` | [`commands`](../packages/ui/commands) | - | [`tui`](../packages/ui/tui), [`acp`](../packages/ui/acp) | - | Plugins register direct human commands; TUI and ACP consume the same effective per-agent catalog without sending invocations to the model. | +| `ctx.tools` | `core` | [`tools`](../packages/core/tools) | - | [`agent-loop`](../packages/core/agent-loop), [`tool-ask-user`](../packages/ui/tool-ask-user), [`tool-bash`](../packages/bash/tool-bash), [`tool-cordis`](../packages/cordis/tool-cordis), [`tool-fs`](../packages/fs/tool-fs), [`tool-pty`](../packages/pty/tool-pty), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-todo`](../packages/todo/tool-todo), [`tool-web`](../packages/web/tool-web) | - | Registers capabilities, owns Code Mode transport, and routes calls through pre-policy, monotonic guards, around dispatch, post-policy, and final-result observation. | +| `ctx.userInteraction` | `seam` | [`user-interaction`](../packages/ui/user-interaction) | [`tui`](../packages/ui/tui) | [`tool-ask-user`](../packages/ui/tool-ask-user), [`tui`](../packages/ui/tui) | - | UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise. | +| `ctx.planMode` | `core` | [`plan-mode`](../packages/plan/plan-mode) | - | - | - | Folds logged plan/mode state, flushes user selections at turn boundaries, renders deployment-owned guidance, registers /plan, and keeps the plan-exit schema stable across transitions. | +| `ctx.commands` | `core` | [`commands`](../packages/ui/commands) | - | [`tui`](../packages/ui/tui) | - | Plugins register direct human commands; TUI consumes the effective per-agent catalog without sending invocations to the model. | | `ctx.tui` | `bundle` | [`tui`](../packages/ui/tui) | - | - | - | One TUI front door provides a FIFO overlay host; injected plugins receive caller-fiber ownership without access to pi-tui or terminal lifecycle state. | | `ctx.skills` | `seam` | [`skill`](../packages/skill/skill) | [`skill-local`](../packages/skill/skill-local) | [`tool-skill`](../packages/skill/tool-skill) | - | Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies. | -| `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/ui/acp), [`cli-demo`](../packages/examples/cli-demo), [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`tui-demo`](../packages/examples/tui-demo) | - | Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation. | +| `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`cli-demo`](../packages/examples/cli-demo), [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`tui-demo`](../packages/examples/tui-demo) | - | Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation. | | `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`agent-spine-demo`](../packages/examples/agent-spine-demo) | - | The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package. | | `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | Folds revisioned objective state from the session log and keeps live continuation activation process-local. | | `ctx.bash` | `seam` | [`bash`](../packages/bash/bash) | [`bash-local`](../packages/bash/bash-local), [`bash-sandbox`](../packages/bash/bash-sandbox) | [`tool-bash`](../packages/bash/tool-bash), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | - | The model-facing bash tools and hook bridges consume this seam; sandboxed or remote executors replace bash-local without touching them. | @@ -296,8 +315,8 @@ flowchart LR | `ctx.pty` | `seam` | [`pty`](../packages/pty/pty) | [`pty-local`](../packages/pty/pty-local) | [`tool-pty`](../packages/pty/tool-pty) | - | The registry owns exact-Agent session identity and cleanup; backends own terminal mechanics, while tool-pty exposes the owner-scoped model surface. | | `ctx.sandbox` | `seam` | [`sandbox`](../packages/sandbox/sandbox) | [`sandbox-local`](../packages/sandbox/sandbox-local) | [`bash-sandbox`](../packages/bash/bash-sandbox), [`pty-local`](../packages/pty/pty-local) | - | Consumers hand over the exact argv they are about to spawn; same-world backends wrap it under a per-call policy and report enforcement. | | `ctx.sandboxPolicy` | `core` | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | - | [`bash-sandbox`](../packages/bash/bash-sandbox), [`fs-sandbox`](../packages/fs/fs-sandbox), [`pty-local`](../packages/pty/pty-local) | - | The one home for the deployment default mode + workspace root; only the sandboxed executor and provider read the service (the tool layers use the pure `sandbox/mode` fold it also exports). Both enforcing families read it so bash and fs cannot confine to different roots. | -| `ctx.approval` | `seam` | `approval` | [`acp`](../packages/ui/acp) | [`tools`](../packages/core/tools), [`tool-bash`](../packages/bash/tool-bash) | - | One-shot permission decisions dispatched over the `approval/request` waterfall; answerers are listeners (the ACP bridge for its own agents), absence fails closed to `unavailable`. | -| `ctx.permission` | `core` | [`permission`](../packages/ui/permission) | - | [`acp`](../packages/ui/acp) | - | User-facing preset table (`workspace-write`/`danger-full-access`) bundling the sandbox-mode and approval-policy knobs; a switch writes one `permission/preset` event through to both knob events. | +| `ctx.approval` | `seam` | `approval` | [`acp`](../packages/acp/acp) | [`tools`](../packages/core/tools), [`tool-bash`](../packages/bash/tool-bash) | - | One-shot permission decisions dispatched over the `approval/request` waterfall; answerers are listeners (the ACP bridge for its own agents), absence fails closed to `unavailable`. | +| `ctx.permission` | `core` | [`permission`](../packages/ui/permission) | - | - | - | User-facing preset table (`workspace-write`/`danger-full-access`) bundling the sandbox-mode and approval-policy knobs; a switch writes one `permission/preset` event through to both knob events. | | `ctx.codeRuntime` | `seam` | [`code-runtime`](../packages/code-runtime/code-runtime) | [`code-runtime-worker`](../packages/code-runtime/code-runtime-worker) | [`tools`](../packages/core/tools) | - | Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the tool registry consumes it for Code Mode). | | `ctx.fs` | `seam` | [`fs`](../packages/fs/fs) | [`fs-local`](../packages/fs/fs-local), [`fs-sandbox`](../packages/fs/fs-sandbox) | [`tool-fs`](../packages/fs/tool-fs) | [`fs-policy`](../packages/fs/fs-policy) | tool-fs executes read/write/edit through ctx.fs; fs-sandbox fences mutations by the shared sandbox mode; fs-policy contributes observed-state checks through the fs/* event gate. | | `ctx.compact` | `seam` | [`compact`](../packages/compact/compact) | [`compact-basic`](../packages/compact/compact-basic) | [`compact-basic`](../packages/compact/compact-basic) | - | The basic backend consumes post-step pressure and request-error recovery events; a model-facing compact tool remains deferred. | @@ -305,6 +324,8 @@ flowchart LR | `ctx.tasks` | `core` | [`tasks`](../packages/tasks/tasks) | - | [`tool-bash`](../packages/bash/tool-bash), [`tool-pty`](../packages/pty/tool-pty), [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-tasks`](../packages/tasks/tool-tasks) | - | Producers (background bash, PTY sends, and subagent delegations) register running work; tool-tasks is the model-facing control surface that reads, lists, and kills it. | | `ctx.web` | `seam` | [`web`](../packages/web/web) | [`web-search-exa`](../packages/web/web-search-exa), [`web-search-perplexity`](../packages/web/web-search-perplexity), [`web-search-deepseek`](../packages/web/web-search-deepseek), [`web-fetch-local`](../packages/web/web-fetch-local) | [`tool-web`](../packages/web/tool-web) | - | Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names. | | `ctx.spillStore` | `seam` | [`spill`](../packages/spill/spill) | [`spill-local`](../packages/spill/spill-local) | [`spill-policy`](../packages/spill/spill-policy) | - | The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill. | +| `ctx.httpServer` | `core` | `webserver` | - | `connection`, `modules`, `hmr` | - | Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes. | +| `ctx.clientModuleHost` | `core` | `modules` | - | `hmr` | - | Composes the __DSH_BOOT__ entry graph from an incremental dshClient scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers. | | `ctx.workflows` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/workflow/tool-ralph) | - | One engine per context (bash shape, no named-provider registry); the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents. | Maintenance mode: hybrid: services are discovered from Cordis declarations; interface/implementation/consumer roles are classified in `scripts/gen-doc-graphs.ts` with a completeness guard. diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 88d8f1bbaa..a1b9d4449f 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -11,14 +11,14 @@ A `Requires:` line lists the service keys the plugin `inject`s: its `cordis.yml` ## `@deepseek-ai/dsh-acp` -Requires: `agents` · `commands` · `sessionPersistence` · `sessionQuery` · `tools` · `userInteraction` · `llm` · `systemPrompt` +Requires: `agents` ```ts config-catalog -/** Plugin config: the agent template ACP sessions are created from. */ +/** Plugin config: the provider/model target used for each ACP-created agent. */ export interface AcpConfig { /** Provider route for created agents. */ provider?: string - /** Model name for created agents (must have a registered adapter). */ + /** Model name for created agents. */ model?: string /** Runtime-only transport override; production uses stdio. */ stream?: Stream @@ -27,15 +27,14 @@ export interface AcpConfig { Depends on: `Stream` (`@agentclientprotocol/sdk`) -Source: [`packages/ui/acp/src/index.ts:285`](../packages/ui/acp/src/index.ts) +Source: [`packages/acp/acp/src/index.ts:56`](../packages/acp/acp/src/index.ts) ## `@deepseek-ai/dsh-acp-demo` ```ts config-catalog /** - * App config: the swappable per-deployment values. `provider` and `model` configure the - * agent template the ACP bridge creates each session's agent from (NOT a - * pre-created agent — ACP creates agents at `session/new`); `persona` is the + * App config: the swappable per-deployment values. `provider` and `model` configure + * each agent the ACP bridge creates at `session/new`; `persona` is the * deployment persona (forwarded to the system-prompt plugin); `toolOrder` is * the explicit model-facing tool order (forwarded to the system-prompt plugin); * `tools` is the tool registry's config (its presentation `mode`, forwarded @@ -64,8 +63,6 @@ export interface Config { packChunks?: boolean /** JSONL artifact encoding; defaults to checksummed Zstandard frames. */ persistenceCompression?: JsonlCompression - /** Cross-session reference discovery and snapshot byte budgets. */ - sessionReferences?: SessionReferenceConfig /** Controls automatic AGENTS.md/CLAUDE.md loading; configure a byte budget or set `false`. */ workspaceContext: agentCore.Config['workspaceContext'] /** Skill registry, local-provider, and model-facing consumer config forwarded to agent-spine-demo. */ @@ -74,16 +71,16 @@ export interface Config { toolBash?: NonNullable<agentCore.Config['toolBash']> /** Generic background-task controls forwarded through agent-core; set false to omit their tool surface. */ toolTasks?: NonNullable<agentCore.Config['toolTasks']> - /** Persisted same-session goals; owner defaults enable them, or false disables the stack and command. */ + /** Persisted same-session goals; owner defaults enable them, or false disables the stack and tools. */ goals?: agentCore.GoalConfig | false /** Bounded transient model-request retry policy forwarded through agent-core. */ llmRetry?: NonNullable<agentCore.Config['llmRetry']> } ``` -Depends on: [`agentCore`](../packages/examples/agent-spine-demo/src/index.ts) · [`JsonlCompression`](../packages/session-persistence/session-persistence-jsonl/src/index.ts) · [`SessionReferenceConfig`](#deepseek-aidsh-session-reference) · [`ToolsConfig`](#deepseek-aidsh-tools) +Depends on: [`agentCore`](../packages/examples/agent-spine-demo/src/index.ts) · [`JsonlCompression`](../packages/session-persistence/session-persistence-jsonl/src/index.ts) · [`ToolsConfig`](#deepseek-aidsh-tools) -Source: [`packages/examples/acp-demo/src/index.ts:44`](../packages/examples/acp-demo/src/index.ts) +Source: [`packages/examples/acp-demo/src/index.ts:39`](../packages/examples/acp-demo/src/index.ts) ## `@deepseek-ai/dsh-agent-loop` @@ -276,6 +273,20 @@ Depends on: [`agentCore`](../packages/examples/agent-spine-demo/src/index.ts) · Source: [`packages/examples/cli-demo/src/index.ts:26`](../packages/examples/cli-demo/src/index.ts) +## `@deepseek-ai/dsh-client-hmr` + +Requires: `clientModuleHost` · `httpServer` + +```ts config-catalog +/** Plugin config, validated by the same-named schemastery schema. */ +export interface Config { + /** Bundle stat-poll interval in milliseconds (default 500, the build-side watcher's polling default). */ + pollIntervalMs?: number +} +``` + +Source: [`packages/client/hmr/src/index.ts:29`](../packages/client/hmr/src/index.ts) + ## `@deepseek-ai/dsh-code-runtime-worker` ```ts config-catalog @@ -474,6 +485,38 @@ export interface Config { Source: [`packages/hooks/hooks-codex/src/index.ts:42`](../packages/hooks/hooks-codex/src/index.ts) +## `@deepseek-ai/dsh-host-apiproxy` + +Requires: `agents` · `sessions` · `tools` · `userInteraction` + +```ts config-catalog +/** Gateway plugin config: the host-level default agent routing. */ +export interface Config { + /** Default provider route for created/resumed agents. */ + provider: string + /** Default model id. */ + model: string +} +``` + +Source: [`packages/host/apiproxy/src/index.ts:32`](../packages/host/apiproxy/src/index.ts) + +## `@deepseek-ai/dsh-host-webserver` + +```ts config-catalog +/** Gateway config: listen address plus the static dist anchor (injected by the composing app, never self-resolved). */ +export interface Config { + /** Listen host; the two supported values are loopback and all-interfaces. */ + host: '127.0.0.1' | '0.0.0.0' + /** Listen port; zero requests an OS-assigned port. */ + port: number + /** Absolute path of index.html inside the static root (dist location is workspace knowledge of the app). */ + distIndex: string +} +``` + +Source: [`packages/host/webserver/src/index.ts:39`](../packages/host/webserver/src/index.ts) + ## `@deepseek-ai/dsh-invariants` ```ts config-catalog @@ -624,7 +667,7 @@ export interface ReplayProviderConfig { id: string /** Selector label; defaults to {@link id}. */ name?: string - /** Advisory models exposed to clients such as ACP editors. */ + /** Advisory models exposed to replay scenarios that exercise discovery. */ models?: ReplayModelConfig[] } @@ -641,7 +684,7 @@ export interface ReplayModelConfig { } ``` -Source: [`packages/support/llm-replay/src/index.ts:387`](../packages/support/llm-replay/src/index.ts) +Source: [`packages/support/llm-replay/src/index.ts:392`](../packages/support/llm-replay/src/index.ts) ## `@deepseek-ai/dsh-llm-retry` @@ -1157,6 +1200,84 @@ export interface Config { Source: [`packages/spill/spill-policy/src/index.ts:51`](../packages/spill/spill-policy/src/index.ts) +## `@deepseek-ai/dsh-storage-domain` + +Requires: `storage` + +```ts config-catalog +/** + * Plugin config. Which backend serves which domain is decided here, not + * globally on the hub: `backend` is the default route and `routes` overrides + * it per domain name. A route naming an unregistered backend fails loud at + * `open` with `backend-not-found`. + */ +export interface Config { + /** Default backend name for every domain without an explicit route. Required: there is no universally correct medium. */ + backend: string + /** Per-domain overrides: domain name → backend name. */ + routes?: Record<string, string> +} +``` + +Source: [`packages/storage/storage-domain/src/index.ts:45`](../packages/storage/storage-domain/src/index.ts) + +## `@deepseek-ai/dsh-storage-json` + +Requires: `storage` + +```ts config-catalog +/** + * Plugin configuration. + * `root` has NO default on purpose: a `process.cwd()` fallback would scatter + * unit files wherever the process happens to start; assemblies state the + * location explicitly. + */ +export interface Config { + /** Directory holding one `<unit>.json` file per unit. */ + root: string +} +``` + +Source: [`packages/storage/storage-json/src/index.ts:27`](../packages/storage/storage-json/src/index.ts) + +## `@deepseek-ai/dsh-storage-sqlite` + +Requires: `storage` + +```ts config-catalog +/** Plugin configuration. */ +export interface Config { + /** + * Filesystem path to the SQLite database file. The special value `:memory:` + * opens an in-process database (tests). On filesystems with POSIX modes, + * missing directories and databases are created owner-only; existing path + * modes are preserved. Filesystem setup errors other than an existing + * database fail the open. The backend does not protect confidentiality or + * integrity when another principal can replace the database entry in its + * parent directory. + */ + path: string + /** + * SQLite `journal_mode` pragma. `wal` (the default) suits local disks; pick + * a rollback-journal mode (`delete`/`truncate`/`persist`) on filesystems + * where WAL's shared-memory files do not work (network mounts). See + * {@link JournalMode}. + */ + journalMode?: JournalMode +} + +/** + * Journal modes the backend will run under. `wal` is the default; the + * rollback-journal modes (`delete`/`truncate`/`persist`) exist for + * filesystems where WAL's shared-memory files do not work (network mounts). + * `memory`/`off` are excluded: dropping journal durability silently + * contradicts the durability clause of the KV backend contract. + */ +export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' +``` + +Source: [`packages/storage/storage-sqlite/src/index.ts:24`](../packages/storage/storage-sqlite/src/index.ts) + ## `@deepseek-ai/dsh-subagent-acp` Requires: `subagents` @@ -1911,9 +2032,9 @@ Source: [`packages/context/workspace-context/src/config.ts:17`](../packages/cont These load from a `cordis.yml` entry with no `config:` block; they declare no config surface. - `@deepseek-ai/dsh-agent` ([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts)) -- `@deepseek-ai/dsh-client-connection` ([`packages/client/connection/src/index.ts`](../packages/client/connection/src/index.ts)) -- `@deepseek-ai/dsh-client-hmr` ([`packages/client/hmr/src/index.ts`](../packages/client/hmr/src/index.ts)) +- `@deepseek-ai/dsh-client-connection` — requires `httpServer` · `apiProxy` ([`packages/client/connection/src/index.ts`](../packages/client/connection/src/index.ts)) - `@deepseek-ai/dsh-client-i18n` ([`packages/client/i18n/src/index.ts`](../packages/client/i18n/src/index.ts)) +- `@deepseek-ai/dsh-client-modules` — requires `httpServer` · `loader` ([`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts)) - `@deepseek-ai/dsh-client-runtime` ([`packages/client/runtime/src/index.ts`](../packages/client/runtime/src/index.ts)) - `@deepseek-ai/dsh-client-ui-conversation` ([`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts)) - `@deepseek-ai/dsh-client-ui-layout` ([`packages/client/ui-layout/src/index.ts`](../packages/client/ui-layout/src/index.ts)) @@ -1930,12 +2051,14 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-pty` ([`packages/pty/pty/src/index.ts`](../packages/pty/pty/src/index.ts)) - `@deepseek-ai/dsh-session` ([`packages/core/session/src/index.ts`](../packages/core/session/src/index.ts)) - `@deepseek-ai/dsh-session-checkpoint-policy` — requires `llm` · `sessionPersistence` · `sessions` · `tools` ([`packages/session-persistence/session-checkpoint-policy/src/index.ts`](../packages/session-persistence/session-checkpoint-policy/src/index.ts)) +- `@deepseek-ai/dsh-storage` ([`packages/storage/storage/src/index.ts`](../packages/storage/storage/src/index.ts)) - `@deepseek-ai/dsh-subagent` ([`packages/subagent/subagent/src/index.ts`](../packages/subagent/subagent/src/index.ts)) - `@deepseek-ai/dsh-tasks` ([`packages/tasks/tasks/src/index.ts`](../packages/tasks/tasks/src/index.ts)) - `@deepseek-ai/dsh-timeout-policy` — requires `tools` ([`packages/timeout/timeout-policy/src/index.ts`](../packages/timeout/timeout-policy/src/index.ts)) - `@deepseek-ai/dsh-tool-ask-user` — requires `tools` · `userInteraction` ([`packages/ui/tool-ask-user/src/index.ts`](../packages/ui/tool-ask-user/src/index.ts)) - `@deepseek-ai/dsh-tool-todo` — requires `tools` ([`packages/todo/tool-todo/src/index.ts`](../packages/todo/tool-todo/src/index.ts)) - `@deepseek-ai/dsh-user-interaction` ([`packages/ui/user-interaction/src/index.ts`](../packages/ui/user-interaction/src/index.ts)) +- `@deepseek-ai/dsh-workspace` — requires `storage` ([`packages/workspace/workspace/src/index.ts`](../packages/workspace/workspace/src/index.ts)) ## Seam packages (not directly loadable) @@ -1960,16 +2083,13 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. - `@deepseek-ai/dsh-agent-loop-testkit` ([`packages/support/agent-loop-testkit/src/index.ts`](../packages/support/agent-loop-testkit/src/index.ts)) - `@deepseek-ai/dsh-app-boot` ([`packages/ui/app-boot/src/index.ts`](../packages/ui/app-boot/src/index.ts)) - `@deepseek-ai/dsh-brand` ([`packages/util/brand/src/index.ts`](../packages/util/brand/src/index.ts)) -- `@deepseek-ai/dsh-client-modules` ([`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts)) - `@deepseek-ai/dsh-client-ui-primitives` ([`packages/client/ui-primitives/src/index.ts`](../packages/client/ui-primitives/src/index.ts)) - `@deepseek-ai/dsh-client-ui-slots` ([`packages/client/ui-slots/src/index.ts`](../packages/client/ui-slots/src/index.ts)) - `@deepseek-ai/dsh-client-web` ([`packages/client/web/src/index.ts`](../packages/client/web/src/index.ts)) - `@deepseek-ai/dsh-client-web-react` ([`packages/client/web-react/src/index.ts`](../packages/client/web-react/src/index.ts)) - `@deepseek-ai/dsh-helper` ([`packages/sdk/helper/src/index.ts`](../packages/sdk/helper/src/index.ts)) - `@deepseek-ai/dsh-hook-protocol` ([`packages/hooks/hook-protocol/src/index.ts`](../packages/hooks/hook-protocol/src/index.ts)) -- `@deepseek-ai/dsh-host-apiproxy` ([`packages/host/apiproxy/src/index.ts`](../packages/host/apiproxy/src/index.ts)) - `@deepseek-ai/dsh-host-runtime` ([`packages/host/runtime/src/index.ts`](../packages/host/runtime/src/index.ts)) -- `@deepseek-ai/dsh-host-webserver` ([`packages/host/webserver/src/index.ts`](../packages/host/webserver/src/index.ts)) - `@deepseek-ai/dsh-jsonrpc-demo` ([`packages/examples/jsonrpc-demo/src/index.ts`](../packages/examples/jsonrpc-demo/src/index.ts)) - `@deepseek-ai/dsh-loader-smoke` ([`packages/support/loader-smoke/src/index.ts`](../packages/support/loader-smoke/src/index.ts)) - `@deepseek-ai/dsh-paths` ([`packages/util/paths/src/index.ts`](../packages/util/paths/src/index.ts)) diff --git a/docs/cookbook/adding-a-tool.i18n.yaml b/docs/cookbook/adding-a-tool.i18n.yaml index 2c8f18513b..4c0e480bee 100644 --- a/docs/cookbook/adding-a-tool.i18n.yaml +++ b/docs/cookbook/adding-a-tool.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 -adding-a-tool.md: 788c967cffa9df06e8d96e190930d69b9f2182ed -adding-a-tool.zh.md: 4ff9ce25a66625435ccba4454f2ac4b5472e5668 +adding-a-tool.md: c4deed8e13afcdc8e1a714364b086b8b0da018c1 +adding-a-tool.zh.md: 103c92b596a90192aae5a6b4d1e42fbcf052cf66 diff --git a/docs/cookbook/adding-a-tool.md b/docs/cookbook/adding-a-tool.md index 788c967cff..c4deed8e13 100644 --- a/docs/cookbook/adding-a-tool.md +++ b/docs/cookbook/adding-a-tool.md @@ -64,9 +64,9 @@ In [Code Mode](../../packages/core/tools/README.md), every visible registered to Design `output.schema` as a useful programmatic API: return handles and fields directly, allow scalar/array/null roots when they are the honest value, and keep human explanation in `output.render`. Intermediate values are execution-local, are not persisted or prompt-truncated, and have no byte cap, so the producer's truthful acquisition bounds and process memory still matter. Only the outer `run_code` logs/result cross the configurable output cap and model-facing spill pipeline. -## How your tool renders in an editor (ACP presentation) +## How your tool renders in a UI -Your tool's `output.render` returns model-facing content; its **editor card** is a separate concern declared through pure presentation projections and optional `presentCall` / `presentResult` methods. Design these alongside the canonical value—an editor (Zed, over the ACP bridge) shows the card, and a tool with no UI presentation falls back to a generic card (title = tool name, raw args as input). +Your tool's `output.render` returns model-facing content; its **UI card** is a separate concern declared through pure presentation projections and optional `presentCall` / `presentResult` methods. Design these alongside the canonical value. A tool with no UI presentation falls back to a generic card (title = tool name, raw args as input). Both methods return a **`card`-tagged render intent** — pick the card kind that matches what your tool does: @@ -76,17 +76,17 @@ Both methods return a **`card`-tagged render intent** — pick the card kind tha - `{ card: 'diff', title, diffs, locations? }` — your call creates or modifies a file. `diffs: [{ path, oldText, newText }]` (`oldText: null` for a new file) renders as an inline diff card. (tool-fs `write`/`edit`.) - `presentResult(args, { content, isError, meta? })` returns the completed card: - `generic` supplies an optional title and content. - - `terminal` supplies raw output and optional exit metadata; the bridge renders the capability-specific or fenced fallback view. - - `diff` supplies applied hunks, often derived by `output.presentationMeta` and carried in persisted `result.meta` so replay reproduces them. Mutation tools keep a diff result because an ACP update replaces the pending card's content. + - `terminal` supplies raw output and optional exit metadata; each UI renders its capable or fallback view. + - `diff` supplies applied hunks, often derived by `output.presentationMeta` and carried in persisted `result.meta` so replay reproduces them. Mutation tools keep a diff result because the completed view replaces the pending card. Hard rules (they bite if broken): -- **Purity.** These run on live streaming AND on session-log REPLAY, so they must be pure functions of `args` (+ the result) — NO I/O, NO reading session state, NO clock/random. A diff is derived from the args (`write` uses `oldText: null` because a call-time presenter has no prior file content); the BRIDGE, not the tool, fills the session cwd and relativizes a display-path title. If you find yourself wanting the file's old content or the working directory inside `presentCall`, stop — that belongs on the bridge or a future result-event shape, not the presenter. -- **UI-only formatting stays out of the model result.** A fenced ` ```console ` block, a diff, a relativized path—none of these belongs in the canonical value or Native content merely to serve an editor. `output.render` owns model-facing prose; `presentationMeta` plus the card presenters own replayable UI state. A `terminal` result view carries raw output and the bridge adds fences. +- **Purity.** These run on live streaming AND on session-log REPLAY, so they must be pure functions of `args` (+ the result) — NO I/O, NO reading session state, NO clock/random. A diff is derived from the args (`write` uses `oldText: null` because a call-time presenter has no prior file content); the UI adapter, not the tool, supplies session context. If you find yourself wanting the file's old content or the working directory inside `presentCall`, stop — that belongs in durable result metadata or the adapter, not the presenter. +- **UI-only formatting stays out of the model result.** A fenced ` ```console ` block, a diff, a relativized path—none of these belongs in the canonical value or Native content merely to serve a UI. `output.render` owns model-facing prose; `presentationMeta` plus the card presenters own replayable UI state. A `terminal` result view carries raw output and the adapter adds any fallback framing. - **`defineTool` soft-validates the display path.** A malformed/older logged arg shape makes the wrapper return `undefined` (a generic fallback) rather than throw — display must never crash a replay. -The neutral vocabulary lives in `dsh-tools` (never import an ACP type into a tool); the ACP bridge maps each `card` to the wire. The design and the why are in [the render-intent-union Agent Note](../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md); `dsh-tool-fs` (generic/diff) and `dsh-tool-bash` (terminal) are the reference implementations. +The neutral vocabulary lives in `dsh-tools`; tools never import a UI or transport type. The TUI and host/client runtime map each `card` into their own view. The design and the why are in [the render-intent-union Agent Note](../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md); `dsh-tool-fs` (generic/diff) and `dsh-tool-bash` (terminal) are the reference implementations. ## Tests every tool needs -Cover argument rejection, every canonical value and Native rendering shape, output-schema rejection, and HMR disposal. For a side-effecting tool, drive the real tool through the agent loop with a scripted `MockAdapter` and assert its `tool/call` and projected `tool/result` session events; prove the canonical value itself is not persisted. For an editor card, assert the exact `presentCall` and `presentResult` views and add an [ACP snapshot](../../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md) through the real bridge; a terminal card's scenario sets `terminalOutput: true` to exercise the capable-client path. +Cover argument rejection, every canonical value and Native rendering shape, output-schema rejection, and HMR disposal. For a side-effecting tool, drive the real tool through the agent loop with a scripted `MockAdapter` and assert its `tool/call` and projected `tool/result` session events; prove the canonical value itself is not persisted. For a UI card, assert the exact `presentCall` and `presentResult` views and exercise the owning TUI or host/client projection. Add an assembled snapshot for the shipped model or UI behavior the tool changes. diff --git a/docs/cookbook/adding-a-tool.zh.md b/docs/cookbook/adding-a-tool.zh.md index 4ff9ce25a6..103c92b596 100644 --- a/docs/cookbook/adding-a-tool.zh.md +++ b/docs/cookbook/adding-a-tool.zh.md @@ -64,9 +64,9 @@ producer 提供同步的 `cancel`、在资源清理后 settle 且不 reject 的 请把 `output.schema` 设计为实用的程序化 API:直接返回句柄与字段;当标量、数组或 null 确实就是结果时,允许采用相应的根类型;将面向人类的解释放入 `output.render`。中间值只存在于执行期间,不会被持久化或按提示词上限截断,也不设字节上限,因此生产方如实声明的采集边界和进程内存仍然重要。只有外层 `run_code` 日志/结果会受到可配置输出上限和面向模型的输出落盘流水线约束。 -## 工具在编辑器中的渲染方式(ACP 展示) +## 工具在 UI 中的渲染方式 -工具的 `output.render` 返回模型可见的内容;其**编辑器卡片**是另一项独立关注点,通过纯展示投影以及可选的 `presentCall`/`presentResult` 方法声明。请将这些内容与规范值一并设计:编辑器(如 Zed,通过 ACP(Agent Client Protocol)桥接)会展示该卡片,没有 UI 展示方法的工具则回退到通用卡片(标题 = 工具名,原始 args 作为输入)。 +工具的 `output.render` 返回模型可见的内容;其 **UI 卡片** 是另一项独立关注点,通过纯展示投影以及可选的 `presentCall`/`presentResult` 方法声明。请将这些内容与规范值一并设计。没有 UI 展示方法的工具会回退到通用卡片(标题 = 工具名,原始 args 作为输入)。 两个方法都返回一个 **`card` 标签的渲染意图**——选择与你的工具行为匹配的卡片类型: @@ -76,17 +76,17 @@ producer 提供同步的 `cancel`、在资源清理后 settle 且不 reject 的 - `{ card: 'diff', title, diffs, locations? }`——你的调用创建或修改文件。`diffs: [{ path, oldText, newText }]`(新文件时 `oldText: null`)渲染为内联 diff 卡片。(tool-fs `write`/`edit`。) - `presentResult(args, { content, isError, meta? })` 返回完成后的卡片: - `generic` 提供可选的标题和内容。 - - `terminal` 提供原始输出和可选的退出元数据;桥接层渲染能力特定或围栏回退视图。 - - `diff` 提供已应用的 hunk,通常由 `output.presentationMeta` 派生并通过持久化的 `result.meta` 携带,使回放能重现它们。变更类工具保留 diff 结果,因为 ACP 更新会替换 pending 卡片的内容。 + - `terminal` 提供原始输出和可选的退出元数据;各 UI 根据自身能力渲染对应视图或回退视图。 + - `diff` 提供已应用的 hunk,通常由 `output.presentationMeta` 派生并通过持久化的 `result.meta` 携带,使回放能重现它们。变更类工具保留 diff 结果,因为完成后的视图会替换 pending 卡片。 硬性规则(违反会出问题): -- **纯函数。** 这些方法在实时流式输出和会话日志回放时都会运行,因此必须是 `args`(加 result)的纯函数——不做 I/O、不读会话状态、不用时钟/随机数。diff 从 args 派生(`write` 使用 `oldText: null`,因为调用时的展示器没有文件先前内容);**桥接层**(而非工具)填充会话 cwd 并相对化展示路径标题。如果你发现自己想在 `presentCall` 内获取文件旧内容或工作目录,请停下——那属于桥接层或未来的 result-event 形态,不属于展示器。 -- **UI 格式不进入模型结果。** 围栏 ` ```console ` 块、diff、相对化路径均不应仅为服务编辑器而进入规范值或 Native 内容。`output.render` 负责模型可见的自然语言;`presentationMeta` 和卡片展示器负责可回放的 UI 状态。`terminal` 结果视图携带原始输出,由桥接层添加围栏。 +- **纯函数。** 这些方法在实时流式输出和会话日志回放时都会运行,因此必须是 `args`(加 result)的纯函数——不做 I/O、不读会话状态、不用时钟/随机数。diff 从 args 派生(`write` 使用 `oldText: null`,因为调用时的展示器没有文件先前内容);会话上下文由 UI 适配器而非工具提供。如果你发现自己想在 `presentCall` 内获取文件旧内容或工作目录,请停下:那属于持久结果元数据或适配器,不属于展示器。 +- **UI 格式不进入模型结果。** 围栏 ` ```console ` 块、diff、相对化路径均不应仅为服务 UI 而进入规范值或 Native 内容。`output.render` 负责模型可见的自然语言;`presentationMeta` 和卡片展示器负责可回放的 UI 状态。`terminal` 结果视图携带原始输出,由适配器按需添加回退格式。 - **`defineTool` 对展示路径做软校验。** 格式错误或旧版日志中的 arg 形态会使包装器返回 `undefined`(通用回退)而非抛异常——展示绝不能导致回放崩溃。 -中性词汇定义在 `dsh-tools` 中(绝不在工具中导入 ACP 类型);ACP 桥接层将每个 `card` 映射到协议格式(wire format)。设计与原因见[渲染意图联合体 Agent Note](../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md);`dsh-tool-fs`(generic/diff)和 `dsh-tool-bash`(terminal)是参考实现。 +中性词汇定义在 `dsh-tools` 中;工具绝不导入 UI 或传输类型。TUI 和 host/client 运行时将每个 `card` 映射到各自的视图。设计与原因见[渲染意图联合体 Agent Note](../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md);`dsh-tool-fs`(generic/diff)和 `dsh-tool-bash`(terminal)是参考实现。 ## 每个工具必须的测试 -覆盖参数拒绝、每种规范值和 Native 渲染形态、输出 schema 拒绝以及 HMR dispose。对于有副作用的工具,使用脚本化的 `MockAdapter` 驱动真实工具通过 agent loop(智能体循环),并断言其 `tool/call` 和投影后的 `tool/result` 会话事件;同时证明规范值本身未被持久化。对于编辑器卡片,断言 `presentCall` 和 `presentResult` 的精确视图,并通过真实桥接层添加一个 [ACP 快照](../../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md);终端卡片的场景设置 `terminalOutput: true` 以覆盖 capable-client 路径。 +覆盖参数拒绝、每种规范值和 Native 渲染形态、输出 schema 拒绝以及 HMR dispose。对于有副作用的工具,使用脚本化的 `MockAdapter` 驱动真实工具通过 agent loop(智能体循环),并断言其 `tool/call` 和投影后的 `tool/result` 会话事件;同时证明规范值本身未被持久化。对于 UI 卡片,断言 `presentCall` 和 `presentResult` 的精确视图,并实际运行所属 TUI 或 host/client 投影。如果工具改变了已交付的模型或 UI 行为,请添加组装应用快照。 diff --git a/docs/cookbook/extension-cookbook.i18n.yaml b/docs/cookbook/extension-cookbook.i18n.yaml index 03d868a264..a7e63abdeb 100644 --- a/docs/cookbook/extension-cookbook.i18n.yaml +++ b/docs/cookbook/extension-cookbook.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 -extension-cookbook.md: c13b46e06a3b34512cd371e6a4868a6e932a575f -extension-cookbook.zh.md: aeb5f905278c07344c68d80da05dc5daf299b4f6 +extension-cookbook.md: 0ab337377518f832c0649bc80cf2941751cb934f +extension-cookbook.zh.md: f7c2572d0b91867589636249f29896848f8aec82 diff --git a/docs/cookbook/extension-cookbook.md b/docs/cookbook/extension-cookbook.md index c13b46e06a..0ab3373775 100644 --- a/docs/cookbook/extension-cookbook.md +++ b/docs/cookbook/extension-cookbook.md @@ -58,11 +58,11 @@ export function apply(ctx: Context) { } ``` -## A client-driver plugin (external protocol bridge) +## An external protocol driver -A *client driver* is a UI plugin for a wire-protocol peer. It owns stdio, so stdout logging must be disabled, creates or resumes agents through the factory, maps harness events to protocol messages, and maps requests to `followup()` or `cancel()`. Settle each request exactly once from durable `turn/end`, even if rendering fails, and tear agents down with `AgentHandle.dispose()` so disposal reaches quiescence. +A *protocol driver* adapts a wire peer to `ctx.agents`; it may serve a UI or an automation client. A stdio driver owns stdout, creates or resumes agents through the factory, maps the protocol's requests to `followup()` or `cancel()`, and settles each request exactly once from durable `turn/end`. Tear agents down with `AgentHandle.dispose()` so disposal reaches quiescence. -`packages/ui/acp` is the worked example: it bridges the agent to the Agent Client Protocol (JSON-RPC over stdio) so Zed and other ACP editors can drive it. See its README for the full method surface and the permission-prompt answerer it registers on the approval seam. +[`packages/acp/acp`](../../packages/acp/acp) is the automation-only worked example: it exposes fresh text sessions over Agent Client Protocol JSON-RPC stdio, emits committed assistant text, and registers a one-shot machine permission answerer for agents it owns. Its [README](../../packages/acp/acp/README.md) owns the exact method and lifecycle contract. ```ts import type { Context } from 'cordis' diff --git a/docs/cookbook/extension-cookbook.zh.md b/docs/cookbook/extension-cookbook.zh.md index aeb5f90527..f7c2572d0b 100644 --- a/docs/cookbook/extension-cookbook.zh.md +++ b/docs/cookbook/extension-cookbook.zh.md @@ -58,11 +58,11 @@ export function apply(ctx: Context) { } ``` -## 客户端驱动插件(外部协议桥接) +## 外部协议驱动 -*客户端驱动*是面向协议格式(wire format)对端的 UI 插件。它拥有 stdio,因此必须禁用 stdout 日志;通过工厂创建或恢复 agent(智能体);将 harness 事件映射为协议消息;将请求映射为 `followup()` 或 `cancel()`。每个请求从持久的 `turn/end` 恰好结算一次(即使渲染失败),并通过 `AgentHandle.dispose()` 拆除 agent 以使 dispose(资源释放)达到静止状态。 +*协议驱动*将协议对端接入 `ctx.agents`;它可以服务于 UI 或自动化客户端。stdio 驱动拥有 stdout,通过工厂创建或恢复 agent(智能体),将协议请求映射为 `followup()` 或 `cancel()`,并根据持久的 `turn/end` 对每个请求恰好结算一次。通过 `AgentHandle.dispose()` 拆除 agent,以使 dispose(资源释放)达到完全停稳。 -`packages/ui/acp` 是完整的工作示例:它将 agent 桥接到 ACP(Agent Client Protocol)(基于 stdio 的 JSON-RPC),使 Zed 及其他 ACP 编辑器能够驱动它。其 README 描述了完整的方法接口以及它在审批 seam 上注册的权限提示应答器。 +[`packages/acp/acp`](../../packages/acp/acp) 是仅面向自动化的完整示例:它通过 ACP(Agent Client Protocol)JSON-RPC stdio 提供全新文本会话,发出已提交的助手文本,并为其拥有的 agent 注册一次性机器权限应答器。其 [README](../../packages/acp/acp/README.md) 拥有精确的方法和生命周期契约。 ```ts import type { Context } from 'cordis' diff --git a/docs/cordis-catalog/events.md b/docs/cordis-catalog/events.md index ed9bebdc92..1948c17f97 100644 --- a/docs/cordis-catalog/events.md +++ b/docs/cordis-catalog/events.md @@ -489,6 +489,26 @@ A command was registered or unregistered. This is an unfiltered registry notific Source: [`packages/ui/commands/src/index.ts:103`](../../packages/ui/commands/src/index.ts) +## `domain/*` + +### `domain/changed` — emit + +A domain record or the global singleton changed, emitted once per write strictly after the backend acknowledged durability. Events of one domain arrive in its write-chain order. + +```ts cordis-catalog +/** + * A domain record or the global singleton changed, emitted once per write + * strictly after the backend acknowledged durability. Events of one + * domain arrive in its write-chain order. + * @param change - domain, table (`''` for global), key (`''` for global), + * operation discriminant, and on `put` the new snapshot. + * @mode emit + */ +'domain/changed'(change: DomainChanged): void +``` + +Source: [`packages/storage/storage-domain/src/events.ts:46`](../../packages/storage/storage-domain/src/events.ts) + ## `fs/*` ### `fs/edit-intent` — waterfall diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 3657d5e05c..534cacf39b 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -319,6 +319,50 @@ Types: [DshEnvironment](../core-data-structures/bash.md) · [ToolExecution](../c Source: [`packages/bash/tool-bash/src/index.ts:104`](../../packages/bash/tool-bash/src/index.ts) +## `ctx.clientModuleHost` — `ClientModuleHostService` + +The web plugin table service: incremental dshClient scan + wire composition + bundle route + index tap. Construction runs the activation scan synchronously — a malformed declaration or missing bundle among the already-loaded entries aggregates into one loud throw (FAILED fiber; the boot sweep reports it). + +```ts cordis-catalog +/** + * Current composed entry graph (stable object between changes). + * @returns the graph served as `window.__DSH_BOOT__`. + */ +graph(): WebBootGraph + +/** + * Absolute path of an entry's client bundle. + * @param id - entry id (package name). + * @returns the path, or undefined for an unknown id. + */ +clientPath(id: string): string | undefined + +/** + * Re-hash one bundle (the HMR watch's registration hook — the only entry + * point through which bundle content changes reach the graph). + * @param id - entry id (package name). + * @returns the new rev, or undefined for an unknown id. + */ +rebuilt(id: string): string | undefined + +/** + * Subscribe to bundle rebuilds; fires only when the re-hash changed the rev. + * @param listener - receives the entry id and its new bundle rev. + * @returns the unsubscriber. + */ +onRebuilt(listener: (id: string, rev: string) => void): () => void + +/** + * Fires after any flush that recomposed the graph (row added/removed, or a + * rebuilt rev change). Pull model: listeners re-read {@link graph}. + * @param listener - notified with no payload. + * @returns the unsubscriber. + */ +onGraphChanged(listener: () => void): () => void +``` + +Source: [`packages/client/modules/src/index.ts:143`](../../packages/client/modules/src/index.ts) + ## `ctx.codeRuntime` — `CodeRuntime` (abstract seam) Registers one `ctx.codeRuntime` implementation. Program, budget, abort, and substrate failures resolve in CodeRunResult; only seam misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate runs from one another, and terminate and await in-flight runs during disposal. @@ -614,6 +658,30 @@ Types: [Agent](../core-data-structures/core.md) · [CreateGoalRequest](../core-d Source: [`packages/goal/goal/src/index.ts:135`](../../packages/goal/goal/src/index.ts) +## `ctx.httpServer` — `HttpServerService` + +The web-shape HTTP carrier service. Activation listens immediately (route registration order carries no request-facing semantics: named routes are composed to be disjoint, and the static dist fallback answers anything not yet claimed during the boot window). A listen failure throws out of init — a FAILED fiber the boot's fail-loud sweep reports. + +```ts cordis-catalog +/** + * Register a named route. Duplicate (kind, path) throws — route patterns are + * a composition-level contract, so a collision is a misconfiguration. + * @param route - kind, path, and the owning handler. + * @returns the disposer removing the route. + */ +register(route: WebRoute): () => void + +/** + * Register an index.html transform, applied to every index response in + * registration order. + * @param transform - pure html-to-html function. + * @returns the disposer removing the transform. + */ +tapIndex(transform: (html: string) => string): () => void +``` + +Source: [`packages/host/webserver/src/index.ts:55`](../../packages/host/webserver/src/index.ts) + ## `ctx.invariants` — `InvariantService` Package-owned invariant registry with global and regex-based selection. @@ -1274,7 +1342,7 @@ fork(source: SessionForkSource, boundary?: number, childSessionId?: SessionId): Types: [CreateSessionOptions](../core-data-structures/persistence.md) · [OutOfBandSessionEventType](../core-data-structures/session.md) · [Session](../core-data-structures/session.md) · [SessionEvent](../core-data-structures/core.md) · [SessionEventMap](../core-data-structures/session.md) · [SessionId](../core-data-structures/core.md) · [TurnTrigger](../core-data-structures/session.md) -Source: [`packages/core/session/src/index.ts:604`](../../packages/core/session/src/index.ts) +Source: [`packages/core/session/src/index.ts:606`](../../packages/core/session/src/index.ts) ## `ctx.sessionTitle` — `SessionTitleService` @@ -1381,6 +1449,30 @@ Types: [SaveTextSpill](../core-data-structures/spill.md) · [SpillRef](../core-d Source: [`packages/spill/spill/src/index.ts:45`](../../packages/spill/spill/src/index.ts) +## `ctx.storage` — `Storage` + +The storage hub service. Backends register under `backend`; data forms mount under their `StorageForms` key and are reached as `ctx.storage.<form>`. + +```ts cordis-catalog +/** + * Mount a data-form facility on the hub. Mounting is an effect: the + * returned disposer unmounts the form. + * @param form - Form key declared in {@link StorageForms}. + * @param facility - The facility instance to expose. + * @returns the disposer that unmounts the form. + */ +mount<K extends keyof StorageForms>(form: K, facility: StorageForms[K]): () => void + +/** + * Resolve a mounted data form. + * @param form - Form key declared in {@link StorageForms}. + * @returns the mounted facility. + */ +form<K extends keyof StorageForms>(form: K): StorageForms[K] +``` + +Source: [`packages/storage/storage/src/index.ts:35`](../../packages/storage/storage/src/index.ts) + ## `ctx.subagents` — `SubagentService` Named provider registry and capability-checked start surface. @@ -1841,6 +1933,52 @@ Types: [WorkflowRun](../core-data-structures/workflow.md) · [WorkflowStartReque Source: [`packages/workflow/workflow/src/index.ts:159`](../../packages/workflow/workflow/src/index.ts) +## `ctx.workspace` — `WorkspaceRegistry` + +The workspace registry service. Opens the `workspace` domain at startup, rebuilds one entity per stored record, and serves entities from an in-memory cache keyed by id. Session persistence is an OPTIONAL peer (resolved via `ctx.get`, never injected): while it is absent, session attachment rejects (what cannot be validated is not recorded) and `sessionIds` projections serve the account unfiltered. + +There is deliberately no delete entry point in this phase: workspace deletion ships as one complete semantic together with the session-cascade primitives (future work in the owning Agent Note). + +```ts cordis-catalog +/** + * Create a workspace over an existing directory. The path is canonicalized + * through `fs.realpath` first — a nonexistent path rejects with the + * original `ENOENT`, a path resolving to anything but a directory rejects, + * and a canonical path already owned by another workspace (including a + * symlink resolving to it) rejects. + * @param path - Directory the workspace points at; canonicalized before storing. + * @param title - Display title; defaults to `basename` of the canonical path. + * @returns the created workspace after durability. + */ +async create(path: string, title?: string): Promise<Workspace> + +/** + * Look up a workspace by id. + * @param id - The workspace id. + * @returns the workspace, or `undefined` when unknown. + */ +get(id: WorkspaceId): Workspace | undefined + +/** + * Snapshot of all workspaces, in load-then-creation order. + * @returns a fresh array of the cached entities. + */ +list(): Workspace[] + +/** + * Resolve a workspace by directory path, through the same `fs.realpath` + * canon as {@link create} (hence async). A path that does not exist rejects + * with the original error — a missing directory has no canonical form to + * compare (a workspace whose recorded directory vanished is only reachable + * by id; see `Workspace.status`). + * @param path - Directory path in any spelling (symlinks, `..`, trailing slash). + * @returns the owning workspace, or `undefined` when none matches. + */ +async resolveByPath(path: string): Promise<Workspace | undefined> +``` + +Source: [`packages/workspace/workspace/src/index.ts:60`](../../packages/workspace/workspace/src/index.ts) + ## Inherited `ctx` members (cordis core + loader/hmr/timer) The framework `ctx` surface every plugin also sees, beyond the harness services above. This is pinned vendor source ([vendoring policy](../../vendor/README.md)); it is summarized here so the page is a complete picture of what `ctx` offers, without elevating framework internals to the harness tier's prominence. diff --git a/docs/cordis-primer.i18n.yaml b/docs/cordis-primer.i18n.yaml new file mode 100644 index 0000000000..ef52bf6812 --- /dev/null +++ b/docs/cordis-primer.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +cordis-primer.md: ee65e6e702ecaeb506ce7334032c38e09c936cda +cordis-primer.zh.md: ee4f6864ba7864fc95b5eb8e31acbcaea6e99825 diff --git a/docs/cordis-primer.md b/docs/cordis-primer.md index 64230564b7..ee65e6e702 100644 --- a/docs/cordis-primer.md +++ b/docs/cordis-primer.md @@ -1,5 +1,7 @@ # Cordis Primer +English | [中文](cordis-primer.zh.md) + Cordis is the vendored plugin framework underneath the DeepSeek Harness SDK. This primer teaches the Cordis ideas a harness plugin author needs before reading the generated [events](cordis-catalog/events.md) and [services](cordis-catalog/services.md) catalogs; the [Cordis tutorial](cordis-tutorial/index.md) walks the same ideas hands-on. The vendored source and sync procedure live in [vendor/README.md](../vendor/README.md). ## Cordis In Five Ideas diff --git a/docs/cordis-primer.zh.md b/docs/cordis-primer.zh.md new file mode 100644 index 0000000000..ee4f6864ba --- /dev/null +++ b/docs/cordis-primer.zh.md @@ -0,0 +1,48 @@ +# Cordis 入门 + +[English](cordis-primer.md) | 中文 + +Cordis 是 DeepSeek Harness SDK 底层以 vendor 方式引入的插件框架。本文介绍 harness 插件作者在阅读生成的[事件](cordis-catalog/events.md)与[服务](cordis-catalog/services.md)目录之前需要了解的 Cordis 核心概念;[Cordis 教程](cordis-tutorial/index.md)则通过实践逐一讲解这些概念。vendor 源码与同步流程见 [vendor/README.md](../vendor/README.md)。 + +## 五个核心概念 + +- **插件是实现 Service 的对象。** 它可以是一个带有可选 `inject` 和 `apply(ctx)` 字段的函数,也可以是一个 `Service` 子类,其生命周期由 Cordis 挂载到当前上下文中。 +- **上下文是服务的容器。** 一个服务占据一个稳定的 `ctx.<key>`(如 `ctx.tools`、`ctx.llm`、`ctx.sessions`);其他插件通过 key 查找服务,而非导入具体实现。 +- **通过 `inject` 声明服务依赖。** 插件声明所需的服务后,会等待这些服务就绪才启动;加载顺序通过服务依赖表达,而非手动编排启动序列。 +- **类型化事件用于通信。** 服务通过 TypeScript 声明合并注册事件名,然后以 `emit`、`waterfall`(瀑布式事件)、`parallel` 或 `serial` 方式分发,分别对应监听者观察、包装、并行扇出或按序执行。 +- **注册是可逆的副作用。** 提示词片段、工具 schema、适配器、提供方和监听器通过 `ctx.effect()` 或 `ctx.on()` 安装,reload 和 teardown 时可预期地回卷。 + +## 分发模式 + +每个事件具有以下分发模式之一,且只能通过对应方法分发。 + +| 模式 | 是否 await? | 分发顺序 | 是否有返回值? | +|---|---|---|---| +| `emit` | 否 | 监听器按注册顺序观察 | 否 | +| `waterfall` | 否 | 监听器按注册顺序观察 | 是 | +| `parallel` | 是 | 所有监听器并行观察事件 | 否 | +| `serial` | 是 | 监听器按注册顺序观察 | 是 | + +分发模式是事件公开契约的一部分。新的 harness 事件通过 `@mode` 标签记录模式,以便生成的目录可以将声明与分发调用点做交叉校验。 + +<a id="cordis-waterfall-semantics"></a> + +## Cordis Waterfall 语义 + +`ctx.waterfall` 是环绕中间件。监听器接收 `(...args, next)`。调用 `next()` 会执行下游监听器;下游返回值通过 `next()` 返回当前包装层,可由该层包装后继续向外返回。不调用 `next()` 直接返回则短路。 + +协作式监听器通常修改一个共享的请求或决策对象,然后委托。监听器也可以选择完全替换结果,下游监听器将只看到替换后的结果。仅当监听器必须在普通注册之前运行时才使用 `prepend: true`。 + +对于单决策事件,短路是设计意图。策略监听器在拥有决策权时可以不调用 `next()` 直接返回,而仅做标注或观察的监听器则必须委托。 + +<a id="loader-configuration"></a> + +## Loader 配置 + +`@cordisjs/plugin-include` 将 `!!js` 解析为表达式节点,但 Loader 仅在挂载插件前对条目的 `config` 做插值。条目元数据(`id`、`name`、`group`、`disabled`、`inject`、`intercept` 和 `isolate`)保持字面值;因此 `disabled: !!js ...` 是一个 truthy 对象,会始终禁用该条目。需要根据环境选择挂载哪些插件时,请使用显式的配置覆盖层。 + +## 实践规则 + +将行为封装为插件:工具流水线事件属于 `ctx.tools`,模型流式输出属于 `ctx.llm`,实时 agent(智能体)协调属于 `ctx.agents`。拦截和策略优先使用事件;直接能力调用优先使用服务方法。 + +每个注册都应有对应的 disposer(dispose(资源释放)函数):要么从 `ctx.effect()` 返回一个,要么使用 Cordis 提供的辅助方法自动处理。如果 teardown 顺序有要求,请将相关工作放在同一个 effect 中,以确保资源释放按预期顺序回卷。 diff --git a/docs/core-data-structures/approval.i18n.yaml b/docs/core-data-structures/approval.i18n.yaml new file mode 100644 index 0000000000..7bcc6e692d --- /dev/null +++ b/docs/core-data-structures/approval.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 0de13eb1504b5ecc4ac0eafefefa2c87562c89b4 +approval.zh.md: b7ba10449fccfdb0dd5b52374e14038e3ec76ff8 diff --git a/docs/core-data-structures/approval.md b/docs/core-data-structures/approval.md index 8634415a62..0de13eb150 100644 --- a/docs/core-data-structures/approval.md +++ b/docs/core-data-structures/approval.md @@ -1,6 +1,8 @@ # User Approval -The user-approval seam of [dsh-user-approval](../../packages/ui/user-approval) answers one question: may this specific action proceed? It owns the shared request/outcome vocabulary, the `ctx.approval` dispatch service, the `approval/request` answerer waterfall, the log-only audit pair, and the per-session `ask`/`never` policy. UI channels such as [dsh-acp](../../packages/ui/acp) provide answerers; callers such as [dsh-tools](../../packages/core/tools) and [dsh-tool-bash](../../packages/bash/tool-bash) consume the closed outcome and fail closed unless it is `allowed-once`. +English | [中文](approval.zh.md) + +The user-approval seam of [dsh-user-approval](../../packages/ui/user-approval) answers one question: may this specific action proceed? It owns the shared request/outcome vocabulary, the `ctx.approval` dispatch service, the `approval/request` answerer waterfall, the log-only audit pair, and the per-session `ask`/`never` policy. UI channels may provide human answerers; the [ACP automation bridge](../../packages/acp/acp) provides one-shot machine decisions for its own agents. Callers such as [dsh-tools](../../packages/core/tools) and [dsh-tool-bash](../../packages/bash/tool-bash) consume the closed outcome and fail closed unless it is `allowed-once`. Source: [`packages/ui/user-approval/src/index.ts`](../../packages/ui/user-approval/src/index.ts) @@ -46,7 +48,7 @@ type ApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable' type ApprovalPolicy = 'ask' | 'never' ``` -The prompt section states the deterministic `never` behavior and records either policy with a source-owned marker. The pre-step narrator reads that marker from the logged request header after restart; it does not infer state from deployment persona prose. An idle ACP switch is held in the bridge until the next `turn/start`, because approval audit and policy events must remain turn-enclosed for durable replay. +The prompt section states the deterministic `never` behavior and records either policy with a source-owned marker. The pre-step narrator reads that marker from the logged request header after restart; it does not infer state from deployment persona prose. ## Approval request diff --git a/docs/core-data-structures/approval.zh.md b/docs/core-data-structures/approval.zh.md new file mode 100644 index 0000000000..b7ba10449f --- /dev/null +++ b/docs/core-data-structures/approval.zh.md @@ -0,0 +1,90 @@ +# 用户审批 + +[English](approval.md) | 中文 + +[dsh-user-approval](../../packages/ui/user-approval) 的用户审批 seam 回答一个问题:这个具体操作是否可以继续?它拥有共享的请求/结果词汇、`ctx.approval` 分发服务、`approval/request` 应答者 waterfall(瀑布式事件)、仅记录日志的审计事件对,以及按会话的 `ask`/`never` 策略。UI 通道可以提供人类应答者;[ACP(Agent Client Protocol)自动化桥接层](../../packages/acp/acp)为其拥有的 agent 提供一次性机器决策。调用方如 [dsh-tools](../../packages/core/tools) 和 [dsh-tool-bash](../../packages/bash/tool-bash) 消费闭合的结果,除非结果为 `allowed-once`,否则一律拒绝。 + +源码:[`packages/ui/user-approval/src/index.ts`](../../packages/ui/user-approval/src/index.ts) + +## 标识与结果 + +每个请求都会获得一个全新的 `ApprovalRequestId`。该品牌类型将 `approval/asked` 与 `approval/decided` 审计事件配对,同时不会让审批 id 与工具调用 id 或 agent(智能体)/会话 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' +``` + +## 按会话策略 + +`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' +``` + +提示词段落会声明 `never` 的确定性行为,并以服务自有的标记记录当前策略。重启后,步骤前叙述器从已记录的请求头中读取该标记,而非从部署 persona 行文中推断状态。 + +## 审批请求 + +`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 + * UI answerer only answers for agents it owns) and receives the audit + * events on its session log. + */ + readonly agent: Agent + /** The tool the question is about (presentation and audit). */ + readonly toolName: string + /** + * The exact tool call being decided, when the asker has one — lets a UI + * attach the prompt to the tool call it already streamed. + */ + readonly callId?: CallId + /** The asker's human-readable explanation of WHY it is asking. */ + readonly reason?: string + /** + * Aborting withdraws the question: the request settles `'cancelled'` + * immediately and a late answer from a still-pending answerer is discarded. + */ + readonly signal?: AbortSignal +} +``` + +## 分发与审计 + +`ctx.approval.request(req)` 要求发起请求的会话处于一个打开的轮次内。它追加 `approval/asked`,获取一个结果,追加对应的 `approval/decided`,然后以该结果 resolve。`never` 策略在服务内部、waterfall 分发之前强制执行,因此即使后来以 `prepend` 注册的应答者也无法绕过它。应答者在拥有该请求时返回结果,否则调用 `next()` 委托;第一个应答占据唯一的决策槽位。 + +审计事件仅写入日志,不进入模型 transcript(文本记录)。模型可见的行为是调用方派生的工具结果,而请求头记录的是模型实际看到的提示词策略。服务 dispose(资源释放)时会一并移除其提示词段落和步骤前叙述器;应答者监听器独立地通过 effect 绑定到其所属插件。 diff --git a/docs/core-data-structures/bash.i18n.yaml b/docs/core-data-structures/bash.i18n.yaml new file mode 100644 index 0000000000..98855cdc0c --- /dev/null +++ b/docs/core-data-structures/bash.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 35cf2061588907dde41123efb01e453eb9cc929d +bash.zh.md: 0cfeb9e1a858f7057e720215c41a757588751122 diff --git a/docs/core-data-structures/bash.md b/docs/core-data-structures/bash.md index b639e55927..35cf206158 100644 --- a/docs/core-data-structures/bash.md +++ b/docs/core-data-structures/bash.md @@ -1,5 +1,7 @@ # Bash Executor +English | [中文](bash.zh.md) + The bash execution seam is split across interface ([dsh-bash](../../packages/bash/bash), `ctx.bash`), implementations ([dsh-bash-local](../../packages/bash/bash-local) and [dsh-bash-sandbox](../../packages/bash/bash-sandbox)), and consumer ([dsh-tool-bash](../../packages/bash/tool-bash), the `bash` schema). Generic background-task ids, ownership, and controls live in [tasks.md](tasks.md); this seam returns a task-free process handle. Source: [`packages/bash/bash/src/types.ts`](../../packages/bash/bash/src/types.ts) diff --git a/docs/core-data-structures/bash.zh.md b/docs/core-data-structures/bash.zh.md new file mode 100644 index 0000000000..0cfeb9e1a8 --- /dev/null +++ b/docs/core-data-structures/bash.zh.md @@ -0,0 +1,241 @@ +# Bash 执行器 + +[English](bash.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) + +## 受管 shell 环境命名空间 + +`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<Record<DshEnvironmentKey, string>> +``` + +## 请求与规格:`resolve()` 拆分 + +该 seam 将**面向模型/插件的请求**(`workdir`/`timeoutMs`/`stdoutMaxBytes` 可选,由配置或请求策略补全)与执行器实际使用的**完全解析后的 spec**(这些字段均为必填)分开。工具层在二者之间调用 `ctx.bash.resolve(request)`——这具体落实了仓库的「包(package) 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 + /** + * Bytes to write to the command's stdin, then close it. Absent leaves stdin + * closed/empty (the default for model-driven tool calls). Set by in-process + * plugins (e.g. the hooks bridges, which write a hook command's JSON payload + * to its stdin); the model-facing bash tool does not expose it as a parameter + * (a model that needs stdin uses shell syntax like a heredoc or a pipe). + */ + stdin?: string | undefined + /** + * 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<string, string> | undefined + /** + * 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. + */ + 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 stdin before closing it; absent means no stdin. */ + stdin?: string | undefined + /** + * 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<string, string> | undefined + /** Managed `DSH_*` snapshot; implementations reject ordinary names. */ + dshEnv?: DshEnvironment | undefined + /** Resolved sandbox policy; ignored by executors that do not confine. */ + sandboxPolicy: SandboxExecutionPolicy | 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)。 + +`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 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` 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 execution facts, absent for an unsandboxed executor. */ + sandbox?: BashSandboxInfo +} +``` + +每个流是一个 `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 + /** True when bytes were dropped from `text`. */ + truncated: boolean + /** Path to a file holding the COMPLETE stream, when truncated and available. */ + spillPath?: string +} +``` + +## 文件沙箱:`BashSandboxInfo` + +使用沙箱的执行器通过 `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) 所有;模式仅管辖文件效果。 + +沙箱化运行会报告其模式、保守的拒绝分类与强制执行完整度。`runnerFailed` 标记命令运行前沙箱 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 + /** Whether the sandbox denied a file operation. */ + denied: boolean + /** How completely the selected runner enforced the requested mode. */ + enforcement?: SandboxEnforcement + /** Whether the sandbox runner failed before the command could run. */ + runnerFailed?: boolean +} +``` + +最后一项补全了这套词汇:当受限模式没有可用后端时,`ctx.sandbox` 提供方会抛出、执行器会传播由[沙箱 seam](sandbox.md)所有的 `SANDBOX_UNAVAILABLE` 错误码。选定的 runner 拒绝其 profile 时会触达同一个故障关闭的前台错误;已结束的后台任务则记录 `runnerFailed`。模型会在结果中收到拒绝/runner 事实,仅当拒绝标记指出生效模式时才得知该模式,并可通过 `sandbox_permissions` 加 `justification` 请求一次性、严格更宽松的重试;执行任何操作前,`ctx.approval` 必须批准该次确切调用。完整的策略与切换设计见[沙箱 Agent Note](../../.agents/notes/implemented/feature/2026-07-06-sandbox.md)。 + +## 后台进程:`BashProcess` + +`start()` 返回不含 id 或所有者的句柄。`dsh-tool-bash` 将它适配为 `ctx.tasks.start()` 钩子;随后由通用运行时拥有任务标识与生命周期。`done` 在进程关闭时 resolve 且绝不 reject;进程结束后仍可读取,并且沙箱事实会在 `done` resolve 前写入。 + +```ts type-equiv +/** + * 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 — a spawn failure settles as `killed` with the error on stderr). */ + readonly done: Promise<void> + /** 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()` 返回增量 delta 与 spill 恢复事实: + +```ts type-equiv +/** 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. */ + lossy: boolean + /** Full stdout spill file, when stdout truncation occurred and a safe path is available. */ + stdoutSpillPath?: string + /** Full stderr spill file, when stderr truncation occurred and a safe path is available. */ + stderrSpillPath?: string +} +``` + +## 服务 + +`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 new file mode 100644 index 0000000000..218ef4eea9 --- /dev/null +++ b/docs/core-data-structures/code-runtime.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 64de3c45d4f1d1d981daa6c6f074abb667e0aa52 +code-runtime.zh.md: 4b14aeb2183010e8140540258ce8109df9f59910 diff --git a/docs/core-data-structures/code-runtime.md b/docs/core-data-structures/code-runtime.md index 41009f065e..64de3c45d4 100644 --- a/docs/core-data-structures/code-runtime.md +++ b/docs/core-data-structures/code-runtime.md @@ -1,5 +1,7 @@ # Code Runtime +English | [中文](code-runtime.zh.md) + The code-execution seam — a [capability seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md) whose interface ([dsh-code-runtime](../../packages/code-runtime/code-runtime), `ctx.codeRuntime`) runs one model-written program against host-provided async bindings and reports what it printed and returned. Code execution is **one optional capability**, not part of the agent-loop spine — so its vocabulary lives here, not in [core.md](core.md). Backends differ by execution substrate and source language, both readonly descriptors on the service; the worker-thread backend and tool-registry consumer are specified by the [Code Mode foundation](../../.agents/notes/implemented/feature/2026-06-15-code-mode.md) and [typed-return contract](../../.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.md). Source: [`packages/code-runtime/code-runtime/src/types.ts`](../../packages/code-runtime/code-runtime/src/types.ts) diff --git a/docs/core-data-structures/code-runtime.zh.md b/docs/core-data-structures/code-runtime.zh.md new file mode 100644 index 0000000000..4b14aeb218 --- /dev/null +++ b/docs/core-data-structures/code-runtime.zh.md @@ -0,0 +1,147 @@ +# 代码运行时 + +[English](code-runtime.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 基础设计](../../.agents/notes/implemented/feature/2026-06-15-code-mode.md)和[类型化返回契约](../../.agents/notes/implemented/feature/2026-07-20-code-mode-typed-tool-returns.md)。 + +源码:[`packages/code-runtime/code-runtime/src/types.ts`](../../packages/code-runtime/code-runtime/src/types.ts) + +## 运行:请求进,结果出 + +`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 + * runs as the body of an async function: top-level `await` and `return` + * are available, and the completion value becomes + * {@link CodeRunResult.value}. + */ + program: string + /** Host functions exposed to the program, one global object per namespace. */ + bindings: CodeBindingNamespace[] + /** + * Abort the run: the runtime stops the program (hard, even mid-loop) and + * resolves with a {@link CodeRunFailure} of kind `'abort'`. In-flight + * binding calls are the CALLER's to settle — the runtime only stops asking. + */ + signal?: AbortSignal +} +``` + +结果将错误报告为一个**字段**,而非 `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 + * completion and the value crossed the runtime's lossless-JSON boundary. + * Invalid or over-limit completions fail the run instead of substituting a + * rendered string; a failed or value-less run leaves this absent. + */ + value?: CodeJsonValue + /** Text the program emitted, in order, bounded only as part of the outer result. */ + logs: string[] + /** Present iff the run failed; see {@link CodeRunFailure} for the taxonomy. */ + error?: CodeRunFailure +} +``` + +## 绑定:宿主函数作为程序全局变量 + +每个 `CodeBindingNamespace` 在程序内成为一个由异步可调用函数组成的全局对象(Code Mode 消费方传入一个:`tools`)。参数与返回值必须是无损 JSON,且跨越边界时不受 seam 层字节上限约束;运行时可以通过结构化克隆桥接它们。命名空间可以声明程序可见的错误类,而无需让运行时知道消费方的名称:运行时会注入真实构造函数,并将被拒绝的调用转为该类的实例。运行时也将绑定名视为不可信输入(`__proto__` 是普通自有属性,绝不会发生原型碰撞): + +```ts type-equiv +/** + * Program-visible typed rejection for one binding namespace. The runtime + * injects a real error constructor under `name`; rejected member calls become + * its instances and expose the exact member name through + * `memberNameProperty`. Both strings are runtime data rather than knowledge + * of a particular consumer such as Code Mode. + */ +interface CodeBindingErrorClass { + /** Constructor global and resulting `Error.name` (must be a usable JS identifier). */ + name: string + /** Non-empty own property for the member name; cannot replace `name`, `message`, or `stack`. */ + memberNameProperty: string +} +``` + +```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 + /** The callable members, keyed by the exact name the program calls. */ + functions: Record<string, CodeBindingFunction> + /** Optional program-visible typed rejection contract for this namespace. */ + errorClass?: CodeBindingErrorClass +} +``` + +```ts type-equiv +/** A lossless JSON value transferable across the dependency-light code-runtime seam. */ +type CodeJsonValue = null | boolean | number | string | CodeJsonValue[] | { [key: string]: CodeJsonValue } +``` + +```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 lossless JSON. A runtime rejects a + * lossy or non-cloneable value with a descriptive error rather than corrupting + * the run. No seam-level byte cap applies to a binding resolution. A rejection + * of this function surfaces inside the program as a rejection of the + * corresponding call. + */ +type CodeBindingFunction = (args: unknown) => Promise<CodeJsonValue> +``` + +## 捕获的输出与失败分类体系 + +日志是按发出顺序排列的纯字符串。运行时捕获程序的 console 与流输出,但通道和 console 方法的元数据不属于 seam,因为消费方只渲染文本。实现会对序列化后的外层日志数组,以及完成值或失败消息的组合载荷设置上限;固定的结果封装语法与消费方展示空白不计入这份可变载荷计量。超限会显式失败,而不会在值中插入替代内容。 + +失败类型是**正交的结果,独立报告**(见 [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). + * - `'invalid-output'` — the completion value was not lossless JSON. + * - `'output-limit'` — the serialized outer logs/value/diagnostic exceeded the configured cap. + */ +interface CodeRunFailure { + /** The failure class (see the interface doc for each kind's meaning). */ + kind: 'exception' | 'timeout' | 'abort' | 'worker-exit' | 'invalid-output' | 'output-limit' + /** Human-readable detail, suitable for feeding back to a model to self-correct. */ + message: string +} +``` + +## 服务 + +`CodeRuntime`(`ctx.codeRuntime`,抽象服务,定义于 [`packages/code-runtime/code-runtime/src/index.ts`](../../packages/code-runtime/code-runtime/src/index.ts))由 `run(request)` 加两个只读描述符组成:`language`(程序必须使用的语言,`'typescript'` 是已知值;生成语言相关展示的消费方据此切换,遇到无法展示的语言时应显式报错)和 `isolation`(执行基底,`'worker-thread'`、`'process'`、`'container'`;仅为诊断标签,**不构成安全承诺**)。实现必须保证各次运行彼此隔离(无跨运行状态),并在 dispose(资源释放)时等待系统完全停稳:teardown 完成前,进行中的运行都已终止并等待结束。 diff --git a/docs/core-data-structures/commands.md b/docs/core-data-structures/commands.md index c33b27ce1c..c36942cf18 100644 --- a/docs/core-data-structures/commands.md +++ b/docs/core-data-structures/commands.md @@ -1,15 +1,15 @@ # Human Commands -The human-command seam of [`dsh-commands`](../../packages/ui/commands). TUI and ACP adapters use it to discover and directly execute plugin-owned commands for an exact agent without creating a model message. The [command Agent Note](../../.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md) owns dispatch and lifecycle rationale; the [package README](../../packages/ui/commands/README.md) owns composition and limitations. +The human-command seam of [`dsh-commands`](../../packages/ui/commands). Interactive adapters use it to discover and directly execute plugin-owned commands for an exact agent without creating a model message. The [command Agent Note](../../.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md) owns dispatch and lifecycle rationale; the [package README](../../packages/ui/commands/README.md) owns composition and limitations. Source: [`packages/ui/commands/src/index.ts`](../../packages/ui/commands/src/index.ts) ## Input metadata -ACP currently exposes one unstructured-input hint. Command availability follows plugin composition: every adapter consuming the registry sees every effective definition. +The seam exposes one optional unstructured-input hint. Command availability follows plugin composition: every adapter consuming the registry sees every effective definition. ```ts type-equiv -/** Immutable command input metadata compatible with ACP unstructured input. */ +/** Immutable metadata for a command's optional unstructured input. */ interface CommandInputDescriptor { /** Placeholder shown before the user supplies free-form input. */ readonly hint: string diff --git a/docs/core-data-structures/compaction.i18n.yaml b/docs/core-data-structures/compaction.i18n.yaml new file mode 100644 index 0000000000..3f192f0194 --- /dev/null +++ b/docs/core-data-structures/compaction.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 71bbe7d9c17c6a3d35684a6c87d3072ab4f88df1 +compaction.zh.md: 35e9c9ef0050f01c5249d1502bb2782511acc819 diff --git a/docs/core-data-structures/compaction.md b/docs/core-data-structures/compaction.md index 6fa281a96c..71bbe7d9c1 100644 --- a/docs/core-data-structures/compaction.md +++ b/docs/core-data-structures/compaction.md @@ -1,5 +1,7 @@ # Compaction +English | [中文](compaction.zh.md) + The compaction seam — a [capability seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md) split like bash: interface ([dsh-compact](../../packages/compact/compact), `ctx.compact`), implementation (a backend such as [dsh-compact-basic](../../packages/compact/compact-basic)), and consumer (a `/compact` tool, deferred). Compaction is **one optional capability**, not part of the agent-loop spine — so its vocabulary lives here, not in [core.md](core.md). A tokenizer- or template-based backend is a sibling package implementing the same interface. Unlike bash, the interface necessarily depends on `dsh-session` and `dsh-llm`: its verbs act on an agent-owned `Session`, and its durable summary event uses the `ContentBlock` vocabulary (see the [compaction capability-seam Agent Note](../../.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md)). Source: [`packages/compact/compact/src/types.ts`](../../packages/compact/compact/src/types.ts) diff --git a/docs/core-data-structures/compaction.zh.md b/docs/core-data-structures/compaction.zh.md new file mode 100644 index 0000000000..35e9c9ef00 --- /dev/null +++ b/docs/core-data-structures/compaction.zh.md @@ -0,0 +1,97 @@ +# 压缩(compaction) + +[English](compaction.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 或模板的后端是实现同一接口的兄弟包(package)。与 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) 扩展三种事件类型。三者都**仅写入日志**——记录压缩锁及其 provenance,绝不进入 surface。这里有意不扩展 `SurfaceEventType`(只有产生消息的事件才到达模型),因此摘要本身承载在另一条带有 `surfaceOp: { op: 'replace', start, end }` 的 `user/message` 上——这是摘要压缩执行的唯一 surface 变更。关于复用 `user/message` 为何是如实建模而非权宜之计,见对应 Agent Note。 + +| 事件 | 载荷 | 作用 | +|---|---|---| +| `compact/start` | `{ turn }` | 获取日志记录的锁 | +| `compact/summary` | `{ summary, shadowedRange, shadowedSeqs, shadowedTokenCount, provider, model, maxTokens? }` | provenance:摘要块、被遮蔽的 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`。 + +这些变体在 `declare module '@deepseek-ai/dsh-session'` 块内合并,因此——与其他子页面上的顶层类型不同——它们不以漂移检查的 ` ```ts type-equiv ` 块粘贴(`verify-type-equiv` 提取器只按名称匹配顶层声明)。上方的载荷表即为目录条目;权威形状请循源码链接查看。 + +## `CompactionResult` + +成功压缩向调用方返回:记账事件 seq、原始摘要、被遮蔽的范围与 seq,以及估算 token 数。 + +```ts type-equiv +/** Result of a successful compaction operation. */ +interface CompactionResult { + /** The seq of the appended `compact/start` event. */ + startSeq: number + /** The seq of the appended `compact/summary` event. */ + summarySeq: number + /** The seq of the appended `compact/end` event. */ + endSeq: number + /** The summary content blocks produced by the backend. */ + summary: ContentBlock[] + /** + * The surface-boundary pair that was shadowed: the seqs of the first + * (`start`) and last (`end`) surface nodes of the replaced range. A + * surface-POSITION span, not a numeric seq interval — after a prior replace + * lands a fresh high-seq summary node at an older range's position, `start` + * can be GREATER than `end`. {@link CompactionResult.shadowedSeqs} is the + * authoritative set of shadowed nodes, in surface order. + */ + shadowedRange: { start: number; end: number } + /** The seqs of all shadowed surface nodes, in surface order. */ + shadowedSeqs: number[] + /** Estimated token count of the shadowed content. */ + shadowedTokenCount: number +} +``` + +## 服务 + +自动调用方会说明策略为何运行;实现可以比普通压力更激进地处理已确认的溢出。 + +```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(...)`。每个后端都使用包导出的 `COMPACT_CHECKPOINT_SOURCE` 标记其替换用的 `user/message`;消费方调用 `isCompactCheckpointSource()`,而不是把检查点识别逻辑耦合到某一个后端。实现必须把传入的 signal 转发给摘要流程。该 seam 不拥有计价 API:单例 [`ctx.tokenMeter`](token-meter.md) 直接拥有估算与回放,而 `dsh-compact-basic` 拥有保留策略、事件排序、按路由执行的摘要调用及其配置。 + +压力压缩在串行 `agent/post-step` 中运行:此时成功的 assistant 输出、工具结果、缓冲上下文和 steering(中途引导)已持久化,但 `step/end` 尚未发生。一旦压力或规范化溢出满足条件,compact-basic 会在选择范围前调用可选的 [`ctx.toolResultPrune`](../../packages/compact/compact-tool-result-prune/README.md),再通过 `ctx.tokenMeter` 重新测量,并且可以在不生成摘要的情况下推进 surface。失败请求的恢复在失败的步骤关闭后通过 `agent/request-error` 运行;仅当 surface replacement generation 前进时才批准一个带新编号的步骤重试,即便后续摘要工作在剪枝后抛异常亦如此;取消仍然优先。区域边界保持工具调用/结果配对,但不保持整个轮次,因此一个过大轮次中较早关闭的步骤可以被压缩。`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 new file mode 100644 index 0000000000..47310dd09b --- /dev/null +++ b/docs/core-data-structures/core.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 781267cccdb5bbda33e5be6a9e807fdbe47dbc83 +core.zh.md: d0f67983b98b0cf679a8e599a5f8ab3c64490dd0 diff --git a/docs/core-data-structures/core.md b/docs/core-data-structures/core.md index b409a37284..781267cccd 100644 --- a/docs/core-data-structures/core.md +++ b/docs/core-data-structures/core.md @@ -1,5 +1,7 @@ # Core Data Structures +English | [中文](core.zh.md) + This folder catalogs the **data structures** of the DeepSeek Harness — what each core type represents, its literal shape, and where the full detail lives. It complements [architecture.md](../architecture.md), which describes *behavior* (the service map, the session/turn/step lifecycle, the event taxonomy); this page describes the *vocabulary* that behavior moves around. ## What counts as "core" @@ -163,6 +165,8 @@ Adapters emit a raw **chunk** protocol; the loop logs the chunks (replay fidelit The full union, the adapter contract (usage-before-finish, raw-JSON tool arguments, the two sanctioned error paths), and `BlockAssembler` live on **[llm-streaming.md](llm-streaming.md)**. +<a id="the-model-request-and-result"></a> + ## The model request One model call is a fully-assembled `GenerateOptions`. The adapter answers with a raw `StreamChunk` stream; the consumer assembles it with `BlockAssembler` (see [llm-streaming.md](llm-streaming.md)). @@ -560,7 +564,7 @@ interface Agent { `AgentStatus` is `'idle' | 'running' | 'disposed'`, and `SessionId` is branded. `running` describes the driver-wide drain interval, which can span turn close, its durability checkpoint, and consecutive queued turns; it does not prove a turn is still open. `AgentOptions` is merge-extensible: core declares `provider?` and `model?` (dispatch requires both after `agent/request`). Persona belongs to `dsh-system-prompt`: an agent-scoped `deployment:persona` may shadow the global default. -The cause is a TypeScript-enforced same-process input. An active holder copies its discriminant into the runtime-only `AbortSignal.reason`; it is retired before `turn/end` publication. `agentInterruptReasonOf(signal)` recognizes `user`, `parent`, and lifecycle-only `disposed` without consulting ambient initiator state. Durable `turn/end` retains the coarse `{ kind: 'aborted' }` outcome; request provenance would require a separate durable event rather than overloading the terminal result. +The cause is a TypeScript-enforced same-process input. An active `TurnCancellation` holder copies its discriminant into the runtime-only `AbortSignal.reason` and is retired before `turn/end` publication; the frozen `AbortSignal.reason` remains readable after that retirement. `agentInterruptReasonOf(signal)` recognizes `user`, `parent`, and lifecycle-only `disposed` without consulting ambient initiator state. Durable `turn/end` retains the coarse `{ kind: 'aborted' }` outcome; request provenance would require a separate durable event rather than overloading the terminal result. The [event taxonomy](../architecture.md#event) owns the `agent/*` lifecycle, checkpoint, and waterfall contracts. Turn and step boundaries are durable session events rather than agent emits. diff --git a/docs/core-data-structures/core.zh.md b/docs/core-data-structures/core.zh.md new file mode 100644 index 0000000000..d0f67983b9 --- /dev/null +++ b/docs/core-data-structures/core.zh.md @@ -0,0 +1,671 @@ +# 核心数据结构 + +[English](core.md) | 中文 + +本目录编目 DeepSeek Harness 的**数据结构**:每个核心类型代表什么、它的字面形状,以及完整细节在哪里。它与 [architecture.md](../architecture.md) 互补——后者描述*行为*(服务映射、会话/轮次/步骤生命周期、事件分类体系);本页描述行为所操作的*词汇*。 + +## 什么算"核心" + +harness 是一个微内核:一个极小的核心加上众多插件。大多数类型属于某一个插件或某一项能力。但有少数类型构成**主干**——agent loop(智能体循环)及其事件在*每一个*轮次中使用的语言,无论加载了哪些可选插件。这些就是"核心"。 + +精确地说,一个数据结构是**核心**的,当且仅当满足以下条件之一: + +1. 它流经 agent loop 主干——循环在每个轮次中持有、派生、流式输出或记录它(`Message`、`StreamChunk`、`SessionEvent`、`Agent` 句柄本身),与当前加载了哪些插件无关;**或者** +2. 它是插件作者面向某条流水线编写的代表性类型——`ToolDefinition`(每个工具*是什么*)。 + +其他一切都记录在**子页面**上,而非本页。划线的规则是:*你编写、持有或接收的类型是核心;为它提供类型推导、渲染或持久化的机制是子页面细节*。因此 `ToolDefinition` 是核心,但为它提供类型推导的 `ValueSchemaSpec`/`ParameterSchemaSpec` 机制、为它提供渲染意图的 `ToolCallView`/`ToolResultView` 词汇,以及存储事件日志的 `SessionPersistence` seam 都不是——它们分别在下列子页面中。 + +| 子页面 | 负责内容 | +|---|---| +| [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-title.md](session-title.md) | 持久标题快照、来源 provenance 与异步提供方契约 | +| [system-prompt.md](system-prompt.md) | 逐次组装的上下文、工具提供方结果、提示词段落与协作式组装 | +| [tools.md](tools.md) | `ToolDefinition` 完整字段、schema DSL、`ToolExecution`/`ToolResult`、工具展示 UI 类型,以及受保护的执行流水线 | +| [user-interaction.md](user-interaction.md) | UI 支持的人工问答 seam:`AskUserQuestionRequest`、answer/options 词汇、提供方 API、错误分类体系 | +| [approval.md](approval.md) | 一次性用户审批 seam:`ApprovalRequest`、`ApprovalOutcome`、逐会话策略、审计与 answerer 契约 | +| [bash.md](bash.md) | bash 执行器 seam:`BashExecRequest`/`Spec`、`BashRunResult`、后台 `BashProcess` 句柄 | +| [pty.md](pty.md) | 持久化终端 ID、后端/会话契约、发送就绪状态、有界读取与 owner 可见快照 | +| [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`、提供方可用性、`WebError` | +| [spill.md](spill.md) | spill 存储 seam:`SaveTextSpill`、`SpillOwner`/`SpillSource`、`SpillRef`、品牌类型 `SpillLocator` | +| [workflow.md](workflow.md) | 工作流 seam:`WorkflowStartRequest`、`WorkflowMeta`、`WorkflowRun`/`Result`、`workflow/*` 事件载荷、`WorkflowError` 致命性 | + +> 这些页面上的类型声明及其 JSDoc 与源码等价,并由 `pnpm run verify-type-equiv` 检查漂移(见 [development.md](../development.md#documenting-types-verbatim-ts-type-equiv))。普通块保留完整声明;`public-api` 块保留去除实现体的公开 class 声明。Cordis 服务使用生成的[服务目录](../cordis-catalog/services.md)。 + +<a id="the-map--derived-union-pattern"></a> + +## `…Map → derived-union` 模式 + +harness 中几乎所有可扩展的和类型都遵循同一形状:一个以判别标签为键的接口(`…Map`),联合类型由 `keyof` 派生。插件通过**声明合并**添加变体——无需修改拥有该类型的包(package)。 + +```ts ignore-check +// The pattern, schematically: +interface ThingMap { + 'a': { kind: 'a'; /* … */ } + 'b': { kind: 'b'; /* … */ } +} +type ThingKind = keyof ThingMap // 'a' | 'b' +type Thing = ThingMap[keyof ThingMap] // the discriminated union + +// A plugin extends it without touching the source package: +declare module '@deepseek-ai/dsh-llm' { + interface ThingMap { + 'c': { kind: 'c'; /* … */ } + } +} +``` + +六个规范 map 使用此模式;插件作者扩展它们: + +| Map | 包 | 派生 | 目录 | +|---|---|---|---| +| `ContentBlockMap` | dsh-llm | `ContentBlock` | [下文](#content-blocks-and-messages) | +| `MessageSourceMap` | dsh-llm | `MessageSource` | [下文](#content-blocks-and-messages) | +| `FinishReasonMap` | dsh-llm | `FinishReason` | [下文](#the-model-request-and-result) | +| `TurnTriggerMap` | dsh-session | `TurnTrigger` | [session.md](session.md) | +| `TurnEndReasonMap` | dsh-session | `TurnEndReason` | [session.md](session.md) | +| `SessionEventMap` | dsh-session | `SessionEvent` | [session.md](session.md) | + +消费方最常 `switch` 的两个大型判别联合类型是:**`StreamChunk`**(流式协议)和 **`SessionEvent`**(日志条目)。按仓库约定,对标签做 `switch`——不要链式 `if`——这样每个分支都能窄化类型,拼错的标签会编译失败。 + +<a id="branded-ids"></a> + +## 品牌化 ID + +跨越包边界的 ID 都经过**品牌化**——结构上是字符串,但在类型层面不可互换(不能把 `SessionId` 传给需要 `CallId` 的位置)。每种类型通过各自的工厂构造;比较、日志记录和 JSON 行为与普通字符串相同。 + +`Branded<B>` 原语位于独立的纯类型包 [dsh-brand](../../packages/util/brand) 中(没有运行时代码,也不依赖 Harness 包),因此任何包都能品牌化其拥有的 id,而无需依赖无关的能力包。 + +源码:[`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<B extends string> = string & { readonly [BRAND]: B } +``` + +两个核心 ID 是 `CallId`(关联工具调用及其结果;dsh-llm)和 `SessionId`(活跃 agent 与持久会话共享的标识;dsh-session)。能力包也会品牌化各自的 id,例如 [tasks.md](tasks.md) 中的 `TaskId`。 + +<a id="content-blocks-and-messages"></a> + +## 内容块与消息 + +一段对话由 `Message` 组成;一条消息是一个类型化**内容块**的数组。块的联合类型从 `ContentBlockMap` 派生。 + +源码:[`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 + 'tool-call': ToolCallBlock + 'tool-result': ToolResultBlock +} +``` + +各块接口(完整字段见源码):`TextBlock`(`text`)、`ReasoningBlock`(thinking,区别于可见文本)、`ToolCallBlock`(`id: CallId`、`name`、原始 JSON `arguments`)、`ToolResultBlock`(`toolCallId`、嵌套 `content: ContentBlock[]`、`isError?`)。`ContentBlock = ContentBlockMap[ContentBlockType]`。核心集仅限于每条交付路径都尊重的块——多模态内容(图像、音频等)没有核心块类型;需要的功能通过可合并扩展的 map 添加,同时提供适配器/UI/压缩支持。 + +`Message` 由角色和块组成。由循环派生的 assistant 消息携带其持久提供方/模型标识,以及可选的适配器私有回放元数据: + +```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 } +} +``` + +## 流式输出 + +适配器发出原始**分片**协议;循环记录分片(回放保真度),同时将同一批分片送入 `BlockAssembler` 以重建块和消息。`StreamChunk` 是基于 `type` 的封闭判别联合——`block-start`、`text-delta`、`reasoning-delta`、`tool-call-delta`、`block-end`、`usage`、`finish`。 + +完整联合类型、适配器契约(usage-before-finish、原始 JSON 工具参数、两条认可的错误路径)和 `BlockAssembler` 在 **[llm-streaming.md](llm-streaming.md)** 中。 + +<a id="the-model-request-and-result"></a> + +## 模型请求 + +一次模型调用是一个完全组装好的 `GenerateOptions`。适配器以原始 `StreamChunk` 流作答;消费方用 `BlockAssembler` 组装它(见 [llm-streaming.md](llm-streaming.md))。 + +源码:[`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 + * the `system` slot). A loop-built request assembles them as + * `EpochHeader.messagePrefix` + the derived history (dsh-agent-loop); a + * hand-built one-shot passes any list. + */ + messages: Message[] + /** System prompt text (adapters map to the provider's system slot). */ + system?: string + /** Tool schemas (adapters map to the provider's `tools` field). */ + tools?: ToolSchema[] + temperature?: number + maxTokens?: number + /** + * Stop sequences: generation halts as soon as the model produces any one of + * these strings (adapters map to the provider's stop field, e.g. OpenAI + * `stop`). The stop string itself is not included in the output. + */ + stop?: string[] + signal?: AbortSignal + /** + * Session identity stamped by the loop for listener routing. Adapters ignore + * 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 or purpose-specific + * generation policy. Ordinary conversation requests leave it unset. + */ + purpose?: 'compaction' | 'session-title' +} +``` + +模型响应为何停止由可合并扩展的原因表示。提供方终态失败携带流式契约的 [`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'; failure: LlmFailure } + 'error': { kind: 'error'; failure: LlmFailure } +} +``` + +`FinishReason = FinishReasonMap[keyof FinishReasonMap]`。`TokenUsage`(逐调用计量,含不相交的缓存字段)详见 [llm-streaming.md](llm-streaming.md)。 + +`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 + /** JSON Schema object for the arguments. */ + parameters: Record<string, unknown> +} +``` + +面向模型的 `ToolSchema` 是协议格式;产出它的已注册 `ToolDefinition`(schema + `execute`)在 [tools.md](tools.md) 中。 + +### 请求信封:`LlmCallConfig` 与记录的 header + +循环从已记录状态构建每个请求。`EpochHeader` 通过完整的 `request/header` 快照记录调用配置、渲染后的提示词、权威返回工具顺序(由 `toolOrder` 配置;未配置时按字典序)以及会话前缀。结合派生历史,请求便可由会话日志重建。见 [session.md](session.md#the-request-header-event-requestheader) 与[可重建性 Agent Note(agent 决策记录)](../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md)。 + +`agent/request` 接收冻结的调用配置种子,并可返回替代值以切换提供方、模型或采样参数。`agent/session-prefix` 为每个循环实例组合一次仅用于请求的 prefix 消息,header 记录实际使用的确切结果。到达 `llm/stream` 的请求会被深度冻结,因此变更会抛异常;请求还携带进程本地循环标识,使观察者不会把单独记录的冻结辅助调用误认成对话请求。 + +在协议格式上,循环构建的请求按此顺序读取:`system` 槽位(渲染后的提示词组装)→ `messagePrefix`(冻结的会话前缀)→ 派生历史——边界快照,其尾部在轮次首步是最新的 `user/message`,在后续步骤是上一步的工具结果。前缀从不进入派生历史;它的持久记录是 header 事件,开发不变式针对每个循环构建的请求精确重算此等式。 + +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 + stop?: string[] +} +``` + +## 会话 + +`Session` 是一份类型化 `SessionEvent` 的**仅追加日志**——唯一的真源。LLM(大语言模型)消息历史从日志*派生*(`deriveMessages()`),而非单独存储。事件词汇从 `SessionEventMap` 派生: + +源码:[`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`, `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<T extends SessionEventType = SessionEventType> = { + [K in SessionEventType]: { + type: K + /** Monotonic sequence number within the session. */ + seq: number + /** Unix epoch milliseconds. */ + time: number + data: SessionEventMap[K] + } & (K extends SurfaceEventType ? { + /** + * 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). 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. */ + surfaceOp?: SurfaceOp + } : object) +}[T] +``` + +十三种事件变体(`turn/start`、`turn/end`、`step/start`、`step/end`、`user/message`、`prompt/blocked`、`assistant/chunk`、`assistant/message`、`tool/call`、`tool/result`、`steering/message`、`todo/write`、`request/header`)、`deriveMessages()` 投影规则、`TurnTrigger`/`TurnEndReason` 原因以及轮次封闭不变量都在 **[session.md](session.md)** 中。日志如何持久化——`SessionPersistence` seam、JSONL/SQLite 后端、`session/flush` 检查点、崩溃恢复与 `SessionHeader`——则在 **[persistence.md](persistence.md)** 中。 + +<a id="the-agent-handle"></a> + +## Agent 句柄 + +`Agent` 是每个插件(UI、钩子、orchestrator)面向编程的 surface。具体实现为 dsh-agent-loop 包内部细节;循环外没有任何组件依赖它。 + +源码:[`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts) + +```ts type-equiv +/** + * Options for {@link Agent.followup}, {@link Agent.queue}, and {@link Agent.steer}. + * An omitted source attests direct human input as `{ kind: 'user' }` and may + * authorize policy consumers, so non-human producers must label their content. + */ +interface SendOptions { + source?: MessageSource + /** + * Model-facing contexts captured with this inbox item. A queued prompt exposes + * them through the default `agent/prompt-submit` allow decision, while steering + * records them directly at its next checkpoint. + */ + contexts?: HookContext[] + /** Opaque JSON state retained on the durable message but hidden from the model. */ + meta?: JsonValue +} +``` + +```ts type-equiv +/** Options specific to durable synthetic context injection. */ +interface InjectOptions { + /** Defaults to `{ kind: 'plugin', plugin: '' }`; non-human producers should identify themselves. */ + source?: MessageSource + /** Opaque JSON state retained on the durable message but hidden from the model. */ + meta?: JsonValue +} +``` + +高级接收形式会显式给出所有默认值,并禁止为注入附加上下文: + +```ts type-equiv +/** + * Fully specified input for {@link Agent.send}. Unlike the intent-named + * helpers, this form applies no defaults: callers provide content, source, + * contexts, metadata (including explicit `undefined`), target, and wakeup. + * The union excludes attached contexts from non-waking next-step injection. + */ +type ResolvedAgentInput = { + content: ContentBlock[] + source: MessageSource + meta: JsonValue | undefined +} & ( + | { target: 'next-turn'; wakeup: boolean; contexts: HookContext[] } + | { target: 'next-step'; wakeup: true; contexts: HookContext[] } + | { target: 'next-step'; wakeup: false; contexts: [] } +) +``` + +FIFO 投递方法返回不透明的 `AgentMessageId`,该 id 在同一条消息的各个 `agent/inbox/*` 事件中保持稳定。注入也返回 id,但会绕过这些事件: + +```ts type-equiv +/** + * Opaque id assigned to one accepted agent input. FIFO inputs carry the same id + * on their `agent/inbox/*` events; injection bypasses those events. + */ +type AgentMessageId = Branded<'AgentMessageId'> +``` + +`agent/inbox/*` 实时事件承载一条已接收的消息;注入绕过两个 FIFO,从不出现在这些事件中: + +```ts type-equiv +/** + * One accepted FIFO message, carried by the `agent/inbox/*` live events. `id` + * is the value returned by the accepting helper or {@link Agent.send}, + * stable across this message's enqueue, dequeue, and discard events. Source + * defaults, when applicable, are already applied, so these are the exact values + * the item was accepted with. + * `steering` is true for an item drained between steps; otherwise it is claimed + * at a turn boundary. `SendOptions.meta` is intentionally omitted: it is durable + * model-hidden state that lands on the eventual `user/message`/ + * `steering/message`, not live-event routing data. + */ +interface AgentMessage { + /** The id returned by the accepting helper or {@link Agent.send}. */ + id: AgentMessageId + content: ContentBlock[] + source: MessageSource + contexts: HookContext[] + /** Whether the item joined the steering FIFO rather than the queued FIFO. */ + steering: boolean + /** Whether the item wakes the driver or requests another step. */ + wakeup: boolean +} +``` + +```ts type-equiv +/** Options for {@link Agent.cancel}. */ +interface CancelOptions { + /** + * Preserve queued and steering inbox items instead of discarding them. The + * active turn is still aborted, but un-started and pending work survives for a + * later turn and no `agent/inbox/discard` fires. + */ + keepInbox?: boolean +} +``` + +```ts type-equiv +/** Stable runtime cause accepted by {@link Agent.cancel}. */ +type AgentCancelCause = + | { readonly kind: 'user' } + | { readonly kind: 'parent' } +``` + +结构化 `Agent` 接口公开四个按意图命名的辅助方法,以及接受完全解析输入的方法。具体驱动器只需实现一次这套路由矩阵,每个辅助方法提供其固定路由与默认值。 + +```ts type-equiv +/** Public agent handle; its concrete implementation is internal to `@deepseek-ai/dsh-agent-loop`. */ +interface Agent { + /** The single identity shared with {@link session}. */ + readonly id: SessionId + /** The provider route and model this agent's requests use. */ + readonly options: AgentOptions + /** The live session this agent drives; its log is the durable source of truth. */ + readonly session: Session + /** The current lifecycle state, mirrored on every `agent/status` transition. */ + readonly status: AgentStatus + /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */ + readonly ctx: Context + + /** + * Queue an ordinary message as its own FIFO-ordered turn and wake the driver. + * Content, resolved source, and attached contexts are detached, validated, + * and frozen together; invalid input throws synchronously before notification + * or enqueue. + * @param content - the prompt content blocks. + * @param options - source, attached contexts, and durable model-hidden meta. + * @returns the accepted message's {@link AgentMessageId}, stable across its `agent/inbox/*` events. + */ + followup(content: ContentBlock[], options?: SendOptions): AgentMessageId + + /** + * Queue an ordinary message without waking an idle driver. The item retains + * FIFO order and is claimed only after another input wakes the driver. A lone + * queued item leaves `whenIdle()` resolved. + * @param content - the prompt content blocks. + * @param options - source, attached contexts, and durable model-hidden meta. + * @returns the accepted message's {@link AgentMessageId}, stable across its `agent/inbox/*` events. + */ + queue(content: ContentBlock[], options?: SendOptions): AgentMessageId + + /** + * Submit steering into the running turn and request another step. 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. Idle steering + * becomes a waking ordinary turn. + * @param content - the steering content blocks. + * @param options - source, attached contexts, and durable model-hidden meta. + * @returns the accepted message's {@link AgentMessageId}, stable across its `agent/inbox/*` events. + */ + steer(content: ContentBlock[], options?: SendOptions): AgentMessageId + + /** + * 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`. An omitted source defaults to + * `{ kind: 'plugin', plugin: '' }`. + * @param content - the injected context content blocks. + * @param options - source and durable model-hidden meta. + * @returns the accepted injection's {@link AgentMessageId}; injection emits no `agent/inbox/*` events. + */ + inject(content: ContentBlock[], options?: InjectOptions): AgentMessageId + + /** + * Accept one fully specified input through the same snapshot and routing path + * as the four intent-named helpers. `next-turn` targets the ordinary FIFO; + * `next-step`/wakeup targets steering (falling back to an ordinary waking turn + * while idle); and `next-step` without wakeup injects durable context without + * running the model. Every field is mandatory and no source or routing default + * is applied. Invalid input throws synchronously before notification, enqueue, + * or append. + * @param input - the resolved content, attribution, context, metadata, and routing facts. + * @returns the accepted input's {@link AgentMessageId}, carried by FIFO lifecycle events when applicable. + */ + send(input: ResolvedAgentInput): AgentMessageId + + /** + * Clear queued and steering work — unless `keepInbox` — 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. Omitted cause + * 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. + * @param options - cancellation options; `keepInbox` preserves pending work. + */ + cancel(cause?: AgentCancelCause, options?: CancelOptions): void + + /** Resolve at idle quiescence; disposal waits for driver exit rather than only the status transition. */ + whenIdle(): Promise<void> +} +``` + +`AgentStatus` 为 `'idle' | 'running' | 'disposed'`,`SessionId` 是品牌类型。`running` 描述整个驱动器的排空区间,可能跨越轮次关闭、其持久化检查点以及连续的排队轮次;它不能证明某个轮次仍然打开。`AgentOptions` 可合并扩展:core 声明 `provider?` 与 `model?`(在 `agent/request` 后,分发要求两者都存在)。Persona 归 `dsh-system-prompt` 所有:agent 作用域的 `deployment:persona` 可以遮蔽全局默认值。 + +cause 是由 TypeScript 强制约束的同进程输入。活跃的 `TurnCancellation` 持有者会把其判别字段复制到仅运行时的 `AbortSignal.reason`,并在发布 `turn/end` 前退役;冻结后的 `AbortSignal.reason` 仍可读取。`agentInterruptReasonOf(signal)` 无需查询环境中的 initiator 状态,即可识别 `user`、`parent` 与仅用于生命周期的 `disposed`。持久 `turn/end` 保留粗粒度 `{ kind: 'aborted' }` 结果;若需记录请求 provenance,应使用单独的持久事件,而不是让终态结果承担额外含义。 + +[事件分类](../architecture.md#event)拥有 `agent/*` 生命周期、检查点与 waterfall(瀑布式事件)契约。轮次和步骤边界是持久会话事件,而不是 agent emit。 + +## 发起 Agent + +`ctx.agents` 携带的进程本地 initiator 就是上面的确切 `Agent`,不是单独的 frame 或复制的标识。环境中存在该值既不能证明存活,也不代表授权;其生命周期与边界规则由 [initiator 作用域决策](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md)规定。 + +## 拦截决策 + +每个 `agent/*` 拦截 waterfall 都返回一个小型、特定于 seam 的类型化联合——统一的 Decision 惯用形状([tools.md](tools.md) 中工具 seam 的 `PreToolDecision`/`PostToolDecision` 也采用相同形状)。CC/Codex 钩子桥接层把其 `permissionDecision`/`decision`/`continue`/`additionalContext` 字段映射到这些联合上;原生插件则直接返回它们。提示词决策与工具后决策共享一种面向模型的上下文形状 `HookContext`,它必须携带 `source`(缺少 source 会默认成 `{kind:'user'}`,从而把插件上下文错标为用户提示词)。其中的 `content` 作为 user-role 输入逐字到达模型,而 JSON `meta` 持久保存插件状态但不向模型暴露。未指定放置方式或指定为 `separate` 时,上下文会成为一条注入的 `user/message`(来源类别为插件或 goal);`prompt-prefix` 放置方式可用于提示词和 steering 收件箱附件,会在同一条消息中把上下文置于最终生效的请求之前。两种决策都携带 `additionalContexts[]`,使每一项保留各自的 provenance、元数据与放置方式。Continuation reason 则是 steering 消息,并有意使用更窄的 content/source 形状。 + +源码:[`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts) + +```ts type-equiv +/** Model-facing context injected by a listener or atomically attached to one inbox message. */ +interface HookContext { + content: ContentBlock[] + source: MessageSource + /** + * Model placement. Absent or `separate` records an independent injected + * `user/message`; `prompt-prefix` prepends this context and a stable + * request delimiter to the same user-role message as its attached prompt. + */ + placement?: 'separate' | 'prompt-prefix' + /** Opaque JSON state retained in the session event but hidden from the model. */ + meta?: JsonValue +} +``` + +`agent/prompt-submit` 返回 `PromptDecision`(允许该轮次已领取的排队消息——可选地改写其 `content` 或附加 `additionalContexts`——或者记录 `prompt/blocked` 并以 `rejected` 结束这个零步骤轮次): + +```ts type-equiv +/** + * Prompt interception result. `allow.content` replaces the prompt. Each + * `additionalContexts` entry follows its declared placement: separate context + * message by default, or a prefix inside the prompt's user-role message. + * `block` records a durable `prompt/blocked` and ends the claimed prompt's + * zero-step turn as rejected. An `allow` returned by a listener is + * authoritative: a listener wrapping `next()` preserves downstream `content` + * and `additionalContexts` unless it intentionally replaces them. + */ +type PromptDecision = + | { kind: 'allow'; content?: ContentBlock[]; additionalContexts?: HookContext[] } + | { kind: 'block'; reason: string } +``` + +`agent/turn-continuation` 返回 `ContinuationDecision`(步骤有工具调用或注入了 steering 时,循环默认为 `continue`,否则为 `stop`;`continue` 的 `reason` 会记录为同一轮次中下一个步骤的 steering,因此不携带上下文元数据——即类型化 `/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?: { content: ContentBlock[]; source: MessageSource } } +``` + +`agent/request-error` 接收确切的原始 `RequestError`、其不可变 `LlmFailure`、在连续序列中已批准另一次请求的不可变失败列表、轮次信号以及 `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 的持久变更之后打开一个带新编号的步骤,而 `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 输出、真实或合成的工具结果、缓冲上下文与 steering 持久化之后、`step/end` 之前被 await。被取消的工具批次在排空后携带 aborted signal 到达这里;其签名为 `(agent, turn, step, signal)`,可回放事实保留在会话日志中,而不是瞬态 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<ContinuationDecision, { action: 'stop' }> +``` + +`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' +``` + +`agent/session-prefix` 在每个循环实例中组合一次 `Message[]`。深度冻结的结果被记录在请求 header 中,并前置于每次派生历史,使其成为会话稳定开场白的归属。恢复的实例会重新组合;会话中途的变更使用仅追加的上下文通道。该 waterfall 直接返回内容,因为它是贡献而非决策。 + +## `ToolDefinition` + +唯一属于核心的流水线编写类型:每个已注册工具*是什么*——一个面向模型的 `ToolSchema` 加上一个 `execute` 函数,以及可选的最终内容回调与 UI 回调。工具作者很少手动构造它(`defineTool` DSL 会用类型化参数构建),但它是注册表持有、循环分发所经过的契约。 + +其完整字段、`defineTool`/`ValueSchemaSpec`/`ParameterSchemaSpec` 类型化 schema DSL、`ToolExecution`/`ToolExecutionResult` waterfall 形状,以及工具展示 UI 词汇在 **[tools.md](tools.md)** 中。 diff --git a/docs/core-data-structures/filesystem.i18n.yaml b/docs/core-data-structures/filesystem.i18n.yaml new file mode 100644 index 0000000000..e360dd99d3 --- /dev/null +++ b/docs/core-data-structures/filesystem.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 110c1fd428b15c5094f9dcc94050cad61c324373 +filesystem.zh.md: aca450364c05c6f756c36fccc11be7246767f3a4 diff --git a/docs/core-data-structures/filesystem.md b/docs/core-data-structures/filesystem.md index 25df997bb0..110c1fd428 100644 --- a/docs/core-data-structures/filesystem.md +++ b/docs/core-data-structures/filesystem.md @@ -1,5 +1,7 @@ # Filesystem +English | [中文](filesystem.zh.md) + The optional filesystem capability has four parts: [dsh-fs](../../packages/fs/fs) owns `ctx.fs` and atomic text operations with optional version guards, [dsh-fs-local](../../packages/fs/fs-local) implements local disk, [dsh-fs-policy](../../packages/fs/fs-policy) adds observed-state and freshness rules through events rather than a service, and [dsh-tool-fs](../../packages/fs/tool-fs) directly executes model-facing read/write/edit calls and renders windows. It is outside the agent-loop spine; alternate backends do not change policy or tool schemas. The model is **additive, not subtractive**: `ctx.fs` alone is a complete, unconstrained text-storage seam (`write` unconditionally creates-or-overwrites, `edit` unconditionally replaces literal text). `dsh-fs-policy` is a plugin that *adds* policy on top by deciding the `fs/*` waterfalls; removing it leaves the bare provider rather than breaking the tool, because the tool is not method-coupled to the policy. A deployment that loads `dsh-tool-fs` is expected to also load `dsh-fs-policy` so the default behavior is read-before-write/edit. diff --git a/docs/core-data-structures/filesystem.zh.md b/docs/core-data-structures/filesystem.zh.md new file mode 100644 index 0000000000..aca450364c --- /dev/null +++ b/docs/core-data-structures/filesystem.zh.md @@ -0,0 +1,259 @@ +# 文件系统 + +[English](filesystem.md) | 中文 + +可选的文件系统能力由四个部分组成:[dsh-fs](../../packages/fs/fs) 拥有 `ctx.fs` 以及带可选版本守卫的原子文本操作;[dsh-fs-local](../../packages/fs/fs-local) 实现本地磁盘后端;[dsh-fs-policy](../../packages/fs/fs-policy) 通过事件(而非服务)添加观测状态与新鲜度规则;[dsh-tool-fs](../../packages/fs/tool-fs) 直接执行面向模型的 read/write/edit 调用并渲染窗口。它位于 agent loop(智能体循环)主干之外;替换后端不会改变策略或工具 schema。 + +该模型是**加法式而非减法式**的:`ctx.fs` 本身就是一个完整、无约束的文本存储 seam(`write` 无条件创建或覆盖,`edit` 无条件替换字面文本)。`dsh-fs-policy` 是一个插件,通过裁决 `fs/*` waterfall(瀑布式事件)在上层*叠加*策略;移除它只会暴露裸提供方,而不会破坏工具,因为工具与策略之间没有方法级耦合。加载了 `dsh-tool-fs` 的部署通常也应加载 `dsh-fs-policy`,使默认行为为「先读后写/编辑」。 + +提供方源码:[`packages/fs/fs/src/types.ts`](../../packages/fs/fs/src/types.ts) 与 [`packages/fs/fs/src/index.ts`](../../packages/fs/fs/src/index.ts)。策略源码:[`packages/fs/fs-policy/src/types.ts`](../../packages/fs/fs-policy/src/types.ts)。读取渲染源码:[`packages/fs/tool-fs/src/read-render.ts`](../../packages/fs/tool-fs/src/read-render.ts)。 + +## 目标标识与元数据(提供方 seam) + +每个操作首先将用户提供的路径解析为不透明的后端目标。消费方可以显示 `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 +} +``` + +后端拥有文件版本 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 +} +``` + +`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 +} +``` + +## 写入与编辑守卫(提供方 seam) + +`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 +} +``` + +`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 +} +``` + +## fs 策略事件(提供方 seam 词汇) + +`dsh-fs` 拥有三个事件,由工具分发、策略插件监听,使发射方(`dsh-tool-fs`)与监听方(`dsh-fs-policy`)共享词汇,而发射方无需依赖策略插件。它们只携带 `dsh-fs` 词汇加一个不透明的 `object` actor,不含面向模型的概念,也不含 agent/会话所有者结构。 + +`fs/write-intent` 与 `fs/edit-intent` 是**单槽决策 waterfall**:工具分发时附带一个默认 thunk(返回 `undefined`,即裸提供方),监听方完全决策而不调用 `next()`。该槽按注册顺序先到先得——由策略插件占据是部署约定,而非强制不变式。`fs/observed` 是一个即发即弃的记录事件,通过普通 `ctx.emit` 分发;其监听方必须是同步的、仅产生副作用,因为工具不守卫该 emit——抛异常的监听方会在一次已成功的变更上表现为工具的 `isError` 结果。生成的目录在 [events.md](../cordis-catalog/events.md) 中展示确切签名。 + +## 执行上下文(策略插件) + +策略插件只需要足够的执行上下文,通过收窄 `fs/*` 事件携带的不透明 `object` actor 来推导观测状态的所有者。`ToolExecution` 满足此形状,因此 `dsh-tool-fs` 将其执行对象作为 actor 直接传递,而无需让 `dsh-fs-policy` 导入工具、agent 或会话包(package)。 + +```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 + } +} +``` + +## 读取结果(消费方 / 读取渲染) + +文本读取受行窗口、字节上限和后端限制约束。达到字节上限后,扫描仍会继续,但不再保留更多行,因此 `totalLines` 仍为精确值。面向模型的 `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[] + /** Exact total line count in the file. */ + totalLines: number + /** Whether selected output hit the byte cap. */ + truncatedByBytes?: true +} +``` + +## 已观测文件状态(策略插件) + +已观测状态是 `dsh-fs-policy` 插件内部持有的 `WeakMap<owner, Map<targetKey, { version }>>`。**当且仅当**所有者已读取、写入或编辑过该目标时(每次成功都 emit `fs/observed`),条目才存在,因此其存在本身就是先前观测的记录——没有单独的 `hasRead` 标志,也没有视图区分。所有者从事件 actor 推导(通常是 `exec.agent.session`),被视为不透明且从不读取。成功的 read/write/edit 会刷新该所有者对应的已记录版本;dispose(资源释放)时丢弃全部数据(HMR(热模块替换)安全)。 + +## 错误分类体系(提供方 seam) + +文件系统故障使用稳定的 `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' + | 'FS_AMBIGUOUS_EDIT' + | 'FS_EDIT_NOT_FOUND' + | 'FS_ABORTED' +``` + +目录列表使用 `FS_NOT_DIRECTORY`、`FS_PERMISSION_DENIED` 与 `FS_IO_ERROR` 区分已存在但并非目录的目标、被拒绝的列表操作和意外的后端 I/O 失败。`FS_SANDBOX_DENIED` 是强制执行沙箱的后端(`dsh-fs-sandbox`)所作的策略拒绝——模式边界拒绝了写入/编辑——与 `FS_PERMISSION_DENIED`(宿主内核拒绝)不同。`FS_NOT_OBSERVED` 表示策略插件没有此所有者的先前观察记录(或 `createIfAbsent` 遇到了现有文件)。`FS_STALE_VERSION` 表示后端版本不再与观察到的版本匹配(或编辑操作遇到缺失目标)。新鲜度授权没有部分/完整之分,因此不存在 `FS_PARTIAL_OBSERVATION`。 + +## 服务与插件 + +`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 new file mode 100644 index 0000000000..28191bd56c --- /dev/null +++ b/docs/core-data-structures/llm-streaming.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: cb99c935aea2dc9cc769e3056fdb98a2e5c9eacb +llm-streaming.zh.md: 740fa1f796088e63d0195cfbecf975adb236381c diff --git a/docs/core-data-structures/llm-streaming.md b/docs/core-data-structures/llm-streaming.md index 257ce90cda..cb99c935ae 100644 --- a/docs/core-data-structures/llm-streaming.md +++ b/docs/core-data-structures/llm-streaming.md @@ -1,5 +1,7 @@ # LLM Streaming +English | [中文](llm-streaming.zh.md) + The wire-level streaming vocabulary of [dsh-llm](../../packages/llm/llm). [core.md](core.md) introduces `StreamChunk`, `Message`, and `ContentBlock`; this page owns the full chunk protocol, the adapter contract every adapter must obey, and the shared assembler. Source: [`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts) diff --git a/docs/core-data-structures/llm-streaming.zh.md b/docs/core-data-structures/llm-streaming.zh.md new file mode 100644 index 0000000000..740fa1f796 --- /dev/null +++ b/docs/core-data-structures/llm-streaming.zh.md @@ -0,0 +1,218 @@ +# LLM(大语言模型)流式输出 + +[English](llm-streaming.md) | 中文 + +[dsh-llm](../../packages/llm/llm) 的协议格式(wire format)级流式输出词汇。[core.md](core.md) 介绍了 `StreamChunk`、`Message` 与 `ContentBlock`;本页拥有完整的分片协议、每个适配器必须遵守的适配器契约(adapter contract),以及共享的 assembler。 + +源码:[`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts) + +## `StreamChunk`:原始协议 + +一个流式响应交错包含多种类型的块(文本、推理(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 } + | { type: 'reasoning-delta'; index: number; text: string } + | { 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 + /** Adapter-private lossless-JSON state for replaying a successful response. */ + replayState?: unknown + } +``` + +## `LlmFailure` + +每个抛出的失败或最终适配器的带内失败都会规范化为一种可序列化、提供方无关的 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 +} +``` + +## 适配器契约 + +每个适配器必须遵守以下规则,每个消费方可以依赖它们: + +- **`usage` 在 `finish` 之前,`finish` 之后不再有任何分片。** 将两者都推迟到提供方的流结束标记,这样尾部的 usage-only 分片就不会违反顺序。 +- **工具调用的 `arguments` 全程保持原始 JSON 字符串。** 部分片段通过 `argumentsDelta` 流式传输;如果提供方返回的是已解析的对象,适配器在 `block-end` 时重新序列化为字符串。 +- **两条受支持的错误路径,一种事实形状。** 失败可以从 `stream()` 抛出(传输/协议错误),**或者**以 `finish {kind:'error'|'aborted', failure}` 结束流(无法在流中途抛异常的适配器用它表示提供方带内错误)。`LlmError.failure` 携带同一个 `LlmFailure`。最终适配器边界保留被抛出的确切 `Error` 对象,并将不可变事实关联到该调用;agent loop(智能体循环)关闭失败的步骤,再把错误、事实与不可变的先前已重试事实提供给 `agent/request-error`。若未恢复,结构化失败会成为轮次错误,并且该次尝试不会提交正常 assistant 消息或工具副作用。 +- **一次适配器调用就是一次提供方尝试。** 适配器禁用库重试。agent 层恢复会打开另一个持久、带编号的步骤;直接调用 `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 分片错误路径,而传输边界测试证明每个空闲 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(元数据清单)获取版本;每个字段都是公开产品事实——不含 secret、路径、会话 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` 只包含未缓存输入;缓存输入单独报告,计费输入是三者之和。若提供方把缓存命中折入单一提示词总数(如 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 + cacheReadTokens?: number + cacheWriteTokens?: number + reasoningTokens?: number +} +``` + +## `BlockAssembler` + +`BlockAssembler`([`packages/llm/llm/src/assembler.ts`](../../packages/llm/llm/src/assembler.ts))是唯一的共享实现,负责把 `StreamChunk` 流折叠回 `ContentBlock`、usage、结束原因与回放状态。循环在记录原始分片的同时,把同一批分片送入 assembler,再将组装后的 assistant 内容连同其提供方/模型 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(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 格式正确的分片——块重组不是每个适配器各自的问题。消费方 surface(`ctx.llm.stream()`)与 `llm/stream` waterfall 见 [architecture.md § 内容块与流式传输](../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<readonly LlmModelInfo[]>; + /** + * 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<LlmModelContext | undefined>; + /** + * 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<StreamChunk>; +} +``` + +`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 + 'tool-call': ToolCallBlock + 'tool-result': ToolResultBlock +} +``` + +块接口详见 [core.md § Content blocks and messages](core.md#content-blocks-and-messages)。 diff --git a/docs/core-data-structures/persistence.i18n.yaml b/docs/core-data-structures/persistence.i18n.yaml new file mode 100644 index 0000000000..cbb92a56d1 --- /dev/null +++ b/docs/core-data-structures/persistence.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 1e96e983fc390befe9e35ed3a2f0d6ab5f92a5b8 +persistence.zh.md: 5236f4fe2ba8ad1be7e74bffafebfea19014d7aa diff --git a/docs/core-data-structures/persistence.md b/docs/core-data-structures/persistence.md index af34dfa058..1e96e983fc 100644 --- a/docs/core-data-structures/persistence.md +++ b/docs/core-data-structures/persistence.md @@ -1,5 +1,7 @@ # Session Persistence +English | [中文](persistence.zh.md) + The **durability seam** for the event log. [session.md](session.md) describes the in-memory `Session` — the append-only `SessionEvent` log that is the source of truth. This page describes how that log is made durable: the abstract `SessionPersistence` service, its backends, the flush checkpoint, crash recovery, and the metadata header that travels alongside the log. The event vocabulary the log carries is enumerated, member by member, in the generated [persistence log event catalog](../persistence-catalog.md). The seam is a textbook [capability seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md): one abstract service ([dsh-session-persistence](../../packages/session-persistence/session-persistence), `ctx.sessionPersistence`) defining locate/create/append, crash-repairing load, non-mutating inspect, and lightweight list/snapshot observation over the existing `SessionEvent` — **no parallel persisted type** — and two interchangeable backends that pass the same `runPersistenceContract` suite. See the [session-persistence Agent Note](../../.agents/notes/implemented/architecture/2026-06-14-session-persistence.md). @@ -53,7 +55,7 @@ interface SessionHeader { readonly version: number /** The session's id (mirrors the {@link Session}'s id). */ readonly id: SessionId - /** Unix epoch milliseconds when the session was created. */ + /** Non-negative safe-integer Unix epoch milliseconds when the session was created. */ readonly createdAt: number /** Absolute working directory the session was created in (if any). */ readonly cwd?: string diff --git a/docs/core-data-structures/persistence.zh.md b/docs/core-data-structures/persistence.zh.md new file mode 100644 index 0000000000..5236f4fe2b --- /dev/null +++ b/docs/core-data-structures/persistence.zh.md @@ -0,0 +1,134 @@ +# 会话持久化 + +[English](persistence.md) | 中文 + +事件日志的**持久性 seam**。[session.md](session.md) 描述了内存中的 `Session`:仅追加的 `SessionEvent` 日志即为真源。本页描述如何使该日志持久化:抽象的 `SessionPersistence` 服务、它的后端、flush 检查点、崩溃恢复,以及随日志一同存储的元数据头。日志承载的事件词汇在生成的[持久化日志事件目录](../persistence-catalog.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、不会修改数据的 inspect,以及轻量的 list/snapshot 观察——**没有平行的持久化类型**——以及两个可互换、通过同一套 `runPersistenceContract` 的后端。见 [session-persistence Agent Note(agent 决策记录)](../../.agents/notes/implemented/architecture/2026-06-14-session-persistence.md)。 + +## flush 检查点 + +`session/event` 是一个*同步*通知;持久化插件会将事件复制到逐会话控制器,并立即启动写入而不阻塞生产方。并发事件会加入当前批次;在该批次写入期间接纳的事件会触发后续批次。`session/flush` 会等待当前与待处理批次全部清空,因此循环仍将其用作在领取下一个普通轮次之前的顺序与错误观察检查点。立即写入被拒绝时会保留对应事件;显式 flush 会重试这些事件,并通过 `agent/error` 和 logger 报告失败,绝不会把失败记录成已关闭轮次之后的会话事件。dispose(资源释放)会执行同样的最终排空。 + +## 崩溃恢复保留被中断的轮次 + +后端重新加载一个在轮次中途崩溃的日志时,会发现一个已打开的 `turn/start` 却没有 `turn/end`。它**不会**截断日志:在长周期任务中,单个轮次可能非常庞大(许多步骤、大量工具输出),而这些事件在崩溃前已被持久追加。后端改为用一个合成的 `turn/end { reason: { kind: 'interrupted' } }` 关闭这个遗留轮次,保持日志平衡与轮次闭合不变式。`interrupted` 是唯一一个不由循环发出的 `TurnEndReason`(见 [session.md](session.md#why-a-turn-ended-turnendreasonmap))。 + +修复仅适用于冷会话。对于活跃 id,`SessionPersistence.load(id)` 会对内存日志拍摄快照,等待该快照完成持久化,并且只在日志平衡时连同已存储的 header 返回;若活跃轮次仍未闭合,则拒绝操作,而不是添加合成的中断边界。由协调器管理的冷加载会在后端读取和修复写入期间占用该 id,因此并发发布同 id 的活跃会话会被拒绝并回滚。HMR 也会接管活跃前缀,而不会关闭其中正在进行的轮次。 + +`SessionPersistence.inspect(id)` 是恢复机制面向观察方的对等操作:它返回已存储有效前缀的独立副本,不截断不完整记录、不添加中断结束事件,也不发布写入状态。同 id 串行化确保它与后端写入保持一致。派生读取模型使用 `inspect`,绝不使用 `load`,因此即使活跃所有权并发建立,观察已落检查点但仍未闭合的轮次也不会修改日志。 + +## `SessionLocation`——可选的逐会话产物目标 + +`SessionPersistence.locate(meta)` 会同步解析一个归后端所有的独立产物,而不会读取、创建或 flush 它。JSONL 返回其绝对目标路径;SQLite 因各会话共享一个数据库而返回 `undefined`。因此,返回的路径可能指向尚不存在、或还不包含当前尚未 flush 的轮次;它是位置提示,不是授权或新鲜度保证。 + +```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` 上。 + +源码:[`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 + * session is created. A persistence backend rejects any other version on load + * (no migration — see the constant). + */ + readonly version: number + /** The session's id (mirrors the {@link Session}'s id). */ + readonly id: SessionId + /** Non-negative safe-integer Unix epoch milliseconds when the session was created. */ + readonly createdAt: number + /** Absolute working directory the session was created in (if any). */ + readonly cwd?: string + /** The session this one was forked from (seed lineage), if any. */ + readonly parentSession?: SessionId + /** + * 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` 种子边界、`delegationDepth`,以及——仅在重建已持久化会话时——需要保留的原始 `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[] + /** + * 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 + } +} +``` + +因此,回放/fork 的调用方式为 `ctx.sessions.create(id, { seed: seedEvents })`;将一个*持久化*会话恢复为活跃 agent 的调用方式为 `ctx.agents.resume({ resumeSessionId })`。 + +## 轻量源修订号 + +派生状态的消费方会在加载完整事件日志之前比较一个低开销的不透明修订号。其表示由持久化后端拥有,并随 append 或会修改数据的 load 修复以事务方式改变;调用方仅比较修订号是否相等。 + +```ts type-equiv +/** + * Backend-owned token that identifies both one storage source and one revision + * of a persisted session log. + */ +type SessionPersistenceRevision = Branded<'SessionPersistenceRevision'> +``` + +```ts type-equiv +/** Lightweight immutable source identity returned without loading a full log. */ +interface SessionPersistenceSnapshot { + /** Detached metadata for one materialized session. */ + header: SessionHeader + /** Opaque source-qualified token that changes whenever this stored log changes. */ + revision: SessionPersistenceRevision +} +``` + +## 后端 + +两者都实现同一个抽象 `SessionPersistence`(在 `SessionEvent` 上执行 locate/create/append/load/inspect/list/listSnapshots),并通过 `runPersistenceContract`,证明该 seam 确实与后端无关: + +- **[dsh-session-persistence-jsonl](../../packages/session-persistence/session-persistence-jsonl)**——每个会话一份仅追加的逻辑 JSONL 日志,默认存储为带 checksum 的连续 Zstandard frame,也可配置为原始行;支持崩溃安全的原子写入、被中断轮次的恢复以及读取/回放路径。 +- **[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。 diff --git a/docs/core-data-structures/sandbox.i18n.yaml b/docs/core-data-structures/sandbox.i18n.yaml new file mode 100644 index 0000000000..f8189f4e15 --- /dev/null +++ b/docs/core-data-structures/sandbox.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 9bc05fa06f22fdc9ac9e8aacd482c1e7c2f2edec +sandbox.zh.md: 9a52f126758fe0e7988715c7824e963bd6e6ea84 diff --git a/docs/core-data-structures/sandbox.md b/docs/core-data-structures/sandbox.md index bdc86287fb..9bc05fa06f 100644 --- a/docs/core-data-structures/sandbox.md +++ b/docs/core-data-structures/sandbox.md @@ -1,5 +1,7 @@ # Process Sandbox +English | [中文](sandbox.zh.md) + The process-sandbox seam of [dsh-sandbox](../../packages/sandbox/sandbox) wraps a same-world subprocess argv in a file-effect policy without coupling consumers to a platform runner. [dsh-sandbox-local](../../packages/sandbox/sandbox-local) supplies the Linux bwrap/Landlock and macOS Seatbelt backends; [dsh-bash-sandbox](../../packages/bash/bash-sandbox) is the first consumer. Containers, microVMs, and remote execution are sibling implementations of whole capability seams, not providers of `ctx.sandbox`. Source: [`packages/sandbox/sandbox/src/index.ts`](../../packages/sandbox/sandbox/src/index.ts) diff --git a/docs/core-data-structures/sandbox.zh.md b/docs/core-data-structures/sandbox.zh.md new file mode 100644 index 0000000000..9a52f12675 --- /dev/null +++ b/docs/core-data-structures/sandbox.zh.md @@ -0,0 +1,127 @@ +# 进程沙箱 + +[English](sandbox.md) | 中文 + +[dsh-sandbox](../../packages/sandbox/sandbox) 的进程沙箱 seam 将与宿主共享文件系统和内核的子进程 argv 包装在文件效果策略中,而不将消费方耦合到特定平台运行器。[dsh-sandbox-local](../../packages/sandbox/sandbox-local) 提供 Linux bwrap/Landlock 与 macOS Seatbelt 后端;[dsh-bash-sandbox](../../packages/bash/bash-sandbox) 是第一个消费方。容器、microVM 和远程执行是完整能力 seam 的兄弟实现,而非 `ctx.sandbox` 的提供方。 + +源码:[`packages/sandbox/sandbox/src/index.ts`](../../packages/sandbox/sandbox/src/index.ts) + +## 模式与强制执行 + +`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<SandboxMode, 'danger-full-access'> +``` + +强制执行程度是一个报告事实。`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`,因此消费方可以只解析一次策略,再决定是否绕过约束。普通工具调用从调用会话的不可变 cwd 派生 `workspaceRoot`;部署配置是没有 agent(智能体)时的回退值。root 会先按文件系统语义规范化,再做词法规范化,因此包含 `symlink/..` 的 cwd 会标识所生成进程实际运行的目录。 + +```ts type-equiv +/** + * 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: SandboxMode + /** Absolute root directory `workspace-write` may write under. */ + workspaceRoot: string +} +``` + +`ctx.sandboxPolicy.resolve()` 接收活跃会话;对于已批准的重试,还接收显式模式。该服务拥有优先级与 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 的同时收窄模式。这使并发会话、消费方与一次性提权重试可以向同一提供方请求不同边界,而无需改变提供方状态。 + +```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[] + /** How completely the selected backend enforces the policy's file effects. */ + enforcement: SandboxEnforcement + /** + * The selected backend's denial DIALECT: the case-insensitive stderr + * substrings a file effect denied by THIS backend produces (EROFS text + * under bwrap's read-only binds, EACCES under Landlock, EPERM under + * Seatbelt). A consumer that infers denials from a failed run's stderr + * matches against exactly these rather than a cross-backend union — the + * union claims denials a given backend never produces. + */ + denialSignatures: readonly string[] + /** + * 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[] +} +``` + +运维人员配置的本地运行器必须为自身的 pre-exec 拒绝方言提供至少一条 `runnerFailureSignatures` 条目;提供方会自动添加外层 shell 的 missing 和 unexecutable 形式。这使得可执行的自定义运行器拒绝其 profile 的情况能够与被包装命令以相同状态码退出的情况区分开来。 + +## 提供方与 fail-closed 错误 + +`ctx.sandbox.confine(argv, policy)` 返回一个 `ConfinedArgv`,或在没有可用后端时抛出 `SandboxUnavailableError`(错误码 `SANDBOX_UNAVAILABLE`)。已选定的运行器也可能在执行时 fail-closed,此时其失败签名承载相同的基础设施含义。对于受限策略,静默的无隔离透传永远不合法。 + +提供方探测在多个候选后端之间仲裁,结果在提供方生命周期内缓存。只有一个候选后端的平台可以直接选定它;执行时拒绝仍保留安全属性。本地提供方将 bwrap 和 Seatbelt 报告为 full,并保留 Landlock 启动器的 full/partial 内核裁定。 diff --git a/docs/core-data-structures/scope.i18n.yaml b/docs/core-data-structures/scope.i18n.yaml new file mode 100644 index 0000000000..b565e11461 --- /dev/null +++ b/docs/core-data-structures/scope.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 73a697f2843293daffff85dabf4656346f7dcd04 +scope.zh.md: f3c591da2befdcff69d89ad0667653392111fb8e diff --git a/docs/core-data-structures/scope.md b/docs/core-data-structures/scope.md index e9869f3152..73a697f284 100644 --- a/docs/core-data-structures/scope.md +++ b/docs/core-data-structures/scope.md @@ -1,5 +1,7 @@ # Scoped Registration +English | [中文](scope.zh.md) + The [scope package](../../packages/core/scope) supplies the identity, carrier, and scoped-layer vocabulary that makes one registration context mean both per-agent visibility and shared lifetime ownership. It is a library primitive rather than a Cordis service; the [agent-scope runtime-design Agent Note](../../.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md#scope-routing-one-opaque-key-selects-one-layer) owns the lifecycle rationale, the [shared-storage Agent Note](../../.agents/notes/implemented/architecture/2026-07-12-scoped-layers-store.md) owns the registry-layer decision, and the package [README](../../packages/core/scope/README.md) owns the callable API and filtering semantics. Sources: [`packages/core/scope/src/index.ts`](../../packages/core/scope/src/index.ts) and [`packages/core/scope/src/store.ts`](../../packages/core/scope/src/store.ts). diff --git a/docs/core-data-structures/scope.zh.md b/docs/core-data-structures/scope.zh.md new file mode 100644 index 0000000000..f3c591da2b --- /dev/null +++ b/docs/core-data-structures/scope.zh.md @@ -0,0 +1,59 @@ +# 作用域注册 + +[English](scope.md) | 中文 + +[scope 包(package)](../../packages/core/scope)提供 identity、carrier 与 scoped-layer 词汇,使同一个注册上下文同时代表逐 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)规定,注册表层决策由[共享存储 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/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<T>` 是编译期品牌标记,标注在 `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<T extends object> = 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> | void + /** Dispose every scope-owned registration; racing calls await the same completion. */ + dispose(): Promise<void> +} +``` + +## 带作用域的注册表层 + +`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<L>` 拥有立即创建的全局 layer,以及惰性创建的确切作用域 layer。读取不会创建 layer:`peek(undefined)` 表示没有 overlay,而 `merge()` 会物化按插入顺序排列的全局具名 entry,随后是带作用域的 shadow。注册使用同一个上下文表示可见性与 Cordis effect 所有权,在可选通知前收集一个同步 undo,返回 Cordis 的确切 disposer,并且只在带作用域 layer 的完整 `ScopeLayer` 为空时回收它。 + +`NamedEntries<V>` 提供按插入顺序的查找与 live iteration,重复错误由调用方所有。`AnonymousEntries<V>` 为每次 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 new file mode 100644 index 0000000000..f9c7355148 --- /dev/null +++ b/docs/core-data-structures/session-query.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: d92af4bac34f7d41457e9e193111c3a53fe8022e +session-query.zh.md: ecf330b0a361ffae352a91c0d35524444936606d diff --git a/docs/core-data-structures/session-query.md b/docs/core-data-structures/session-query.md index 4886eb3087..d92af4bac3 100644 --- a/docs/core-data-structures/session-query.md +++ b/docs/core-data-structures/session-query.md @@ -1,5 +1,7 @@ # Session Query +English | [中文](session-query.zh.md) + Query vocabulary over the live-preferred logical session corpus. The [interface package](../../packages/session-query/session-query) owns exact reads, source precedence, relationship tracing, semantic extraction, and provider-independent filters, while the [SQLite package](../../packages/session-query/session-query-sqlite) owns the concrete full-text index lifecycle. Source: [`packages/session-query/session-query/src/types.ts`](../../packages/session-query/session-query/src/types.ts) diff --git a/docs/core-data-structures/session-query.zh.md b/docs/core-data-structures/session-query.zh.md new file mode 100644 index 0000000000..ecf330b0a3 --- /dev/null +++ b/docs/core-data-structures/session-query.zh.md @@ -0,0 +1,355 @@ +# 会话查询 + +[English](session-query.md) | 中文 + +本文定义面向优先使用 live 数据的逻辑会话语料库的查询词汇。[接口包(package)](../../packages/session-query/session-query)负责精确读取、来源优先级、关系追踪、语义提取,以及与提供方无关的过滤器;[SQLite 包](../../packages/session-query/session-query-sqlite)负责具体全文索引的生命周期。 + +源码:[`packages/session-query/session-query/src/types.ts`](../../packages/session-query/session-query/src/types.ts) + +## 逻辑记录 + +`SessionRecord` 由跨语料库列表返回。它独立于克隆后的实时优先 header 暴露源可用性。`SessionEventRecord` 是轻量的原始日志投影;分类使用与 model-history 推导相同的 `foldSurface()` 状态转换。 + +```ts type-equiv +/** Whether an event is current model context, replaced context, or raw-log-only. */ +type SessionEventSurface = 'current' | 'shadowed' | 'log-only' +``` + +```ts type-equiv +/** 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 +} +``` + +`SessionLogSnapshot` 是供恢复预检使用的完整原始日志:它脱离运行时,并经过回放验证。`SessionSurfaceSnapshot` 表示一次精确读取的 surface 观测结果,而不是持续保留的订阅。 + +```ts type-equiv +/** One validated detached observation of a logical session's complete raw log. */ +interface SessionLogSnapshot { + /** Cloned session header selected from the same observation as `events`. */ + session: SessionHeader + /** Cloned contiguous raw events after persistence repair and replay validation. */ + events: SessionEvent[] +} +``` + +```ts type-equiv +/** One atomic live-preferred observation of a session's current model surface. */ +interface SessionSurfaceSnapshot { + /** Cloned session header selected from the same corpus observation as `events`. */ + session: SessionHeader + /** Highest raw-log seq included in the observation, or `null` for an empty log. */ + capturedThroughSeq: number | null + /** Cloned current surface events in model-history order. */ + events: SurfaceEvent[] +} +``` + +`SessionTitleObservation` 将同样的原子观测规则应用于标题折叠,使授权消费者能够验证提供标题的源 header。批量读取会按顺序为每个唯一请求 id 返回一个 `SessionTitleObservationResult`:操作失败只影响对应 id,而取消会拒绝整个操作。 + +```ts type-equiv +/** Latest folded title bound to the same session-header observation. */ +interface SessionTitleObservation { + /** Cloned header selected with the event log used for the title fold. */ + session: SessionHeader + /** Latest title snapshot, absent when the observed log has no title. */ + title?: SessionTitleSnapshot +} +``` + +```ts type-equiv +/** One ordered result from a batch title observation. */ +type SessionTitleObservationResult = + | { + /** Requested session id. */ + sessionId: SessionId + /** Successful atomic header/title observation. */ + status: 'fulfilled' + /** Header and optional latest title from one logical source. */ + value: SessionTitleObservation + } + | { + /** Requested session id. */ + sessionId: SessionId + /** Operational failure isolated to this session. */ + status: 'rejected' + /** Original failure from logical-source resolution or title folding. */ + reason: unknown + } +``` + +```ts type-equiv +/** 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 +} +``` + +## 与提供方无关的过滤器和文档 + +会话和事件过滤器数组内的各项按逻辑与(AND)组合;单个列表子句中的各值按逻辑或(OR)组合。范围包含两端。事件的 `text` 子句会对提取出的语义文本执行正则表达式扫描:搜索文本按字面量处理,Unicode 字符不区分大小写,空白字符可灵活匹配;该过程与全文搜索提供方无关。 + +```ts type-equiv +/** + * One logical-session predicate. A filter array is ANDed; `values` within a + * clause are ORed. + */ +type SessionResultFilter = + | { kind: 'id'; values: readonly SessionId[] } + | { kind: 'cwd'; values: readonly (string | null)[] } + | ({ kind: 'created-at' } & SessionResultRange) + | { kind: 'parent'; values: readonly (SessionId | null)[] } + | { kind: 'availability'; values: readonly SessionAvailability[] } +``` + +```ts type-equiv +/** + * One event predicate. A filter array is ANDed; list-valued clauses are ORed. + * Text is a literal, case-insensitive, whitespace-flexible semantic-text scan. + */ +type SessionEventResultFilter = + | ({ kind: 'seq' } & SessionResultRange) + | ({ kind: 'time' } & SessionResultRange) + | { kind: 'type'; values: readonly SessionEventType[] } + | { kind: 'surface'; values: readonly SessionEventSurface[] } + | { kind: 'text'; text: string } +``` + +```ts type-equiv +/** Searchable semantic document derived from one session event. */ +interface SessionEventSearchDocument extends SessionEventRecord { + /** First-party semantic text used by scan filters and full-text indexes. */ + text: string +} +``` + +`ctx.sessionQuery.filterSessions(filters)` 会对完整的逻辑会话语料库应用 `SessionResultFilter`;`ctx.sessionQuery.filterEvents(sessionId, filters)` 按 seq 升序返回匹配的文档。消息、推理(reasoning)、工具调用和工具结果、被阻止的提示词、待办事项,以及失败和状态详情会纳入语义文本;结构事件和流分片则不会。 + +## 全文搜索结果页 + +整合后的 `ctx.sessionQuery` seam 提供两个全文搜索范围。`searchSessions()` 按匹配度最强的事件对语料库分组;`searchEvents()` 搜索单个会话。请求将不透明游标与规范化后的查询、元数据过滤器和结果数量上限绑定。提供方的元数据过滤器有意不包含事件文本扫描。 + +```ts type-equiv +/** Provider-owned opaque continuation token returned by session search. */ +type SessionSearchCursor = Branded<'SessionSearchCursor'> +``` + +```ts type-equiv +/** Cross-session full-text search request. */ +interface SessionSearchRequest { + /** Full-text query interpreted as data, never executable FTS syntax. */ + query: string + /** Logical-session predicates applied before event ranking. */ + sessionFilters?: readonly SessionResultFilter[] + /** Event predicates applied before event ranking. */ + eventFilters?: readonly SessionEventMetadataFilter[] + /** Maximum sessions in this page. */ + limit?: number + /** Opaque cursor returned for the identical normalized request. */ + cursor?: SessionSearchCursor +} +``` + +```ts type-equiv +/** Within-session full-text search request. */ +interface SessionEventSearchRequest { + /** Session whose live-preferred logical log is searched. */ + sessionId: SessionId + /** Full-text query interpreted as data, never executable FTS syntax. */ + query: string + /** Event predicates applied before ranking. */ + filters?: readonly SessionEventMetadataFilter[] + /** Maximum events in this page. */ + limit?: number + /** Opaque cursor returned for the identical normalized request. */ + cursor?: SessionSearchCursor +} +``` + +```ts type-equiv +/** One cursor-paginated result page. */ +interface SessionSearchPage<T> { + /** Results for this page in contract-defined order. */ + items: readonly T[] + /** Opaque continuation cursor, absent on the final page. */ + nextCursor?: SessionSearchCursor +} +``` + +与跨会话分组 hit 不同,会话内搜索即使没有命中项,也必须公开它观测到的目标 header。 + +```ts type-equiv +/** Event-search results bound to the indexed target-session observation. */ +interface SessionEventSearchPage extends SessionSearchPage<SessionEventSearchHit> { + /** Cloned target header from the same indexed generation as `items`. */ + session: SessionHeader +} +``` + +```ts type-equiv +/** One event full-text search hit with a bounded plain-text excerpt. */ +interface SessionEventSearchHit extends SessionEventRecord { + /** Plain text excerpt selected around the match. */ + snippet: string +} +``` + +```ts type-equiv +/** One grouped cross-session hit, ranked by its strongest matching event. */ +interface SessionSearchHit extends SessionRecord { + /** Strongest matching event for this session. */ + bestMatch: SessionEventSearchHit +} +``` + +## 会话谱系 + +`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 +/** 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 +/** 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[] +} +``` + +```ts type-equiv +/** Event relationships bound to the same session-header observation. */ +interface SessionEventTraceObservation extends SessionEventTrace { + /** Cloned header selected with the event log used for the trace. */ + session: SessionHeader +} +``` + +## 错误 + +封闭的 code 联合类型区分请求校验、目标缺失、surface 日志格式错误、可选后端故障与矛盾的源元数据。 + +```ts type-equiv +/** Stable machine-routable failure taxonomy for session reads, traces, and search. */ +type SessionQueryErrorCode = + | 'SESSION_QUERY_ABORTED' + | 'SESSION_QUERY_EVENT_NOT_FOUND' + | 'SESSION_QUERY_INDEX_FAILED' + | 'SESSION_QUERY_INVALID_CONFIG' + | 'SESSION_QUERY_INVALID_CURSOR' + | 'SESSION_QUERY_INVALID_FILTER' + | 'SESSION_QUERY_INVALID_LIMIT' + | 'SESSION_QUERY_INVALID_QUERY' + | 'SESSION_QUERY_INVALID_LINEAGE' + | 'SESSION_QUERY_INVALID_SURFACE' + | 'SESSION_QUERY_INVALID_WINDOW' + | 'SESSION_QUERY_PERSISTENCE_FAILED' + | 'SESSION_QUERY_SESSION_NOT_FOUND' + | 'SESSION_QUERY_STALE_CURSOR' + | 'SESSION_QUERY_SOURCE_CONFLICT' +``` diff --git a/docs/core-data-structures/session.i18n.yaml b/docs/core-data-structures/session.i18n.yaml new file mode 100644 index 0000000000..454bd17c38 --- /dev/null +++ b/docs/core-data-structures/session.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: d789ffcabb5cb0c744e265b61e322831c1d8a04f +session.zh.md: f4f102861db7403520e9f38cb56613e430718cbe diff --git a/docs/core-data-structures/session.md b/docs/core-data-structures/session.md index 30a6f897d4..d789ffcabb 100644 --- a/docs/core-data-structures/session.md +++ b/docs/core-data-structures/session.md @@ -1,5 +1,7 @@ # Sessions +English | [中文](session.zh.md) + The in-memory, event-sourced model of [dsh-session](../../packages/core/session). A `Session` is an **append-only log** of typed `SessionEvent`s — the single source of truth for an agent's whole interaction history. The LLM message history is *derived* from the log, never stored separately; replay is re-derivation from the same events. How the log is made **durable** (the persistence seam, backends, crash recovery) is the sibling concern on [persistence.md](persistence.md). Source: [`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts) @@ -141,7 +143,7 @@ interface OutOfBandSessionEventMap {} ### `TodoItem` — one todo-list entry -The unit of the `todo/write` event's whole-list snapshot. Deliberately minimal — a `content` line and a three-state `status` (no id, priority, or `activeForm`): the list is replaced wholesale on every write, 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). See the [todo_write Agent Note](../../.agents/notes/implemented/feature/2026-06-29-todo-write-tool.md). +The unit of the `todo/write` event's whole-list snapshot. Deliberately minimal — a `content` line and a three-state `status` (no id, priority, or `activeForm`): the list is replaced wholesale on every write, so entries need no stable identity. See the [todo_write Agent Note](../../.agents/notes/implemented/feature/2026-06-29-todo-write-tool.md). ```ts type-equiv /** @@ -150,10 +152,9 @@ The unit of the `todo/write` event's whole-list snapshot. Deliberately minimal * * 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). + * on every write (last-write-wins), so entries need no stable identity. The + * three statuses describe the complete portable lifecycle needed by model and + * UI consumers. */ interface TodoItem { /** What this task is — a short imperative line shown in the UI. */ diff --git a/docs/core-data-structures/session.zh.md b/docs/core-data-structures/session.zh.md new file mode 100644 index 0000000000..f4f102861d --- /dev/null +++ b/docs/core-data-structures/session.zh.md @@ -0,0 +1,569 @@ +# 会话 + +[English](session.md) | 中文 + +[dsh-session](../../packages/core/session) 的内存事件溯源模型。`Session` 是一份由类型化 `SessionEvent` 组成的**仅追加日志**,是 agent(智能体)完整交互历史的唯一真源。LLM(大语言模型)消息历史从日志*派生*而来,从不单独存储;回放即从同一组事件重新派生。日志如何实现**持久化**(持久化 seam、后端、崩溃恢复)是兄弟文档 [persistence.md](persistence.md) 的关注点。 + +源码:[`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts) + +## `SessionEventMap`:事件词汇 + +仅追加的事件类型。可通过声明合并扩展:插件通过 declaration merging 声明额外的事件类型。例如[压缩(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 +/** + * Shared payload for user, injected-context, and steering prompt messages. A + * direct human prompt, a synthetic `agent.inject()` context, and mid-turn + * steering all project into the model transcript as verbatim user-role content; + * they are told apart by `source` (a non-`user` kind marks injected context), + * not by event type. `meta` carries durable model-hidden producer state. + */ +interface PromptMessageData { + /** Exact model-facing blocks, including any baked prompt-prefix contexts. */ + content: ContentBlock[] + /** Producer provenance for the direct prompt. */ + source: MessageSource + /** Present only when prompt-prefix contexts were baked into `content`. */ + envelope?: PromptMessageEnvelope + /** + * Opaque durable JSON state retained on the event but hidden from the model + * projection. It is the intended channel for a 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. + */ + meta?: JsonValue +} +``` + +```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-role message on the model-visible surface: a direct human prompt + * (the queued message claimed for this turn), a synthetic `agent.inject()` + * context (file-change notices, subdir AGENTS.md, skill content, cron + * notifications, …), or an admitted goal continuation round. All three + * project their `content` verbatim; `source` (with a non-`user` kind marking + * injected context) is the only channel that tells them apart. An idle + * injection wraps this event in a one-shot turn so the log stays turn-enclosed. + */ + 'user/message': PromptMessageData + /** + * 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 } + /** Raw stream chunk — token-level replay fidelity. */ + 'assistant/chunk': { turn: number; step: number; chunk: StreamChunk } + /** + * Assembled assistant message for one step (derived history uses this). + * Carries the step's `usage` when the adapter reported token accounting, so + * 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[]; 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, optional internal failure + * identity, and optional tool-private `meta` presentation payload. `meta` is + * opaque to the core (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?: JsonValue + } + /** Steering content injected between steps of a running turn. */ + 'steering/message': PromptMessageData & { turn: number } + /** Whole-list snapshot; latest write wins on replay. Log-only UI state; never derived history. */ + 'todo/write': { todos: TodoItem[] } + /** + * 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 } +} +``` + +`PromptMessageData.content` 始终是确切的模型可见内容。当附加上下文声明 `prompt-prefix` 放置方式时,AgentLoop 会依次把它的块、一个 `## My request:` 分隔符以及最终生效的直接提示词拼接进该数组。可选且对模型隐藏的 `envelope` 会保留 `displayContent`,以及按顺序排列的前缀上下文来源/元数据描述信息,使 transcript(文本记录)、标题与重新引用消费方无需改变可重建历史,就能呈现人类提示词。`displayPromptContent()` 负责该选择,并为普通事件和较早的事件回退到 `content`。 + +### `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`);列表在每次写入时整体替换,因此条目无需稳定标识。见 [todo_write Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-06-29-todo-write-tool.md)。 + +```ts type-equiv +/** + * 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. The + * three statuses describe the complete portable lifecycle needed by model and + * UI consumers. + */ +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' +} +``` + +<a id="the-request-header-event-requestheader"></a> + +### 请求头事件:`request/header` + +请求信封(即 `EpochHeader`:调用配置 + 渲染后的系统提示词 + 已组装的工具 schema + 会话前缀)会作为会话状态写入日志,因此每个对话请求都是日志的纯函数(见可重建性 Agent Note)。带有 reason `'initial'` 或 `'resume'` 的完整 `request/header` 快照记录每个 agent loop 实例的边界;之后请求发生变化时,系统会以 reason `'change'` 记录另一份完整快照。`foldRequestHeader(events)` 通过选择最新快照重建请求头。该事件不是 `SurfaceEventType`,不产生 LLM 消息。 + +```ts type-equiv +/** + * 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 + /** Assembled tool schemas; absent for a tool-less request. */ + tools?: ToolSchema[] + /** + * The session prefix: request-only messages sent BEFORE the entire derived + * history (the `agent/session-prefix` waterfall's product, composed once + * per loop instance and reused for every request it sends). Not session + * history — `deriveMessages()` never returns it — so the header is its + * only durable record; absent when the instance composed none. + */ + messagePrefix?: Message[] +} +``` + +规范形式:空系统提示词、空工具列表和空会话前缀都表示为字段缺失,与请求构建方式一致。`messagePrefix` 是 `agent/session-prefix` waterfall(瀑布式事件)产物的持久记录(请求 = `messagePrefix + derived history`);每个 agent loop 实例只组合一次,并包含在该实例记录的每份完整快照中。包含已移除的 `request/header-delta` 事件或完整快照原因为 `fallback` 的旧版 v0 日志,会在 seed、append 和持久化加载边界被拒绝,而不会以不完整方式回放。 + +## `SessionEvent<T>`:一条日志条目 + +基于 `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`, `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<T extends SessionEventType = SessionEventType> = { + [K in SessionEventType]: { + type: K + /** Monotonic sequence number within the session. */ + seq: number + /** Unix epoch milliseconds. */ + time: number + data: SessionEventMap[K] + } & (K extends SurfaceEventType ? { + /** + * 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). 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. */ + surfaceOp?: SurfaceOp + } : object) +}[T] +``` + +`SessionEventType = keyof SessionEventMap`。由于 `SessionEventMap` 可通过合并扩展,对 `SessionEvent` 的 switch 语句禁止使用 `assertNever`:插件添加的变体是合法的未知值;处理已知 case 后在 `default` 中放行。 + +对于 `assistant/message`,存在的 `sourceEventSeqs: []` 表示提供方流已知且完整地为空;字段缺失则表示旧格式或其他未记录溯源信息的情况。agent loop 会为每次成功的模型调用写入该字段;其他 surface 事件只要包含该字段,其列表就必须非空。 + +## Surface 类型 + +四种产生消息的类型(`SurfaceEventType`:`user/message`、`assistant/message`、`tool/result`、`steering/message`)携带 surface 元数据,用来声明它们如何加入有序的派生 surface。见 [session surface Agent Note](../../.agents/notes/implemented/architecture/2026-06-18-session-surface.md)。 + +### `SurfaceEventType`:事件类型中产生消息的子集 + +```ts type-equiv +/** + * 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' + | 'steering/message' +``` + +### `SurfaceOp`:事件如何进入 surface + +```ts type-equiv +/** + * 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/steering + * 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` 时仅替换单个条目),并在原位置插入新事件。 + +### `SurfaceIntent`:`session.append()` 的参数 + +```ts type-equiv +/** + * 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 类型在编译期拒绝此参数。 + +此处适用相同的溯源区分:只有 `assistant/message` 可以携带存在但为空的 `sourceEventSeqs`;省略该字段并不表示其源流为空。 + +### `SessionSurface`:实时只读 surface 投影 + +`Session.surface` 返回会话稳定的 `SessionSurface` 视图。同一个增量管理器在提交前校验追加候选事件,并根据已提交事件推进该投影;调用方可以观察成员关系和替换代次,但不能调用校验。 + +```ts type-equiv +/** 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 列表,以及每个声明的替换范围实际遮蔽的 seq。实时管理器复用同一套状态转换,但不保留替换历史。每提交一次替换,其 `replaceGeneration` 就递增一次,使增量消费方能够区分纯尾部增长与重写。 + +```ts type-equiv +/** 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 +/** 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<T extends SessionEventType>( + type: T, + data: SessionEventMap[T], + ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent] : [] + ): SessionEvent<T>; + /** + * 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` → 一条携带确切 `content` 的 user 消息;可选 envelope 仅作为日志中的展示元数据保留。 +- `assistant/message` → 一条 assistant 消息,包含事件的提供方/模型溯源信息和可选的适配器私有回放状态。原始 `assistant/chunk` 事件属于回放/UI 数据,在派生时会被**跳过**(组装后的消息才是权威)。**内容为空的** `assistant/message` 也会跳过:因 max-tokens 而截断且无内容的步骤仍会记录一条 `assistant/message` 以承载用量和溯源信息,但无内容的 assistant 轮次不得进入提供方 transcript。 +- `tool/result` → 一条携带 `tool-result` 块的 user 消息。 +- `user/message`(注入上下文,即非 `user` 来源)→ 按时间顺序在相应位置生成一条 user-role 消息,并原样承载其 `content`。可选的 JSON `meta` 保留在事件日志中,绝不渲染。 +- `steering/message` → 按时间顺序在相应位置生成一条携带确切 `content` 的 user-role 消息;可选 envelope 仅作为日志中的展示元数据保留。 + +其余所有事件(`turn/*`、`step/*`、插件所有的 `llm/retry`)均为结构信息,不会投影为消息。token 记账读取每个步骤的 `assistant/chunk { type: 'usage' }` 记录;如果没有用量分片,则将 `assistant/message.usage` 作为已提交步骤的后备。失败的模型请求尝试没有 assistant 消息,因此其用量分片是持久化的记账记录。操作错误的步骤号记录在 `turn/end.reason`(`kind: 'error'`)中;如果是最终模型请求失败,其中包含规范化的 `LlmFailure` 事实,其他实时错误则包含消息/代码。由于这一尚未发布的格式有意不提供兼容性承诺,seed/load 校验会拒绝缺少提供方和模型的请求头,以及缺少提供方/模型溯源信息的 assistant 消息,而不会猜测历史数据应走的提供方路由。 + +## 活跃会话 fork API + +`ctx.sessions.create(id, { seed, meta })` 是底层的回放/fork 原语。对于普通的活跃会话 fork,`SessionStore` 暴露一个策略 API: + +- `fork(source, boundary?, childSessionId?)` 接受一个活跃的 `Session` 对象或活跃的 `SessionId`,选取到 `boundary` seq(含)为止的源事件(默认为当前最后一个事件),要求 boundary 事件必须是 `turn/end`,然后创建一个活跃的子会话,包含深克隆的种子事件和子会话元数据(`parentSession`、`seedLength` 及继承的 `cwd`)。 + +显式 `boundary` 允许调用者从之前完成的轮次 fork,即使源会话有更新的事件或正在进行的轮次。API 拒绝非 `turn/end` 的 boundary,而不是静默截断。更广泛的轮次封闭性检查留在既有的 `dsh-invariants` 插件和持久化修复路径中,不在 `fork()` 中重复。`dsh-subagent-fork` 保留其已完成前缀截断逻辑,因为工具时委托通常在父轮次仍然打开时启动;普通的会话分支应显式指定请求的 boundary。 + +## 轮次的触发原因:`TurnTriggerMap` + +```ts type-equiv +/** + * What started a turn. + * Merge-extensible sum type (same pattern as MessageSourceMap). + */ +interface TurnTriggerMap { + message: { kind: 'message'; source: MessageSource } + /** + * An out-of-band context injection (`agent.inject()`) made while the agent + * was idle. The loop wraps the injected `user/message` (a non-`user` source, + * plugin by default) in a one-shot turn (`turn/start` → `user/message` → + * `turn/end`) so every event in the log stays turn-enclosed — the + * durability/replay boundary is the turn, and a bare event between turns would + * otherwise be indistinguishable from a crash tail on reload. The trigger's + * `source` mirrors that message's producer. + */ + injection: { kind: 'injection'; source: MessageSource } +} +``` + +<a id="why-a-turn-ended-turnendreasonmap"></a> + +## 轮次的结束原因:`TurnEndReasonMap` + +`aborted` 有意作为一种粗粒度的持久结果:它只记录取消中断了实时轮次,不记录是哪个运行时调用方发起取消。仅属于运行时的调用方词汇由 [`AgentCancelCause`](core.md#the-agent-handle) 定义;未来若有审计需求,应新增独立的控制请求事件,而非让终止结果承载这一信息。 + +```ts type-equiv +/** + * Why a turn ended. Merge-extensible sum type. + */ +interface TurnEndReasonMap { + completed: { kind: 'completed' } + /** 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`). 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 } & ( + | { 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' } + /** + * 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 } + /** + * 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(Agent Client Protocol)桥接层将其映射为 `cancelled`)。`interrupted` 是唯一不会由任何 loop 发出的原因:它由崩溃恢复合成(见 [persistence.md](persistence.md))。两个 map 均可通过合并扩展。 + +## 轮次封闭不变式 + +每个会话事件都位于一个轮次**之内**(在 `turn/start` 和对应的 `turn/end` 之间)。loop 在 `turn/start` *之后*追加已排队的 `user/message` 事件;空闲时的 `agent.inject()` 会用一次性的 `injection` 轮次包住其 `user/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/*` 记录:它注入的 `user/message` 已是持久证据,而且当时没有已打开的轮次可容纳该记录(见[钩子桥接 Agent Note](../../.agents/notes/implemented/feature/2026-06-30-hook-bridges.md))。 + +## 持久性契约 + +持久化后端依赖的契约如下:持久日志无损保存每个事件,**包括** `assistant/chunk`;`seq` 必须连续,因此不能从规范日志中过滤分片。后端可以为事件批次选择自己的存储编码,只要 `load` 返回与追加时完全一致的事件即可(JSONL 后端可选启用的打包分片行就是此类编码;见 [persistence.md](persistence.md))。所有 `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 new file mode 100644 index 0000000000..2f67387224 --- /dev/null +++ b/docs/core-data-structures/skills.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: fc9599713dcfddec9719ed746b66ea0217b86cf5 +skills.zh.md: 0eb4c0aa69ed56117c7508358c0d47e3b3e95fcb diff --git a/docs/core-data-structures/skills.md b/docs/core-data-structures/skills.md index e367adf006..fc9599713d 100644 --- a/docs/core-data-structures/skills.md +++ b/docs/core-data-structures/skills.md @@ -1,5 +1,7 @@ # Skills +English | [中文](skills.zh.md) + The [skill capability family](../../packages/skill) is split across three packages: the registry ([dsh-skill](../../packages/skill/skill), `ctx.skills`) merges provider catalogs; the local provider ([dsh-skill-local](../../packages/skill/skill-local)) scans project/custom/user directories; the consumer ([dsh-tool-skill](../../packages/skill/tool-skill)) owns the session-prefix catalog and model-facing `skill` tool. Skills are optional instructions, not session events, so their vocabulary lives here rather than in [core.md](core.md). Source: [`packages/skill/skill/src/index.ts`](../../packages/skill/skill/src/index.ts), [`packages/skill/skill-local/src/index.ts`](../../packages/skill/skill-local/src/index.ts), and [`packages/skill/tool-skill/src/index.ts`](../../packages/skill/tool-skill/src/index.ts). diff --git a/docs/core-data-structures/skills.zh.md b/docs/core-data-structures/skills.zh.md new file mode 100644 index 0000000000..0eb4c0aa69 --- /dev/null +++ b/docs/core-data-structures/skills.zh.md @@ -0,0 +1,159 @@ +# Skills + +[English](skills.md) | 中文 + +[skill(技能)能力族](../../packages/skill)拆分为三个包(package):注册表([dsh-skill](../../packages/skill/skill),`ctx.skills`)合并各提供方的目录;本地提供方([dsh-skill-local](../../packages/skill/skill-local))扫描项目/自定义/用户目录;消费方([dsh-tool-skill](../../packages/skill/tool-skill))拥有会话前缀目录和面向模型的 `skill` 工具。skill 是可选的指令而非会话事件,因此其词汇定义在此处而非 [core.md](core.md)。 + +源码:[`packages/skill/skill/src/index.ts`](../../packages/skill/skill/src/index.ts)、[`packages/skill/skill-local/src/index.ts`](../../packages/skill/skill-local/src/index.ts) 与 [`packages/skill/tool-skill/src/index.ts`](../../packages/skill/tool-skill/src/index.ts)。 + +## 提供方注册表 + +`ctx.skills` 组合本地、内嵌、远程或其他提供方。注册是同步的;远程初始化与发现属于 `list()` 的 await 阶段。提供方对象、选项与候选项以只读方式借用,语义字段会被校验。 + +重名按 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<readonly SkillCandidate[]> + /** + * 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<SkillDefinition | undefined> +} +``` + +## 本地发现优先级 + +内置的本地提供方按 rank 顺序扫描各根目录: + +| Rank | Source | Root | +|---|---|---| +| 100 | `project-dsh` | `<projectRoot>/.dsh/skills` | +| 200 | `project-agents` | `<projectRoot>/.agents/skills` | +| 300 | `custom` | `Config.customSkillDirs` | +| 400 | `user-dsh` | `<dshHome>/skills` | +| 500 | `user-agents` | `<agentsHome>/skills` | + +项目根目录为包含 `.git` 的最近祖先目录;找不到时使用当前 cwd。当 `ctx.fs` 可用时,git-root 向上查找通过文件系统服务探测 `.git`,使远程或沙箱工作区不会回退到宿主文件系统边界。用户 DSH 根目录会跳过其 `.system` 子目录。本地提供方不附带内置系统 skill;部署方通过另一个提供方提供内置 skill。 + +## Skill 身份 + +skill 名称为 kebab-case(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)。本地提供方接受目录包(`<name>/SKILL.md`)和扁平 Markdown 文件(`<name>.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 & {}) +``` + +## 摘要、候选项与完整定义 + +`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 +} +``` + +`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<Record<string, unknown>> +} +``` + +`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 } + | { readonly kind: 'opaque'; readonly description: string } +``` + +```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<Record<string, unknown>> +} +``` + +运行时 skill 使用相同的完整形状,参与相同的先到先得收集顺序。返回的 disposer 移除该贡献并使发现缓存失效。 + +```ts type-equiv +/** Runtime skill contribution accepted by `ctx.skills.register()`. */ +type SkillRegistration = Omit<SkillDefinition, 'provider'> & { readonly provider?: string } +``` + +## 查找与配置 + +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 +} +``` + +注册表只拥有其发现缓存上限。本地提供方拥有文件系统根目录(`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 `<system-reminder>`。目录只包含已排序的 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,并返回包含 `<skill_content name="...">`、`<skill_resources>` 和 `<skill_instructions>` 的工具结果。`resourceBase` 仅按需解析显式引用的脚本、参考资料和资产;加载结果不枚举 skill 目录。工具结果是模型获取完整指令的可见路径。 diff --git a/docs/core-data-structures/subagent.i18n.yaml b/docs/core-data-structures/subagent.i18n.yaml new file mode 100644 index 0000000000..d8d6a493d7 --- /dev/null +++ b/docs/core-data-structures/subagent.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 0335a3f0780ae17b57ae730f5a49a269261c8073 +subagent.zh.md: dac48b624f6e0cfc28737e3e1a2774ba2d97e85b diff --git a/docs/core-data-structures/subagent.md b/docs/core-data-structures/subagent.md index 4f9cbdae61..0335a3f078 100644 --- a/docs/core-data-structures/subagent.md +++ b/docs/core-data-structures/subagent.md @@ -1,5 +1,7 @@ # Subagent +English | [中文](subagent.zh.md) + The subagent seam — an agent delegating work to a child agent. Like [bash](bash.md) it is **one optional capability**, not part of the agent-loop spine, so its vocabulary lives here rather than in [core.md](core.md). But it differs from every other seam on one axis: **multiple provider implementations coexist** in one context, registered by name (`ctx.subagents`), where bash allows only one executor. The registry shape mirrors the [LLM adapter registry](llm-streaming.md), not the single-service bash executor. Interface: [dsh-subagent](../../packages/subagent/subagent) (`ctx.subagents` + the vocabulary below). Implementations are sibling packages (`dsh-subagent-spawn`, `-fork`, `-acp`); the model-facing consumer is [dsh-tool-subagent](../../packages/subagent/tool-subagent). The proposal and rationale: [the subagent Agent Note](../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md). diff --git a/docs/core-data-structures/subagent.zh.md b/docs/core-data-structures/subagent.zh.md new file mode 100644 index 0000000000..dac48b624f --- /dev/null +++ b/docs/core-data-structures/subagent.zh.md @@ -0,0 +1,248 @@ +# Subagent + +[English](subagent.md) | 中文 + +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` + 下文词汇)。实现为三个兄弟包(package):`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) + +## 两类能力,两种发现方式 + +提供方通过一个静态描述符公布其**启动时**特性,服务在 run 存在之前即行检查;如果请求依赖提供方不具备的特性,会被大声拒绝(`SubagentError('UNSUPPORTED_CAPABILITY')`),绝不会被接受后静默忽略。**运行时**特性(steering(中途引导)、恢复)则是 [`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 +} +``` + +## 启动请求 + +工具层根据模型输入和自身配置构建此请求;服务在 `start` 之前针对指定提供方进行校验。必填的 `parent` 提供会话 cwd、谱系与委派深度。可选的 output schema、depth、工具过滤器和 persona 需要对应的能力 flag 匹配。不支持的 schema 在启动时即失败;进程内后端将 filter 和 persona 的作用域限定在子 agent 创建阶段,并通过强制 capture 工具实现所支持的 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 `assertObjectJsonSchema`'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?: ObjectJsonSchema + /** + * 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 组合控制 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 +} +``` + +`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' +} +``` + +<a id="a-live-run-subagentrun"></a> + +## 活跃 run:`SubagentRun` + +`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 { + /** + * 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<SubagentResult> + /** + * 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<void> + /** + * 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<SubagentRun> +} +``` + +本地 run 必须在 `start()` fulfill 前发布一个普通子 agent/会话,将该子会话 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<SubagentRun> +} +``` + +`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 和会话词汇: + +- **委派深度**由持久 `SessionHeader.delegationDepth` 与可合并扩展的运行时字段 `AgentOptions.subagentDepth` 共同表示;缺失表示顶层深度为零,存在的较大值具有权威性。两个字段都归该 seam 所有——循环既不设置也不读取它们——因此进程内子 agent 会持久保存 parent 深度 + 1,恢复无法降低深度,而且每次 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 new file mode 100644 index 0000000000..e697ec6bcd --- /dev/null +++ b/docs/core-data-structures/system-prompt.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 63a750c74300b4353f132d3dae9da52a10631f23 +system-prompt.zh.md: 3f7ab9aee5743616f00e95e81fb9a3a4af2c6e8a diff --git a/docs/core-data-structures/system-prompt.md b/docs/core-data-structures/system-prompt.md index 85a974e6df..63a750c743 100644 --- a/docs/core-data-structures/system-prompt.md +++ b/docs/core-data-structures/system-prompt.md @@ -1,5 +1,7 @@ # System Prompt Assembly +English | [中文](system-prompt.zh.md) + The [system-prompt package](../../packages/core/system-prompt) owns the data exchanged between prompt contributors and one assembly call. The package [README](../../packages/core/system-prompt/README.md) documents registration, ordering, scoping, and rendering behavior; this page pins the literal cross-package shapes that plugins implement or pass. Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts). diff --git a/docs/core-data-structures/system-prompt.zh.md b/docs/core-data-structures/system-prompt.zh.md new file mode 100644 index 0000000000..3f7ab9aee5 --- /dev/null +++ b/docs/core-data-structures/system-prompt.zh.md @@ -0,0 +1,62 @@ +# 系统提示词组装 + +[English](system-prompt.md) | 中文 + +[system-prompt 包(package)](../../packages/core/system-prompt)负责管理提示词贡献者与一次组装调用之间交换的数据。该包的 [README](../../packages/core/system-prompt/README.md) 记录了注册、排序、作用域与渲染行为;本页固定各插件实现或传递的跨包字面形状。 + +源码:[`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts)。 + +## 组装上下文 + +`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 +} +``` + +## 工具提供方结果 + +`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[] +} +``` + +## 提示词段落 + +`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 new file mode 100644 index 0000000000..56581614ec --- /dev/null +++ b/docs/core-data-structures/tools.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 4a8081154a12a0d30e90f8b4df059ddc4257bba0 +tools.zh.md: 74f543548a54e532d1a858dee33bed906e82f4b3 diff --git a/docs/core-data-structures/tools.md b/docs/core-data-structures/tools.md index d68e280b24..4a8081154a 100644 --- a/docs/core-data-structures/tools.md +++ b/docs/core-data-structures/tools.md @@ -1,5 +1,7 @@ # Tools +English | [中文](tools.zh.md) + The tool pipeline of [dsh-tools](../../packages/core/tools). [core.md](core.md) introduces `ToolDefinition` as the one pipeline-authoring type promoted to the spine and `ToolSchema` as the model-facing wire shape. This page owns the full `ToolDefinition`, the typed schema DSL that builds it, the guarded execution shapes, and the UI-presentation vocabulary. Source: [`packages/core/tools/src/index.ts`](../../packages/core/tools/src/index.ts) · [`packages/core/tools/src/schema.ts`](../../packages/core/tools/src/schema.ts) · [`packages/core/tools/src/presentation.ts`](../../packages/core/tools/src/presentation.ts) @@ -405,8 +407,8 @@ type ObjectJsonSchema = JsonSchemaNode & { type: 'object' } How a tool wants its call shown in a UI (an editor tool-call card, a CLI log line), provider-neutral so a tool describes itself without depending on any client protocol. `presentCall`/`presentResult` return a **`card`-tagged render intent** — a discriminated union a UI bridge switches on: - `ToolCallView` (pending): `{ card: 'generic', title, kind?, rawInput?, content?, locations? }` (the default card; `locations` is `{ path, line? }[]` files the call reads/modifies, for editor follow-along), `{ card: 'terminal', title, description?, cwd? }` (a shell command → a terminal card), or `{ card: 'diff', title, diffs, locations? }` (a file create/modify → an inline diff card; `diffs` is `{ path, oldText, newText }[]`, `oldText: null` for a new file). -- `ToolResultView` (completed): `{ card: 'generic', title?, content? }`, `{ card: 'terminal', title?, output?, exitCode?, signal? }` (the captured run output + exit; a capable UI shows an exit-status pill, an incapable one gets a fenced ` ```console ` fallback the bridge derives from `output`), or `{ card: 'diff', title?, diffs }` (a completed file mutation → the change to show, typically the applied hunks with context lines computed from the before/after content, or a whole-file diff when there is no before-image — e.g. a file create. A `tool_call_update`'s content REPLACES the call's content, so a mutation tool returns this even when it duplicates the call-time snippet, to keep the result from clobbering the diff with result text). +- `ToolResultView` (completed): `{ card: 'generic', title?, content? }`, `{ card: 'terminal', title?, output?, exitCode?, signal? }` (the captured run output + exit; a capable UI shows an exit-status pill, while another may derive a fenced ` ```console ` fallback), or `{ card: 'diff', title?, diffs }` (a completed file mutation → the change to show, typically the applied hunks with context lines computed from the before/after content, or a whole-file diff when there is no before-image). Completed views replace pending views, so mutation tools return a diff result even when it duplicates the call-time snippet. -`ToolCallKind` (`'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other'`) picks an icon on a generic card. `FileLocation` (`{ path, line? }`) and `FileDiff` (`{ path, oldText, newText }`) are the shared file-card vocabulary. The design is pinned in [the render-intent-union Agent Note](../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md); the ACP bridge maps a `diff` card to a `{ type: 'diff' }` content block, a `terminal` card to the `_meta` terminal convention, and relativizes a file card's title against the session cwd. +`ToolCallKind` (`'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other'`) picks an icon on a generic card. `FileLocation` (`{ path, line? }`) and `FileDiff` (`{ path, oldText, newText }`) are the shared file-card vocabulary. The design is pinned in [the render-intent-union Agent Note](../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md); the TUI and host/client runtime project this neutral vocabulary into their own views. The full presentation field docs live in [`packages/core/tools/src/presentation.ts`](../../packages/core/tools/src/presentation.ts). The `bash` schema and executor are on [bash.md](bash.md); generic background controls are on [tasks.md](tasks.md). diff --git a/docs/core-data-structures/tools.zh.md b/docs/core-data-structures/tools.zh.md new file mode 100644 index 0000000000..74f543548a --- /dev/null +++ b/docs/core-data-structures/tools.zh.md @@ -0,0 +1,414 @@ +# 工具 + +[English](tools.md) | 中文 + +[dsh-tools](../../packages/core/tools) 的工具流水线。[core.md](core.md) 介绍了 `ToolDefinition`(唯一被提升到主干的流水线编写类型)和 `ToolSchema`(面向模型的协议格式(wire format)形状)。本页拥有完整的 `ToolDefinition`、用于构建它的类型化 schema DSL、受保护的执行形状,以及 UI 展示词汇。 + +源码:[`packages/core/tools/src/index.ts`](../../packages/core/tools/src/index.ts) · [`packages/core/tools/src/schema.ts`](../../packages/core/tools/src/schema.ts) · [`packages/core/tools/src/presentation.ts`](../../packages/core/tools/src/presentation.ts) + +## `ToolDefinition` — 一个已注册的工具 + +由一个 `ToolSchema`(面向模型的字段)、必需的规范输出声明、`execute` 函数、仅供宿主使用的调度器元数据、可选的最终内容回调和可选 UI 展示函数组成。注册表持有这些定义,循环通过它们分派调用。注册表的 `schemas()` 通过显式允许列表构建面向模型的 `ToolSchema[]`;`output`/`execute`/`finalizeContent`/`timeoutMs`/`isConcurrencySafe`/`presentCall`/`presentResult` 绝不能泄漏到模型请求中。 + +```ts type-equiv +/** Tool-owned canonical output contract used after the body returns a JSON value. */ +interface ToolOutputDefinition { + /** Raw supported JSON Schema enforced against every successful canonical value. */ + readonly schema: JsonSchemaNode + /** Pure projection from validated arguments and value to Native/model content. */ + render(args: unknown, value: JsonValue): ContentBlock[] + /** Pure replayable presentation projection, computed only for surface calls. */ + presentationMeta?(args: unknown, value: JsonValue): JsonValue +} +``` + +```ts type-equiv +/** A registered tool: its schema plus the execution function. */ +interface ToolDefinition extends ToolSchema { + /** Mandatory canonical output declaration. */ + readonly output: ToolOutputDefinition + /** + * Run one accepted call and return only its canonical lossless-JSON value. + * 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 the canonical value declared by `output.schema`. + */ + execute(args: unknown, exec: ToolRunContext): Promise<unknown> + /** + * Synchronous last-mile transform for model-facing content. The registry + * snapshots this callback when execution starts and invokes it exactly once + * for every normalized outcome, including pipeline failures that bypass + * `tools/post-execute`, immediately before lossless materialization. + * Returning `undefined` preserves the content; every other result field + * remains registry-owned. The callback must be total and must not throw. + * @param exec - immutable execution identity and arguments. + * @param result - complete normalized outcome before materialization. + * @returns replacement content, or `undefined` to preserve it. + */ + finalizeContent?(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): ContentBlock[] | undefined + /** + * Cooperative tool-call timeout budget in milliseconds. Omit for no deadline. + * Enforced by `@deepseek-ai/dsh-timeout-policy` (a `tools/execute` wrapper); it + * is NEVER sent to the model — `schemas()` whitelists only name/description/ + * parameters. Declaring it asserts this tool forwards `exec.signal` to a + * 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 + * its own input). Returns a {@link ToolCallView} (a `card`-tagged render intent), + * or `undefined` (or omit the method) to fall back to a generic presentation + * (title = tool name, raw args as input). Pure and side-effect-free: a UI may + * call it during live streaming AND a session-log replay, so it must depend + * only on `args`. + */ + presentCall?(args: unknown): ToolCallView | undefined + /** + * Optional: how to present the COMPLETED state, given the same `args` and the + * durable result projection (`content`, failure state, and optional `meta`). Returns a + * {@link ToolResultView}, or `undefined` (or omit the method) to keep the + * pending title and render the raw result content. Pure and side-effect-free + * for the same replay reason. + */ + presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined +} +``` + +`execute` 接收 `args: unknown`——原始的 `ToolDefinition` 自行校验输入。第一方工具不需要手写校验;它们使用 `defineTool`,由后者代为校验并收窄参数类型、根据 `output.schema` 推导函数体返回类型,并为两个输出投影器提供类型约束。`finalizeContent` 特意接收不可变的执行对象而非类型化参数,因为无效输入和外层流水线失败也会到达该回调;它可以施加工具自有的内容限制,同时保留 `isError`、规范值、结构化错误身份、延迟上下文与展示元数据。 + +## 统一的 JSON 值 schema DSL + +插件作者使用同一套词汇描述类型化参数和类型化输出值。`ValueSchemaSpec` 支持 `string`、`number`、`integer`、`boolean`、`null`、`array`、`object`、仅作者侧可用的 `json`,以及要求恰好命中一个分支的 `oneOf`;标量 `enum` 和 `const` 值必须与节点类型匹配。显式对象节点始终声明 `additionalProperties: true | false`。参数定义仍是隐式的开放对象属性映射,每个必填属性都附带 `required: true`。 + +源码:[`packages/core/tools/src/schema.ts`](../../packages/core/tools/src/schema.ts) + +```ts type-equiv +/** One author-facing schema for any lossless JSON value root. */ +type ValueSchemaSpec = + | StringValueSchemaSpec + | NumberValueSchemaSpec + | IntegerValueSchemaSpec + | BooleanValueSchemaSpec + | NullValueSchemaSpec + | ArrayValueSchemaSpec + | ObjectValueSchemaSpec + | JsonValueSchemaSpec + | OneOfValueSchemaSpec +``` + +```ts type-equiv +/** One implicit parameter-root property, optionally required. */ +type ParameterPropertySpec = ValueSchemaSpec & { required?: true } +``` + +```ts type-equiv +/** + * Tool parameter schema. The map itself is an implicit open object root; + * requiredness remains a per-property `required: true` annotation. + */ +type ParameterSchemaSpec = { + [key: string]: ParameterPropertySpec + [key: symbol]: never +} +``` + +`{ type: 'json' }` 推导为 `JsonValue`,并编译成仅含注解、不施加约束的原始 schema。输出根可以是对象、数组、标量或 null。`InferValue<S>` 在 16 层容器内保留字面量约束与对象开放性,之后回退为 `JsonValue`,避免耗尽 TypeScript 的类型实例化栈。`InferArgs<P>` 依据逐属性的必填标记生成必填和可选的字符串键: + +```ts type-equiv +/** + * Infer the TypeScript value accepted by an author-facing value schema. Exact + * inference is bounded to 16 container levels, then falls back to `JsonValue`. + */ +type InferValue<S> = InferValueAt<S, []> +``` + +```ts type-equiv +/** Infer the TypeScript argument object for an implicit parameter schema. */ +type InferArgs<S> = InferProperties<S, []> +``` + +`defineTool({ name, description, parameters, output, execute, … })` 将参数推导与 `parameterSchemaSpecToJsonSchema()` 和 `validateArgs()` 绑定,并将 `execute`/`render`/`presentationMeta` 与 `InferValue<OutputSchema>` 绑定。Schema 记录只包含自有且可枚举的字符串键,schema 数组是稠密的内建数组,因此推导、编译与校验观察到的是同一份声明。精确推导保持到 16 层容器,之后放宽为 `JsonValue`;运行时校验仍会继续遍历完整 schema。`valueSchemaSpecToJsonSchema()` 通过同一套已强制执行的原始子集编译输出声明。参数不匹配时抛出 `ToolArgsError`(`INVALID_ARGS`);函数体或后置策略产生的值无效时抛出 `ToolOutputError`(`INVALID_TOOL_OUTPUT`)。两者都经由常规工具错误路径处理。原始 JSON Schema 默认保持开放;不支持的关键字会被拒绝,而不会在未强制执行的情况下获准进入。 + +注册是一个受信任的同进程契约。注册表以 readonly 输入借用类型化定义,要求它声明 `output`,校验其原始 schema,并检查 `timeoutMs` 必须为正有限值等语义要求;`schemas()` 在模型边界处物化显式的面向模型投影,使执行和展示共享同一份已解析定义,而不会将回调泄漏到协议上。 + +## `ToolRestriction` — 单个作用域的实时全局过滤器 + +`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()` 接受由调用方拥有且包含必需 readonly `signal` 的 `ToolExecutionInput`,将其解析后的 JSON 参数一次性物化为流水线拥有的 `ToolExecution`,然后让调用依次经过 `tools/pre-execute`(可重排的 allow/deny/ask waterfall)→ 已注册的单调 guard → `tools/execute`(环绕分派包装层)→ `tools/post-execute`(检查/替换结果)→ 可选且由定义拥有的 `finalizeContent` → `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 + /** 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. + */ + readonly parent?: ToolExecutionToken + /** 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 +} +``` + +```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<ToolExecution, 'signal'> { + /** 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<ToolExecution>) => string | undefined +``` + +```ts type-equiv +/** Canonical failure detail; internal routing information remains optional. */ +interface ToolFailure { + /** Human-readable failure message without the Native `Error: ` envelope. */ + message: string + /** Internal error class/code used by policy and durable diagnostics. */ + info?: ToolErrorInfo +} +``` + +```ts type-equiv +/** Successful canonical tool execution, including its Native/model projection. */ +interface ToolExecutionSuccess { + readonly isError: false + /** Execution-local canonical value; deliberately omitted from durable events. */ + readonly value: JsonValue + readonly content: ContentBlock[] + readonly error?: never + readonly meta?: JsonValue + readonly additionalContexts?: HookContext[] +} +``` + +```ts type-equiv +/** Failed canonical tool execution; failures never carry a successful value. */ +interface ToolExecutionFailure { + readonly isError: true + readonly error: ToolFailure + readonly value?: never + readonly content: ContentBlock[] + readonly meta?: JsonValue + readonly additionalContexts?: HookContext[] +} +``` + +```ts type-equiv +/** The discriminated, execution-local outcome of one tool call. */ +type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure +``` + +结果仅承载产出。调用身份保留在不可变的 `ToolExecution` 上,后者伴随结果经过每个钩子,并出现在持久化的 `tool/call` / `tool/result` 会话事件上,因此包装层无法创建第二个相互矛盾的身份。规范的 `value` 仅存在于执行期间:循环只持久化 `content`、`error` 和 `meta`,`tool/code-dispatch` 则存储有界摘要。回放可以重现展示,却无法重建中间值。 + +成功时,注册表会快照并校验函数体返回值,将其冻结,然后调用纯渲染器;对于直接的外层调用,还会调用可选的元数据投影器。注册表会在 `tools/result` 之前另行物化持久展示字段;无效值、渲染器/投影器失败或非 JSON 展示都会转为 JSON 安全的 `isError`。因此,最终实时观察者能看到精确的执行期值,以及可安全用于后续持久追加的字段。 + +在得到最终内容之前,注册表会物化候选结果;若内容、结构化错误、附加上下文或展示元数据无法物化,则会转为仍可到达 `finalizeContent` 的 JSON 安全 `isError` 结果。注册表恰好调用该回调一次,随后在 `tools/result` 之前立即物化并冻结已接受的结果,因此实时观察到的产出可安全用于后续持久化的 `tool/result` 追加。 + +每个拦截 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 } + | { kind: 'ask'; reason?: string } +``` + +```ts type-equiv +/** + * Post-dispatch decision: accept, replace one projection, attach context for the + * next request, or block by turning corrective feedback into an error result. + */ +type PostToolDecision = + | { kind: 'accept'; content?: ContentBlock[]; value?: never; additionalContexts?: HookContext[] } + | { kind: 'accept'; value: JsonValue; content?: never; additionalContexts?: HookContext[] } + | { kind: 'block'; feedback: ContentBlock[]; additionalContexts?: HookContext[] } +``` + +调用 `next()` 获取默认决策,或直接返回一个决策以短路。前置策略可以 deny 或 ask;只有 `allowed-once` 才继续执行,而未授权、缺少审批通道或服务、或无 agent 的请求都会变为拒绝。Guard 仍可施加最终拒绝。参数不可被改写,因为历史记录、审计、UI 和执行必须保持一致。 + +后置策略可以替换内容或值,但不能同时替换两者。替换内容会保留规范值和现有元数据;替换值会重新校验并重新计算内容/元数据;阻止会移除值,并转为包含纠正反馈的 `isError`。内容替换是展示策略,而非保密策略;需要隐藏程序化值的监听器必须阻止或替换该值。`tools/result` 在归一化后接收冻结的执行和结果;观察者无法对其进行变换,观察者的失败也会被隔离。未知工具和抛出异常的工具都会变为结构化错误(`ToolNotFoundError` 映射为 `UNKNOWN_TOOL`),调用失败但不终止当前轮次。 + +## 已强制执行的原始 JSON Schema 子集 + +subagent、工作流、MCP 和动态注册提供的原始 schema 使用作者侧 DSL 在协议层的对应表示。`assertSupportedJsonSchema()` 接受任意 JSON 根,`validateJsonSchemaValue()` 强制执行该 schema,`JsonSchemaError` 则报告每条不受支持或格式错误的 schema 路径。仅含注解的空节点表示不受约束的无损 JSON。`oneOf` 至少要求两个分支,且一个值必须恰好匹配其中一个。仍要求对象根的消费方调用 `assertObjectJsonSchema()` 并携带 `ObjectJsonSchema`;这样,subagent/工作流中由调用方定义的结构化输出可以继续以对象为根,而不会限制共享词汇。 + +```ts type-equiv +/** Scalar JSON values supported by `enum` and `const`. */ +type JsonSchemaScalar = string | number | boolean | null +``` + +```ts type-equiv +/** Single-type keywords accepted by the enforced subset. */ +type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null' +``` + +```ts type-equiv +/** + * One raw JSON Schema node in the enforced subset. The optional fields express + * the external wire shape; {@link assertSupportedJsonSchema} rejects invalid + * combinations before a caller treats the node as trusted. + */ +interface JsonSchemaNode { + /** Omit with no constraints for any JSON value, or use `oneOf`. */ + type?: JsonSchemaType + /** Exactly one branch must validate; at least two branches are required. */ + oneOf?: JsonSchemaNode[] + /** Nested property schemas (`type: 'object'` only). */ + properties?: Record<string, JsonSchemaNode> + /** Required property names; each must appear in `properties`. */ + required?: string[] + /** `false` rejects undeclared keys; absent/`true` follows JSON Schema's open default. */ + additionalProperties?: boolean + /** Item schema (`type: 'array'` only); absent accepts any JSON item. */ + items?: JsonSchemaNode + /** Allowed values for a scalar node. */ + enum?: JsonSchemaScalar[] + /** The single allowed value for a scalar node. */ + const?: JsonSchemaScalar + /** Annotation, ignored for validation. */ + description?: string + /** Annotation, ignored for validation. */ + title?: string + /** Annotation, ignored for validation but required to be lossless JSON. */ + default?: JsonValue + /** Annotation, ignored for validation but required to be lossless JSON. */ + examples?: JsonValue +} +``` + +```ts type-equiv +/** A consumer-constrained object-rooted schema. */ +type ObjectJsonSchema = JsonSchemaNode & { type: 'object' } +``` + +## 工具展示 UI 词汇 + +工具希望其调用在 UI 中如何呈现(编辑器工具调用卡片、CLI(命令行界面)日志行),提供方无关,使工具在不依赖任何客户端协议的情况下描述自身。`presentCall`/`presentResult` 返回一个 **`card` 标签的渲染意图**——一个可辨识联合类型,UI 桥接层据此分发: + +- `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 可以派生围栏 ` ```console ` 回退)、或 `{ card: 'diff', title?, diffs }`(已完成的文件变更→要展示的变更,通常是从变更前后内容计算出带上下文行的已应用 hunk,或在没有前像时的整文件 diff)。已完成视图会替换待执行视图,因此变更工具即使与调用时的片段重复也要返回 diff 结果。 + +`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)固定;TUI 和 host/client 运行时将这套中性词汇投影为各自的视图。 + +完整的展示字段文档见 [`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 new file mode 100644 index 0000000000..66cb12815e --- /dev/null +++ b/docs/core-data-structures/user-interaction.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 798a9790f424683775284a98421be08e6e1399e3 +user-interaction.zh.md: 12bfcffe4fe4caaacb54e90126eac55e333d64a5 diff --git a/docs/core-data-structures/user-interaction.md b/docs/core-data-structures/user-interaction.md index e010b48987..798a9790f4 100644 --- a/docs/core-data-structures/user-interaction.md +++ b/docs/core-data-structures/user-interaction.md @@ -1,6 +1,8 @@ # User Interaction -The user-interaction seam of [dsh-user-interaction](../../packages/ui/user-interaction). It is the provider-neutral vocabulary a tool or permission plugin uses when it needs the human to answer before the agent can continue. UI surfaces provide the active `UserInteractionProvider`: `dsh-tui` uses keyboard-driven overlays, and `dsh-acp` maps questions to ACP form elicitations. +English | [中文](user-interaction.zh.md) + +The user-interaction seam of [dsh-user-interaction](../../packages/ui/user-interaction). It is the provider-neutral vocabulary a tool or permission plugin uses when it needs the human to answer before the agent can continue. UI surfaces provide the active `UserInteractionProvider`; `dsh-tui` uses keyboard-driven overlays and the host runtime relays requests to its connected client. Source: [`packages/ui/user-interaction/src/index.ts`](../../packages/ui/user-interaction/src/index.ts) @@ -93,7 +95,7 @@ interface UserInteractionProvider { ## Errors -`UserInteractionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `NO_PROVIDER`, `ASK_ABORTED`, or ACP-side cancellation. +`UserInteractionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. ```ts type-equiv /** Stable error taxonomy for user-interaction failures. */ diff --git a/docs/core-data-structures/user-interaction.zh.md b/docs/core-data-structures/user-interaction.zh.md new file mode 100644 index 0000000000..12bfcffe4f --- /dev/null +++ b/docs/core-data-structures/user-interaction.zh.md @@ -0,0 +1,108 @@ +# 用户交互 + +[English](user-interaction.md) | 中文 + +[dsh-user-interaction](../../packages/ui/user-interaction) 的用户交互 seam。它是工具或权限插件需要人类回答后 agent(智能体)才能继续时所使用的、提供方无关的词汇。UI surface 提供活跃的 `UserInteractionProvider`;`dsh-tui` 使用键盘驱动的 overlay,host 运行时把请求转发给它连接的客户端。 + +源码:[`packages/ui/user-interaction/src/index.ts`](../../packages/ui/user-interaction/src/index.ts) + +## 问题选项 + +`AskUserQuestionOption` 是可选择项的形状。`label` 是面向用户的选项文字,同时也是面向模型的选中值;`description` 是可选的 UI 帮助文本。 + +```ts type-equiv +/** One selectable answer offered to the user. */ +interface AskUserQuestionOption { + /** User-facing label. */ + label: string + /** Optional extra context rendered by capable UIs. */ + description?: string +} +``` + +## 问题条目 + +`AskUserQuestionItem` 是请求中的一个问题。调用方提供稳定的 `id`,它会随答案原样返回,使批量问题仍可路由。可选的 `detail` 携带辅助文本;提供方会将其随问题渲染,但不会放入可选 option label。 + +```ts type-equiv +/** One question in a user-interaction request. */ +interface AskUserQuestionItem { + /** 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. */ + options?: AskUserQuestionOption[] + /** Whether more than one option may be selected. Defaults to single-select. */ + multiSelect?: boolean +} +``` + +## 提问请求 + +`AskUserQuestionRequest` 是跨包(package)的请求。`questions` 是数组,这样 UI 可以在一个流程中呈现相关提示,同时保持每个回答有稳定的 id。 + +```ts type-equiv +/** Request for a human answer. */ +interface AskUserQuestionRequest { + /** Questions to display. */ + questions: AskUserQuestionItem[] + /** Calling agent, when the request came from an agent tool call. */ + agent?: Agent + /** Abort signal for the owning tool/step. */ + signal?: AbortSignal +} +``` + +## 回答 + +提供方为每个问题 id 返回一个回答项。`selected` 包含选中的选项标签,`custom` 在用户输入自由文本时携带「其他」回答。当 `custom` 存在时,`selected` 为空;自定义文本是对选中项的覆盖,而非补充。UI 也可以使用 `selected` 为空且不含 `custom` 的回答项,在其余问题均已完成的批次中保留被跳过的问题。 + +```ts type-equiv +/** Answer to one question. */ +interface AskUserQuestionAnswerItem { + /** The answered question id. */ + id: string + /** Selected option labels. Empty for custom or unanswered choices. */ + selected: string[] + /** Optional free-text "Other" answer. */ + custom?: string +} +``` + +```ts type-equiv +/** The human's answer. */ +interface AskUserQuestionAnswer { + /** Structured answers keyed by question id. */ + answers: AskUserQuestionAnswerItem[] +} +``` + +## 提供方 + +同一上下文中只能有一个活跃的提供方。提供方注册绑定到 effect,因此 HMR(热模块替换)或 dispose(资源释放)会移除当前活跃的 UI。 + +```ts type-equiv +/** UI-side provider for user questions. */ +interface UserInteractionProvider { + ask(request: AskUserQuestionRequest): Promise<AskUserQuestionAnswer> +} +``` + +## 错误 + +`UserInteractionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。 + +```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) + this.name = 'UserInteractionError' + } +} +``` diff --git a/docs/core-data-structures/web.i18n.yaml b/docs/core-data-structures/web.i18n.yaml new file mode 100644 index 0000000000..912c1decbe --- /dev/null +++ b/docs/core-data-structures/web.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 20d07240c9d9fea2f1f5abbac810f349a3e81f9b +web.zh.md: 68ceed04bb0b80f32ed704118f1fc25f48a0da70 diff --git a/docs/core-data-structures/web.md b/docs/core-data-structures/web.md index 22909b8dfb..20d07240c9 100644 --- a/docs/core-data-structures/web.md +++ b/docs/core-data-structures/web.md @@ -1,5 +1,7 @@ # Web Access +English | [中文](web.zh.md) + The web access seam — a [capability seam](../../.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md) that spans **two capabilities** (search and fetch) on one `ctx.web` service, split across packages: interface ([dsh-web](../../packages/web/web), `ctx.web` + the provider registries), implementations ([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)), and consumer ([dsh-tool-web](../../packages/web/tool-web), the `web_search`/`web_fetch` tool schemas). Web is **one optional capability**, not part of the agent-loop spine — so its vocabulary lives here, not in [core.md](core.md). A search-provider swap does not change how the model asks for a query, and a fetch-implementation swap does not change how the model asks for a URL. Source: [`packages/web/web/src/types.ts`](../../packages/web/web/src/types.ts) diff --git a/docs/core-data-structures/web.zh.md b/docs/core-data-structures/web.zh.md new file mode 100644 index 0000000000..68ceed04bb --- /dev/null +++ b/docs/core-data-structures/web.zh.md @@ -0,0 +1,135 @@ +# Web 访问 + +[English](web.md) | 中文 + +Web 访问 seam 是一个[能力 seam](../../.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md),在同一个 `ctx.web` 服务上横跨**两项能力**(search 与 fetch),并拆分到多个包(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) 中。更换 search 提供方不会改变模型请求 query 的方式,更换 fetch 实现也不会改变模型请求 URL 的方式。 + +源码:[`packages/web/web/src/types.ts`](../../packages/web/web/src/types.ts) + +## 为什么两项能力合为一个 seam + +搜索与抓取既不共享请求 schema,也不共享业务逻辑,但它们被有意设计为同一个 `ctx.web` 中间层:一个提供方选择策略的所有者、一套 abort/error 词汇、一个面向产品的「此 harness 如何访问 Web」配置界面。代价是服务上并行的 `searchX`/`fetchX` 方法对;这种并行是有意为之,而非遗漏的提取。提供方注册的是**能力**(`WebSearchProvider` 或 `WebFetchProvider`),而非工具;面向模型的名称、schema、提示词引导与展示全部集中在唯一的消费方 `dsh-tool-web` 中。 + +## 搜索请求与结果 + +面向模型的工具参数仅为一个 `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. 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 +} +``` + +`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 +} +``` + +## 抓取请求与结果 + +```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 +} +``` + +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 +} +``` + +`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 } +``` + +## 提供方可用性 + +提供方的 `available(): boolean` 是一个廉价的本地检查(凭证是否存在、配置是否可解析),**禁止发起网络调用**。它是执行时选择的输入,而非健康检查系统:`search()`/`fetch()` 读取它以选出可用的提供方,选择失败以结构化的 `WebError` 呈现给调用方路由——其 code 和 message 携带可分支的细节(缺失的 id 或有歧义的候选集)。 + +选择从不依赖注册顺序、配置顺序或 HMR(热模块替换)顺序:一项能力要么有显式的提供方 id(配置 `searchProvider`/`fetchProvider`,或填充同一字段的对应环境变量),要么在恰好只有一个可用提供方注册时自动选择;多个可用提供方且未配置 id 时为 `WEB_PROVIDER_AMBIGUOUS`,而非先注册先赢。 + +## 错误 + +`WebError extends HarnessError`([core.md](core.md) 错误分类体系),带有 `code: string`(开放式,与其他 seam 的错误一致——`LlmError`、`SubagentError`),而非封闭联合类型:提供方可以在不修改 `dsh-web` 的情况下抛出自己的 code,消费方必须容忍未知 code。code 按所有者划分。seam 中立的 code 由 `WebService` 选择逻辑和共享契约抛出:`WEB_PROVIDER_UNAVAILABLE`、`WEB_PROVIDER_CONFIGURED_MISSING`、`WEB_PROVIDER_CONFIGURED_UNAVAILABLE`、`WEB_PROVIDER_AMBIGUOUS`、`WEB_DUPLICATE_PROVIDER`(注册时的编程错误,类似 `LlmService` 的 `DUPLICATE_ADAPTER`)、`WEB_ABORTED`,以及 `WEB_PROVIDER_ERROR`(提供方自身故障通过 seam 暴露的兜底 code,包括网络/传输失败——DNS、连接被拒、TLS)。抓取传输层 code 由 `dsh-web-fetch-local` 实现拥有,不同的抓取后端无需抛出它们:`WEB_INVALID_URL`、`WEB_BLOCKED_URL`、`WEB_REDIRECT_BLOCKED`、`WEB_FETCH_TOO_LARGE`、`WEB_FETCH_TIMEOUT`、`WEB_UNSUPPORTED_CONTENT_TYPE`。 + +## 服务 + +`WebService` 注册搜索与抓取提供方,以 `WEB_DUPLICATE_PROVIDER` 拒绝重复 id,并在执行时以结构化的选择错误解析提供方。本地抓取后端仅接受 HTTP(S)、拒绝凭证、限制重定向次数、字节数、字符数和时间、对每一跳同源重定向重新校验,并解码 body;展示由工具负责。私有网络阻断尚未实现,因此请勿在可触及敏感内部目标的环境中启用 `web_fetch`。 diff --git a/docs/core-data-structures/workflow.i18n.yaml b/docs/core-data-structures/workflow.i18n.yaml new file mode 100644 index 0000000000..492a9bea08 --- /dev/null +++ b/docs/core-data-structures/workflow.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 8d271b89e71de6f6bef548aa8da61402ef9ada6e +workflow.zh.md: b8ed699eb52d9f0cef23c513f625de7e82c46c45 diff --git a/docs/core-data-structures/workflow.md b/docs/core-data-structures/workflow.md index 8d8e47fc79..8d271b89e7 100644 --- a/docs/core-data-structures/workflow.md +++ b/docs/core-data-structures/workflow.md @@ -1,5 +1,7 @@ # Workflow +English | [中文](workflow.zh.md) + The workflow seam — an agent running a model-written orchestration SCRIPT that fans out subagents. Like [subagent](subagent.md) it is **one optional capability**, not part of the agent-loop spine, so its vocabulary lives here rather than in [core.md](core.md). Unlike the subagent registry it takes the bash shape: ONE engine implementation per context provides `ctx.workflows`; there is no named-provider registry (a second engine is a plugin swap, not a co-resident). Interface: [dsh-workflow](../../packages/workflow/workflow) (`ctx.workflows` + the vocabulary below). The implementation is [dsh-workflow-workerthread](../../packages/workflow/workflow-workerthread) (a `node:worker_threads` engine — one worker per run, the script's vm context inside it); the model-facing consumer is [dsh-tool-workflow](../../packages/workflow/tool-workflow). The proposal and rationale: [the dynamic-workflows Agent Note](../../.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md). diff --git a/docs/core-data-structures/workflow.zh.md b/docs/core-data-structures/workflow.zh.md new file mode 100644 index 0000000000..b8ed699eb5 --- /dev/null +++ b/docs/core-data-structures/workflow.zh.md @@ -0,0 +1,132 @@ +# 工作流 + +[English](workflow.md) | 中文 + +工作流 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` 引擎——每个 run 一个 worker,脚本的 vm 上下文位于其中);面向模型的消费方是 [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) + +## 启动请求 + +调用方启动 run 时提出的请求。普通工作流工具根据模型的 `{ 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 <json-value>`). */ + 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 +} +``` + +## 工作流的身份标识:`WorkflowMeta` + +作为数据附在启动请求上的身份块(工具的 `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[] +} +``` + +## 终态结果:`WorkflowResult` + +一次运行的结果,由 `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 +} +``` + +## 活跃运行:`WorkflowRun` + +脚本执行期间消费方持有的句柄。消费方 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<WorkflowResult> + /** 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<void> +} +``` + +## 失败纪律:`WorkflowError.fatal` + +脚本内部的钩子误用:错误参数、未知或延迟的 `agent()` 选项、超出[结构化输出子集](../../packages/core/tools/README.md)的 schema、触发的上限、seam 启动失败、取消,都会抛出 `fatal: true` 的 `WorkflowError`。`parallel()`/`pipeline()` 组合器对 fatal 错误直接重新抛出,而非将该项映射为 `null`:一个拼写错误的选项必须让脚本大声失败,绝不能消融为看似普通子 agent 失败的结果。逐项的 `null` 保留给子运行失败(非 `completed` 的 stop reason)和阶段内的普通脚本错误。 + +## 事件 + +`workflow/*` 事件(`workflow/start`、`workflow/phase`、`workflow/log`、`workflow/agent-start`、`workflow/agent-end`、`workflow/end`,见[事件目录](../cordis-catalog/events.md))是**仅供观察**的 emit,携带数据快照:每个 payload 以 `WorkflowRunInfo`(id + meta)开头,而非活跃的 `WorkflowRun`,因此订阅者无法获得 `cancel`/`dispose`;`workflow/end` 刻意省略 result value(观察结果的监听器不得收到调用方 result 的可变别名)。每次 emit 对每个监听器隔离:抛出异常的订阅者被记录日志但不传播,不会饿死在它之后注册的监听器;每个监听器收到自己的 payload 克隆,因此修改它既不会损坏引擎也不会影响其他监听器。这种隔离方式与 `subagent/start`/`subagent/end` 一致。 diff --git a/docs/defensive-patterns.i18n.yaml b/docs/defensive-patterns.i18n.yaml new file mode 100644 index 0000000000..96c938a74f --- /dev/null +++ b/docs/defensive-patterns.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +defensive-patterns.md: c69094db461048f5dbca5f8bdd1fb5581b08a962 +defensive-patterns.zh.md: eb57f035ad0bd67e62e285d451502d41e4efc2bc diff --git a/docs/defensive-patterns.md b/docs/defensive-patterns.md index a6fe43ef69..c69094db46 100644 --- a/docs/defensive-patterns.md +++ b/docs/defensive-patterns.md @@ -1,5 +1,7 @@ # Defensive patterns +English | [中文](defensive-patterns.zh.md) + Hard-won bug-class rules: each pattern below is a class of defect that actually shipped or nearly shipped here, stated as the rule that prevents its recurrence. Read this before writing lifecycle, concurrency, subprocess, or teardown code. Test-tier counterparts (real entry path, world-verification, resource ownership) are in [testing.md](testing.md). ## Report orthogonal outcomes independently diff --git a/docs/defensive-patterns.zh.md b/docs/defensive-patterns.zh.md new file mode 100644 index 0000000000..eb57f035ad --- /dev/null +++ b/docs/defensive-patterns.zh.md @@ -0,0 +1,29 @@ +# 防御性模式 + +[English](defensive-patterns.md) | 中文 + +来之不易的缺陷类别规则:下面每条模式都是本项目实际发布或差点发布的一类缺陷,以防止其复发的规则形式陈述。在编写生命周期、并发、子进程或清理代码之前请先阅读本文。测试层面的对应规则(真实入口路径、world 验证、资源归属)见 [testing.md](testing.md)。 + +## 正交结果独立上报 + +一个结果可以同时具有多重性质:进程可能既超时又以 exit 0 退出,因为它捕获了信号。每个独立事实(`timedOut`、`signal`、`exitCode`)都应独立暴露;切勿将某个 flag 的上报嵌套在另一个 flag 的分支内,否则调用方会把一次被截断的运行误读为正常成功。 + +## 跨 seam 契约两侧都要遵守 + +当一个接口文档记录了两种合法的信号方式时——例如适配器可以通过从 `stream()` 抛出异常来报告失败,也可以通过以 `finish {kind:'error'|'aborted'}` 分片结束流来报告——消费方必须同时处理两种路径,而不是只处理第一个实现恰好使用的那种。依赖库的适配器可能无法在流中途抛出异常,只能走带内路径;如果 agent loop(智能体循环)只捕获抛出的异常,就会把提供方的 401 错误变成一个正常完成的轮次。请在类型定义处记录契约;通过真实消费方测试每个分支。 + +## 异步状态不是同步状态 + +`agent.followup()` 不会在返回前翻转状态;后台任务的完成与轮次边界存在竞争;`reader.close()` 在 EOF 和 dispose(资源释放)两种情况下都会触发。切勿基于一个刚刚请求的状态来控制流程——应以实际触发的事件/promise(`agent/status`、`task.done`)驱动生命周期,并观察状态转换(先看到 `running` 再看到 `idle`),而不是把状态当作逐次 `followup()` 的结果:多次排队的 `followup()` 会在同一个 `running` 区间内连续运行多个轮次,而取消或资源释放可能丢弃尚未启动的项。这条守则是双向的:如果等待的转换永远不会发生(EOF 时没有提交过任何工作 → 永远不会进入 `running`),等待就会挂起——请显式处理「无需等待」的分支。 + +## Dispose 必须达到完全停稳,而不仅仅是请求停止 + +一个清理流程如果发出 kill/abort 后就返回、而不等待工作实际停止,就会留下孤儿进程。请让清理逻辑异步化并 await 子进程退出(kill → await `done`),并在 kill 之前关闭监听器/通知注册表,使迟到的完成事件保持静默。测试应证明 dispose 确实等待了(`await fiber.dispose()` 之后 pid 已不存在),而不仅仅是进程最终会死。 + +## 在边界处包容回调异常 + +用户提供的监听器如果抛出异常,不得导致它所在的 promise 被 reject,也不得饿死排在它后面的监听器。请用 try/catch 包裹分发循环并记录日志;一个行为不当的订阅者绝不能破坏核心生命周期。 + +## 绝不将环境变量或可预测路径暴露给不可信输出 + +spawn 的命令应获得一份经过清洗的 env(去除 `*KEY*`/`*SECRET*`/`*TOKEN*`),使 harness 凭证无法泄漏到输出、`env` 或溢出文件中。临时/溢出文件应使用私有(0700)目录、随机文件名和排他的仅所有者可访问打开方式(`'wx'`、`0o600`)——可预测的全局可读路径会招致符号链接竞争和信息泄露。 diff --git a/docs/development.i18n.yaml b/docs/development.i18n.yaml index 40828094ce..9d2573305e 100644 --- a/docs/development.i18n.yaml +++ b/docs/development.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 -development.md: 4294038e40aa774a006874e6641ca63eea44beeb -development.zh.md: 1f07c95dd60d0554b945c29e6e3ba8bc6ca9841a +development.md: f706d54764bbf79d1f13ccb4c412e7b5717b1edb +development.zh.md: 15f5ae0c514ac412c302a99cb0a662acce510c44 diff --git a/docs/development.md b/docs/development.md index 4294038e40..f706d54764 100644 --- a/docs/development.md +++ b/docs/development.md @@ -9,7 +9,7 @@ This onboarding guide helps project contributors get started with the local envi - Node.js supports 22.19+ and 24+. CI covers 22.19, 24, and 26; see the [Node engine floor Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md). - Corepack-enabled pnpm. The repo pins `pnpm@11.7.0` in `package.json`; run `corepack enable` if `pnpm --version` does not resolve through Corepack. - Git. -- Optional: a DeepSeek API key for the TUI/Headless/ACP agent demos and real-API e2e tests. +- Optional: a DeepSeek API key for the TUI, headless, and ACP automation demos and real-API e2e tests. ## First-time setup @@ -142,7 +142,7 @@ The self-referential cordis-agent demo can inspect and modify its live plugin ru pnpm run demo:cordis ``` -The ACP server agent demo exposes the agent over JSON-RPC stdio and also needs `DEEPSEEK_API_KEY`: +The ACP automation server exposes fresh agent sessions over JSON-RPC stdio and also needs `DEEPSEEK_API_KEY`: ```sh pnpm run demo:acp diff --git a/docs/development.zh.md b/docs/development.zh.md index 1f07c95dd6..15f5ae0c51 100644 --- a/docs/development.zh.md +++ b/docs/development.zh.md @@ -9,7 +9,7 @@ - Node.js 支持 22.19+ 与 24+。CI 覆盖 22.19、24 和 26;见 [Node 引擎下限 Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md)。 - 启用了 Corepack 的 pnpm。仓库在 `package.json` 中固定使用 `pnpm@11.7.0`;如果 `pnpm --version` 无法通过 Corepack 解析,请先运行 `corepack enable`。 - Git。 -- 可选:一个 DeepSeek API key,用于 TUI/Headless/ACP(Agent Client Protocol) agent(智能体)演示和真实 API 的 e2e 测试。 +- 可选:一个 DeepSeek API key,用于 TUI、headless 和 ACP(Agent Client Protocol)自动化 agent(智能体)演示以及真实 API 的 e2e 测试。 ## 首次搭建 @@ -142,7 +142,7 @@ pnpm run demo:tui pnpm run demo:cordis ``` -ACP 服务器 agent 演示通过 JSON-RPC stdio 暴露 agent,同样需要 `DEEPSEEK_API_KEY`: +ACP 自动化服务器通过 JSON-RPC stdio 提供全新 agent 会话,同样需要 `DEEPSEEK_API_KEY`: ```sh pnpm run demo:acp diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index b36d390f55..bba7989556 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -11,31 +11,32 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/cancel-requested` | `emit` | [`packages/core/agent/src/types.ts:350`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session) | | `agent/created` | `emit` | [`packages/core/agent/src/types.ts:285`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | | `agent/disposed` | `emit` | [`packages/core/agent/src/types.ts:294`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | -| `agent/error` | `emit` | [`packages/core/agent/src/types.ts:498`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session), `runtime`, [`tui`](../packages/ui/tui) | +| `agent/error` | `emit` | [`packages/core/agent/src/types.ts:498`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `apiproxy`, [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | | `agent/inbox/dequeue` | `emit` | [`packages/core/agent/src/types.ts:326`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent) | | `agent/inbox/discard` | `emit` | [`packages/core/agent/src/types.ts:340`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent) | | `agent/inbox/enqueue` | `emit` | [`packages/core/agent/src/types.ts:316`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | | `agent/post-step` | `serial` | [`packages/core/agent/src/types.ts:448`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`compact-basic`](../packages/compact/compact-basic), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy) | | `agent/pre-step` | `serial` | [`packages/core/agent/src/types.ts:379`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`time-context`](../packages/context/time-context), [`user-approval`](../packages/ui/user-approval) | -| `agent/prompt-submit` | `waterfall` | [`packages/core/agent/src/types.ts:395`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`acp`](../packages/ui/acp), [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | +| `agent/prompt-submit` | `waterfall` | [`packages/core/agent/src/types.ts:395`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | | `agent/request` | `waterfall` | [`packages/core/agent/src/types.ts:409`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/types.ts:463`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compact-basic`](../packages/compact/compact-basic), [`llm-retry`](../packages/llm/llm-retry), [`plan-mode`](../packages/plan/plan-mode) | | `agent/session-prefix` | `waterfall` | [`packages/core/agent/src/types.ts:424`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`tool-skill`](../packages/skill/tool-skill), [`workspace-context`](../packages/context/workspace-context) | | `agent/session-start` | `emit` | [`packages/core/agent/src/types.ts:363`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | -| `agent/status` | `emit` | [`packages/core/agent/src/types.ts:303`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), [`goal-session`](../packages/goal/goal-session), `runtime`, [`tui`](../packages/ui/tui) | +| `agent/status` | `emit` | [`packages/core/agent/src/types.ts:303`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `apiproxy`, [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | | `agent/step-result` | `waterfall` | [`packages/core/agent/src/types.ts:436`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | | `agent/turn-continuation` | `waterfall` | [`packages/core/agent/src/types.ts:474`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode) | | `agent/turn-stop` | `serial` | [`packages/core/agent/src/types.ts:485`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`tool-goal`](../packages/goal/tool-goal) | -| `approval/request` | `waterfall` | [`packages/ui/user-approval/src/index.ts:30`](../packages/ui/user-approval/src/index.ts) | [`user-approval`](../packages/ui/user-approval) (`waterfall`) | [`acp`](../packages/ui/acp) | -| `commands/change` | `emit` | [`packages/ui/commands/src/index.ts:103`](../packages/ui/commands/src/index.ts) | [`commands`](../packages/ui/commands) (`events.dispatch`) | [`acp`](../packages/ui/acp), [`tui`](../packages/ui/tui) | +| `approval/request` | `waterfall` | [`packages/ui/user-approval/src/index.ts:30`](../packages/ui/user-approval/src/index.ts) | [`user-approval`](../packages/ui/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp) | +| `commands/change` | `emit` | [`packages/ui/commands/src/index.ts:103`](../packages/ui/commands/src/index.ts) | [`commands`](../packages/ui/commands) (`events.dispatch`) | [`tui`](../packages/ui/tui) | +| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | [`storage-domain`](../packages/storage/storage-domain), [`workspace`](../packages/workspace/workspace) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:62`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-policy`](../packages/fs/fs-policy) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:71`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`emit`) | [`fs-policy`](../packages/fs/fs-policy) | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:54`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-policy`](../packages/fs/fs-policy) | | `goal/changed` | `emit` | [`packages/goal/goal/src/types.ts:167`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-session`](../packages/goal/goal-session) | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:52`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`agent-loop`](../packages/core/agent-loop), [`llm`](../packages/llm/llm), [`llm-replay`](../packages/support/llm-replay), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-title`](../packages/session-title/session-title) | -| `session/created` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`llm-retry`](../packages/llm/llm-retry), `runtime`, [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`user-approval`](../packages/ui/user-approval) | -| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:89`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `runtime`, [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:101`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/ui/acp), [`cli-demo`](../packages/examples/cli-demo), [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), `runtime`, [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title), [`token-meter`](../packages/llm/token-meter), [`tui`](../packages/ui/tui), [`user-approval`](../packages/ui/user-approval), [`workspace-context`](../packages/context/workspace-context) | +| `session/created` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `apiproxy`, [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`llm-retry`](../packages/llm/llm-retry), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`user-approval`](../packages/ui/user-approval) | +| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:89`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `apiproxy`, [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:101`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), `apiproxy`, [`cli-demo`](../packages/examples/cli-demo), [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title), [`token-meter`](../packages/llm/token-meter), [`tui`](../packages/ui/tui), [`user-approval`](../packages/ui/user-approval), [`workspace-context`](../packages/context/workspace-context) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:111`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence`](../packages/session-persistence/session-persistence) | | `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:139`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`jsonrpc`](../packages/ui/jsonrpc), [`subagent`](../packages/subagent/subagent) | | `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:113`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`subagent`](../packages/subagent/subagent), [`tool-subagent`](../packages/subagent/tool-subagent) | @@ -60,7 +61,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event string | Dispatchers | Listeners | | --- | --- | --- | | `internal/dispatch` | - | [`compact`](../packages/compact/compact), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission`](../packages/ui/permission), [`plan-mode`](../packages/plan/plan-mode), [`pty-local`](../packages/pty/pty-local), `runtime`, [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval), [`workflow`](../packages/workflow/workflow) | -| `internal/plugin` | - | `webserver` | +| `internal/plugin` | - | `hmr`, `modules`, `webserver` | | `internal/status` | - | [`agent`](../packages/core/agent) | | `slots/changed` | `runtime` (`emit`) | - | diff --git a/docs/glossary.i18n.yaml b/docs/glossary.i18n.yaml new file mode 100644 index 0000000000..b63e41b87b --- /dev/null +++ b/docs/glossary.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +glossary.md: 0270a2d0dba558483e8e458a932a27b0151f2c93 +glossary.zh.md: ed3009a054815f1c7165fc322e44cc9521527643 diff --git a/docs/glossary.md b/docs/glossary.md index e290543d2c..0270a2d0db 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -1,5 +1,7 @@ # Glossary +English | [中文](glossary.zh.md) + Domain vocabulary for the DeepSeek Harness SDK uses one canonical term per concept. Terms link to their entries with standard Markdown anchors; implementation detail stays in package READMEs and Agent Notes. FIXME(glossary-completeness): Expand this glossary before the first release so it covers the SDK's other core and capability subsystems, not only agent scope. @@ -19,7 +21,7 @@ FIXME(glossary-completeness): Expand this glossary before the first release so i ## goal - **goal** — one durable completion objective attached to an existing session, with a revisioned `active` / `paused` / `blocked` / `complete` phase and a goal-round cap; `blocked` retains a policy code and explanation. A goal is state, not a scheduler or a separate conversation; the session log remains its source of truth. -- **goal round** — one continuation cycle admitted for the current goal. The same-session driver materializes a goal round as one goal-sourced [turn](#turn), which can contain multiple steps; unrelated human turns in the same session do not consume the goal-round cap. <a id="goal-round"></a> +- **goal round** — one continuation cycle admitted for the current goal. The same-session driver materializes a goal round as one goal-sourced [turn](#turn), which can contain zero or more steps; unrelated human turns in the same session do not consume the goal-round cap. <a id="goal-round"></a> - **goal activation** — process-local permission for a continuation consumer to admit another goal round. Activation is either `armed` or `disarmed`; it is deliberately absent from durable replay, so resume and fork require a later human-authorized resume mutation through `/goal` or the model tool before automatic work. ## human command @@ -31,7 +33,7 @@ FIXME(glossary-completeness): Expand this glossary before the first release so i ## loop hierarchy - **turn** — one drain of admitted input in a session, ending after the model and its tools stop or a terminal policy intervenes. <a id="turn"></a> -- **step** — one model request plus the tool executions caused by its response; a turn contains one or more steps. <a id="step"></a> +- **step** — one model request plus the tool executions caused by its response; a turn contains zero or more steps. <a id="step"></a> - **round** — an outer policy iteration containing a turn, such as a [goal round](#goal-round) or one fresh-agent Ralph attempt. Round counters belong to that policy and do not count every turn in a session. <a id="round"></a> ## Ralph diff --git a/docs/glossary.zh.md b/docs/glossary.zh.md new file mode 100644 index 0000000000..ed3009a054 --- /dev/null +++ b/docs/glossary.zh.md @@ -0,0 +1,43 @@ +# 术语表 + +[English](glossary.md) | 中文 + +DeepSeek Harness SDK 的领域词汇为每个概念规定一个规范术语。各术语通过标准 Markdown 锚点链接到相应条目;实现细节留在各包(package)的 README 与 Agent Note(agent 决策记录)中。 + +FIXME(glossary-completeness): 首次发布前扩充本术语表,使其覆盖 SDK 的其他核心与能力子系统,而非仅限于 agent scope。 + +## agent-scope + +- **scope**:按 agent(智能体)划分的注册单位。一项贡献(工具、提示词片段、变量、限制、监听器)要么是*全局的*(对所有 agent 可见),要么是*有范围的*(归属于恰好一个 [scope key](#scope-key))。只有两层,扁平结构:有范围的注册不会向下继承给 subagent;子树行为通过 [lineage](#lineage) 数据表达,从不通过 scope 结构。 +- **scope key**:scope 的不透明标识,按对象同一性比较。harness 约定:一个活跃的 agent 就是其自身 scope 的 key。<a id="scope-key"></a> +- **agent 上下文(`agent.ctx`)**:agent 的有范围上下文;通过它进行的注册既是 scope 可见的,也是 scope 生命周期的(同一事实决定两者),其上的监听器参与该 agent 的 scope 过滤分发。注册表主体事件可以在各自的事件契约下保持故意不过滤。 +- **scope carrier**:scope 过滤分发所携带的 `thisArg`(由 `scopeTarget` 构建);其过滤器放行无标签监听器加上主体自身的监听器。*无主体*的 carrier(没有 key)只放行无标签监听器。 +- **scoped dispatch**:规则是:关于某个 agent 活动的事件以该 agent 的 carrier 进行分发。关于注册表本身的事件(如「一个工具被添加了」)属于*注册表主体*事件,保持不过滤。 +- **shadowing**:最具体者胜出的名称解析:一个有范围的工具/片段/变量仅在该 scope 内替换同名的全局对应项。这是按 agent 定制 persona 和按 agent 定制工具变体的机制。 +- **restriction / scope-local 注册**:restriction(`tools.restrict`)为单个 scope 过滤全局工具表面(多个 restriction 取交集组合);scope-local 注册在过滤之后合并。被过滤掉的全局工具既不出现在提示词中,也拒绝执行,与不存在的工具无法区分。 +- **setup window**:创建者组装 agent 有范围世界的创建时隙(`CreateAgentOptions.setup`):在 scope 和 agent 对象已存在、但 agent 或会话尚未发布、`agent/session-start` 尚未触发、首次提示词尚未组装之前。setup 只做注册,从不驱动 agent。 +- **lineage**:以数据形式携带的父子关系事实(`parentSession`、持久的 `delegationDepth`、运行时 `subagentDepth`);从不影响可见性。<a id="lineage"></a> + +## 目标 + +- **目标**:附着在现有会话上的单个持久完成目标,带有按修订号演进的 `active` / `paused` / `blocked` / `complete` 阶段和 Goal Round 上限;`blocked` 保留策略代码与说明。目标是一种状态,不是调度器,也不是一段独立对话;会话日志仍是其真源。 +- **Goal Round**:为当前目标接纳的一次续行周期。同会话驱动器将 Goal Round 具体化为一个来源为目标的[轮次](#turn),其中可包含零个或多个步骤;同一会话中无关的人类轮次不消耗 Goal Round 上限。<a id="goal-round"></a> +- **目标激活**:续行消费方接纳下一个 Goal Round 的进程本地权限。激活态为 `armed` 或 `disarmed`;它有意不参与持久回放,因此恢复和 fork 后,必须由人类随后通过 `/goal` 或模型工具授权恢复变更,自动工作才可开始。 + +## 人类命令 + +- **人类命令**:以斜杠开头的指令,由面向人类的适配器通过 `ctx.commands` 解释并执行,不会成为模型消息。它既不同于面向模型的工具,也不同于通过 `ctx.bash` 执行 shell 命令。 +- **命令平面**:由 UI 适配器与命令插件拥有的发现、解析、分发、取消和结果渲染。除非处理器另行改变持久领域,否则命令输出属于 UI 状态。 +- **目标命令**:`/goal` 是由 `dsh-command-goal` 提供的人类命令;它直接观察或更改当前目标,而目标领域拥有每条持久且模型可见的记录。 + +## 循环层级 + +- **轮次**:会话中一次对已接纳输入的排空过程,在模型及其工具停止工作或终止策略介入后结束。<a id="turn"></a> +- **步骤**:一次模型请求,以及由模型响应引发的工具执行;一个轮次包含零个或多个步骤。<a id="step"></a> +- **Round**:承载一个轮次的外层策略迭代,例如一个 [Goal Round](#goal-round) 或一次使用全新 agent 的 Ralph 尝试。Round 计数器归该策略所有,并不统计会话中的每个轮次。<a id="round"></a> + +## Ralph + +- **Ralph 循环**:一次面向不可变目标的前台全新 agent 工作流运行。它是由工作流和 subagent 原语组合而成的面向模型的工具策略,不是同会话目标、agent loop(智能体循环)模式、调度器或通用工作流脚本功能。<a id="ralph-loop"></a> +- **Ralph Round**:[Ralph 循环](#ralph-loop)中的一个全新子会话。子会话不接收父会话或此前子会话的对话种子;共享工作区和一份有界的 [Ralph 交接](#ralph-handoff)承载跨 Round 的状态。<a id="ralph-round"></a> +- **Ralph 交接**:从一个仍需继续的 Ralph Round 传给下一个 Ralph Round 的规范化、有界结构化报告,包含状态、摘要、证据、后续步骤和阻塞说明。它补充共享工作区,而不取代工作区的权威地位。<a id="ralph-handoff"></a> diff --git a/docs/graph-atlas.md b/docs/graph-atlas.md index 6050c4a60e..f4a62dac87 100644 --- a/docs/graph-atlas.md +++ b/docs/graph-atlas.md @@ -19,7 +19,6 @@ The process decision behind this index is recorded in [the documentation graph A | [event producer/consumer matrix](event-producer-consumer.md) | `hybrid generated` | | [agent turn and step lifecycle](agent-lifecycle.md) | `curated` | | [tool execution pipeline](tool-execution-pipeline.md) | `curated` | -| [ACP snapshot replay](../packages/ui/acp/snapshot-replay.md) | `curated` | Regenerate with `pnpm run gen-doc-graphs`; verify freshness with `pnpm run verify-doc-graphs`. diff --git a/docs/i18n/README.i18n.yaml b/docs/i18n/README.i18n.yaml index d48ab803ee..602699a178 100644 --- a/docs/i18n/README.i18n.yaml +++ b/docs/i18n/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: 430c499afbbfb786928276f6348cc0cedf14f94d -README.zh.md: 7ac7f4a2a8983c753def61df6f6d86a26405a3a0 +README.md: 77d7b3210216c7c12d7d06b1ed16396d02ef1d16 +README.zh.md: de15fc3b5f30c1280ce6b38c1afd2475be7f9671 diff --git a/docs/i18n/README.md b/docs/i18n/README.md index 430c499afb..77d7b32102 100644 --- a/docs/i18n/README.md +++ b/docs/i18n/README.md @@ -40,7 +40,7 @@ The gate's limit, stated plainly: **a green gate means the pair was confirmed co **Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them): -- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, and `docs/module-graph.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list. +- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, `docs/module-graph.md`, `docs/agent-lifecycle.md`, `docs/capability-seams.md`, `docs/event-producer-consumer.md`, `docs/graph-atlas.md`, and `docs/tool-execution-pipeline.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list. - `docs/AGENTS.md` and `.agents/notes/**/AGENTS.md` — agent instructions, maintained in English only like the root `AGENTS.md`. - `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction. - [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior. diff --git a/docs/i18n/README.zh.md b/docs/i18n/README.zh.md index 7ac7f4a2a8..de15fc3b5f 100644 --- a/docs/i18n/README.zh.md +++ b/docs/i18n/README.zh.md @@ -40,7 +40,7 @@ **排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`): -- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md` 与 `docs/module-graph.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。 +- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md`、`docs/module-graph.md`、`docs/agent-lifecycle.md`、`docs/capability-seams.md`、`docs/event-producer-consumer.md`、`docs/graph-atlas.md` 与 `docs/tool-execution-pipeline.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。 - `docs/AGENTS.md` 与 `.agents/notes/**/AGENTS.md`:agent 指令,与根 `AGENTS.md` 一样只以英文维护。 - `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。 - [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。 diff --git a/docs/i18n/terminology.md b/docs/i18n/terminology.md index 74ce7ad969..ae28258b9b 100644 --- a/docs/i18n/terminology.md +++ b/docs/i18n/terminology.md @@ -52,6 +52,7 @@ | loader | loader | | | | | manifest | manifest | manifest(元数据清单) | | | | monorepo | monorepo | | | | +| Round | Round | | 回合、目标回合、Ralph 回合 | 外层策略使用 Round 时,领域层级为 Session > Round > Turn(轮次) > Step(步骤);Round 是可选的外层策略迭代,并非每个会话轮次都具有的通用层级。Goal Round 与 Ralph Round 均保留英文。一个 Round 承载一个轮次,步骤隶属于该轮次;明确的零步骤轮次仍保持原义。 | | schema | schema | | | | | schema DSL | schema DSL | | | | | seam | seam | | | 与 `extension point` 是不同概念;根据具体语境,可译为`服务边界`或`可替换点` | @@ -103,10 +104,12 @@ | durability | 持久性 | | | | | feature requirement | 功能依赖 | | | 功能或功能选项通过 `requires` 声明的关系 | | enforcement frontier | 执行红线 | | 强制边界 | i18n 配对机制用语:manifest `required` 清单所划的门禁生效范围;与金标样例(style-samples ⑦)一致 | +| ergonomics | 易用性 / 开发体验 | | 人体工学 | API 或面向模型的接口用「易用性」;工具链或开发者工作流用「开发体验」 | | event | 事件 | | | | | event log | 事件日志 | | | | | event stream | 事件流 | | | | | event-sourced | 事件溯源 | | | 沿用 DDD 社区通行译法 | +| Executive summary | 摘要 | | | 事故复盘标题用语 | | executor | 执行器 | | | | | expected output | 预期输出 | | 金标 | 指 snapshot 比较产物;翻译语料的人工校准样例不在此列 | | extension | 扩展 | | | | @@ -131,11 +134,14 @@ | mod | 模组 | | | | | model provider | 模型提供方 | | | | | module | 模块 | | | | +| non-escalation | 非升权 | | 非升级、不可升级 | 仅用于安全与权限语境,指主体不得获得超出既有授权的权限;普通升级不适用此行 | | npm dependency | NPM 依赖 | | | `package.json` 中的包关系;`dependencies`、`devDependencies` 等字段保持原样 | +| opt-out ratio | opt-out 比例 | | 退出检查比例 | | | orphan | 遗留 | | 孤儿、孤立 | 指英文源已不存在的 `.zh.md`(如「遗留译文」);进程语境按 OS 惯用语译「孤儿进程」 | | orphan branch | 孤立分支 | | 孤儿分支 | 沿用 git 官方中文翻译 | | package | 包 | 包(package) | | 指 npm 包(`@deepseek-ai/dsh-*`);`package.json` 等代码标识保持原样 | | pairing | 配对 | | | | +| parent-subset grants | 父级子集授权 | | 父集合授权 | 指授权范围仅限于父级所持授权的子集 | | peer dependency | 对等依赖 | 对等依赖(peer dependency) | | | | permission | 权限 | | | | | persistence | 持久化 | | | | @@ -145,12 +151,14 @@ | provider | 提供方 | | | | | provider-neutral | 提供方无关 | | | | | quality gate | 质量门禁 | | | | +| quiescence | 完全停稳 | | 静默、静止状态 | 指生命周期工作全部结算后的状态 | | reasoning | 推理 | 推理(reasoning) | | 需要和 `inference` 区分时保留英文括注 | | reasoning_content | 思考内容 | | | | | registry | 注册表 | | | | | replay | 回放 | | | | | resume | 恢复 | | | | | runtime | 运行时 | | | | +| same-world subprocess | 与宿主共享文件系统和内核的子进程 | | 同世界子进程 | | | sandbox | 沙箱 | | | | | service | 服务 | | | | | serving surface | 对外服务接口 | | | | @@ -167,6 +175,7 @@ | stream | 流 | | | | | streaming | 流式输出 | | | | | structural signature | 结构签名 | | | i18n 配对机制用语:门禁比对两侧文件时提取的有序结构序列(标题层级、代码块、列表等) | +| Summary | 概述 | | | 事故复盘标题用语 | | system prompt | 系统提示词 | | | | | taxonomy | 分类体系 | | | | | token usage | token 用量 | | | | diff --git a/docs/module-graph.md b/docs/module-graph.md index 9f2d851c24..5d3326134e 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -121,8 +121,10 @@ flowchart TD pkg_llm_replay["llm-replay"] pkg_loader_smoke["loader-smoke"] end - subgraph group_ui["packages/ui"] + subgraph group_acp["packages/acp"] pkg_acp["acp"] + end + subgraph group_ui["packages/ui"] pkg_app_boot["app-boot"] pkg_commands["commands"] pkg_jsonrpc["jsonrpc"] @@ -196,6 +198,12 @@ flowchart TD pkg_scripts["scripts"] pkg_telemetry["telemetry"] end + subgraph group_storage["packages/storage"] + pkg_storage["storage"] + pkg_storage_domain["storage-domain"] + pkg_storage_json["storage-json"] + pkg_storage_sqlite["storage-sqlite"] + end subgraph group_tasks["packages/tasks"] pkg_tasks["tasks"] pkg_tool_tasks["tool-tasks"] @@ -206,6 +214,9 @@ flowchart TD pkg_workflow["workflow"] pkg_workflow_workerthread["workflow-workerthread"] end + subgraph group_workspace["packages/workspace"] + pkg_workspace["workspace"] + end pkg_brand --> pkg_invariants pkg_paths --> pkg_invariants pkg_retention --> pkg_invariants @@ -215,7 +226,6 @@ flowchart TD pkg_subagent_subprocess --> pkg_invariants pkg_acp_snapshot --> pkg_invariants pkg_loader_smoke --> pkg_invariants - pkg_client_connection --> pkg_invariants pkg_client_i18n --> pkg_invariants pkg_client_modules --> pkg_invariants pkg_client_runtime --> pkg_invariants @@ -231,9 +241,13 @@ flowchart TD pkg_host_apiproxy --> pkg_invariants pkg_host_runtime --> pkg_invariants pkg_host_webserver --> pkg_invariants + pkg_storage --> pkg_invariants pkg_llm --> pkg_brand pkg_llm --> pkg_invariants + pkg_client_connection --> pkg_host_webserver + pkg_client_connection --> pkg_invariants pkg_client_hmr --> pkg_client_modules + pkg_client_hmr --> pkg_host_webserver pkg_client_hmr --> pkg_invariants pkg_client_ui_conversation --> pkg_client_runtime pkg_client_ui_conversation --> pkg_client_ui_primitives @@ -251,6 +265,12 @@ flowchart TD pkg_telemetry --> pkg_brand pkg_telemetry --> pkg_invariants pkg_telemetry --> pkg_paths + pkg_storage_domain --> pkg_invariants + pkg_storage_domain --> pkg_storage + pkg_storage_json --> pkg_invariants + pkg_storage_json --> pkg_storage + pkg_storage_sqlite --> pkg_invariants + pkg_storage_sqlite --> pkg_storage pkg_llm_deepseek --> pkg_invariants pkg_llm_deepseek --> pkg_llm pkg_llm_deepseek --> pkg_timeout @@ -414,6 +434,12 @@ flowchart TD pkg_workflow --> pkg_invariants pkg_workflow --> pkg_llm pkg_workflow --> pkg_session + pkg_workspace --> pkg_brand + pkg_workspace --> pkg_invariants + pkg_workspace --> pkg_session + pkg_workspace --> pkg_session_persistence + pkg_workspace --> pkg_storage + pkg_workspace --> pkg_storage_domain pkg_tools --> pkg_agent pkg_tools --> pkg_code_runtime pkg_tools --> pkg_invariants @@ -454,6 +480,10 @@ flowchart TD pkg_session_title_first_message_llm --> pkg_session pkg_session_title_first_message_llm --> pkg_session_title pkg_session_title_first_message_llm --> pkg_session_title_llm + pkg_acp --> pkg_agent + pkg_acp --> pkg_invariants + pkg_acp --> pkg_session + pkg_acp --> pkg_user_approval pkg_permission --> pkg_bash pkg_permission --> pkg_invariants pkg_permission --> pkg_sandbox @@ -654,24 +684,6 @@ flowchart TD pkg_hooks_claude --> pkg_session_persistence pkg_hooks_claude --> pkg_subagent pkg_hooks_claude --> pkg_tools - pkg_acp --> pkg_agent - pkg_acp --> pkg_bash - pkg_acp --> pkg_commands - pkg_acp --> pkg_invariants - pkg_acp --> pkg_llm - pkg_acp --> pkg_llm_retry - pkg_acp --> pkg_permission - pkg_acp --> pkg_plan_mode - pkg_acp --> pkg_sandbox - pkg_acp --> pkg_session - pkg_acp --> pkg_session_persistence - pkg_acp --> pkg_session_query - pkg_acp --> pkg_session_reference - pkg_acp --> pkg_session_title - pkg_acp --> pkg_system_prompt - pkg_acp --> pkg_tools - pkg_acp --> pkg_user_approval - pkg_acp --> pkg_user_interaction pkg_jsonrpc --> pkg_agent pkg_jsonrpc --> pkg_invariants pkg_jsonrpc --> pkg_llm @@ -743,16 +755,12 @@ flowchart TD pkg_acp_demo --> pkg_acp pkg_acp_demo --> pkg_agent_spine_demo pkg_acp_demo --> pkg_app_boot - pkg_acp_demo --> pkg_command_goal - pkg_acp_demo --> pkg_commands pkg_acp_demo --> pkg_invariants pkg_acp_demo --> pkg_session_checkpoint_policy pkg_acp_demo --> pkg_session_persistence_jsonl pkg_acp_demo --> pkg_session_query pkg_acp_demo --> pkg_session_query_sqlite - pkg_acp_demo --> pkg_session_reference pkg_acp_demo --> pkg_tools - pkg_acp_demo --> pkg_user_interaction pkg_acp_demo --> pkg_workspace_context pkg_cli_demo --> pkg_agent pkg_cli_demo --> pkg_agent_spine_demo @@ -797,7 +805,6 @@ flowchart TD | [`subagent-subprocess`](../packages/subagent/subagent-subprocess) | `subagent` | [`invariants`](../packages/support/invariants) | | [`acp-snapshot`](../packages/support/acp-snapshot) | `support` | [`invariants`](../packages/support/invariants) | | [`loader-smoke`](../packages/support/loader-smoke) | `support` | [`invariants`](../packages/support/invariants) | -| [`client-connection`](../packages/client/connection) | `client` | [`invariants`](../packages/support/invariants) | | [`client-i18n`](../packages/client/i18n) | `client` | [`invariants`](../packages/support/invariants) | | [`client-modules`](../packages/client/modules) | `client` | [`invariants`](../packages/support/invariants) | | [`client-runtime`](../packages/client/runtime) | `client` | [`invariants`](../packages/support/invariants) | @@ -813,13 +820,18 @@ flowchart TD | [`host-apiproxy`](../packages/host/apiproxy) | `host` | [`invariants`](../packages/support/invariants) | | [`host-runtime`](../packages/host/runtime) | `host` | [`invariants`](../packages/support/invariants) | | [`host-webserver`](../packages/host/webserver) | `host` | [`invariants`](../packages/support/invariants) | +| [`storage`](../packages/storage/storage) | `storage` | [`invariants`](../packages/support/invariants) | | [`llm`](../packages/llm/llm) | `llm` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants) | -| [`client-hmr`](../packages/client/hmr) | `client` | [`client-modules`](../packages/client/modules), [`invariants`](../packages/support/invariants) | +| [`client-connection`](../packages/client/connection) | `client` | [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/support/invariants) | +| [`client-hmr`](../packages/client/hmr) | `client` | [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/support/invariants) | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-layout`](../packages/client/ui-layout) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-sidebar`](../packages/client/ui-sidebar) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`helper`](../packages/sdk/helper) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants) | | [`telemetry`](../packages/sdk/telemetry) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths) | +| [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`invariants`](../packages/support/invariants), [`storage`](../packages/storage/storage) | +| [`storage-json`](../packages/storage/storage-json) | `storage` | [`invariants`](../packages/support/invariants), [`storage`](../packages/storage/storage) | +| [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`invariants`](../packages/support/invariants), [`storage`](../packages/storage/storage) | | [`llm-deepseek`](../packages/llm/llm-deepseek) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) | | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) | | [`session`](../packages/core/session) | `core` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | @@ -867,6 +879,7 @@ flowchart TD | [`scripts`](../packages/sdk/scripts) | `sdk` | [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants) | | [`tasks`](../packages/tasks/tasks) | `tasks` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`workspace`](../packages/workspace/workspace) | `workspace` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`storage`](../packages/storage/storage), [`storage-domain`](../packages/storage/storage-domain) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/ui/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/ui/commands), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants) | | [`goal-session`](../packages/goal/goal-session) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | @@ -875,6 +888,7 @@ flowchart TD | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`session-title-all-messages-llm`](../packages/session-title/session-title-all-messages-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`session-title-llm`](../packages/session-title/session-title-llm) | | [`session-title-first-message-llm`](../packages/session-title/session-title-first-message-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`session-title-llm`](../packages/session-title/session-title-llm) | +| [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`user-approval`](../packages/ui/user-approval) | | [`permission`](../packages/ui/permission) | `ui` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`user-approval`](../packages/ui/user-approval) | | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query) | | [`pty-local`](../packages/pty/pty-local) | `pty` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`pty`](../packages/pty/pty), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session) | @@ -907,7 +921,6 @@ flowchart TD | [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools) | | [`hooks-claude`](../packages/hooks/hooks-claude) | `hooks` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/hooks/hook-protocol), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | -| [`acp`](../packages/ui/acp) | `ui` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`commands`](../packages/ui/commands), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`permission`](../packages/ui/permission), [`plan-mode`](../packages/plan/plan-mode), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-reference`](../packages/context/session-reference), [`session-title`](../packages/session-title/session-title), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval), [`user-interaction`](../packages/ui/user-interaction) | | [`jsonrpc`](../packages/ui/jsonrpc) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`tui`](../packages/ui/tui) | `ui` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`commands`](../packages/ui/commands), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-reference`](../packages/context/session-reference), [`session-title`](../packages/session-title/session-title), [`skill`](../packages/skill/skill), [`system-prompt`](../packages/core/system-prompt), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) | | [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`paths`](../packages/util/paths), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`skill`](../packages/skill/skill), [`skill-local`](../packages/skill/skill-local), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tool-bash`](../packages/bash/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-skill`](../packages/skill/tool-skill), [`tool-tasks`](../packages/tasks/tool-tasks), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | @@ -915,6 +928,6 @@ flowchart TD | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`subagent-fork`](../packages/subagent/subagent-fork) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | | [`subagent-spawn`](../packages/subagent/subagent-spawn) | `subagent` | [`invariants`](../packages/support/invariants), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | -| [`acp-demo`](../packages/examples/acp-demo) | `examples` | [`acp`](../packages/ui/acp), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`command-goal`](../packages/goal/command-goal), [`commands`](../packages/ui/commands), [`invariants`](../packages/support/invariants), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`session-reference`](../packages/context/session-reference), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction), [`workspace-context`](../packages/context/workspace-context) | +| [`acp-demo`](../packages/examples/acp-demo) | `examples` | [`acp`](../packages/acp/acp), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | | [`cli-demo`](../packages/examples/cli-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | | [`tui-demo`](../packages/examples/tui-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`command-goal`](../packages/goal/command-goal), [`commands`](../packages/ui/commands), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`session-reference`](../packages/context/session-reference), [`tool-ask-user`](../packages/ui/tool-ask-user), [`tools`](../packages/core/tools), [`tui`](../packages/ui/tui), [`user-interaction`](../packages/ui/user-interaction), [`workspace-context`](../packages/context/workspace-context) | diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 973238d905..0ac134aa41 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -78,7 +78,7 @@ export type SessionEvent<T extends SessionEventType = SessionEventType> = { }[T] ``` -Sources: [`packages/core/session/src/types.ts:325`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:338`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:367`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:399`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:324`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:337`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:366`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:398`](../packages/core/session/src/types.ts) ## Events @@ -150,7 +150,7 @@ Source: [`packages/ui/user-approval/src/index.ts:67`](../packages/ui/user-approv Types: [StreamChunk](core-data-structures/llm-streaming.md) -Source: [`packages/core/session/src/types.ts:271`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:270`](../packages/core/session/src/types.ts) #### `assistant/message` — surface @@ -166,7 +166,7 @@ Source: [`packages/core/session/src/types.ts:271`](../packages/core/session/src/ Types: [ContentBlock](core-data-structures/core.md) · [TokenUsage](core-data-structures/llm-streaming.md) -Source: [`packages/core/session/src/types.ts:278`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:277`](../packages/core/session/src/types.ts) ### `compact/*` @@ -329,7 +329,7 @@ Source: [`packages/plan/plan-mode/src/index.ts:41`](../packages/plan/plan-mode/s Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:269`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:268`](../packages/core/session/src/types.ts) ### `request/*` @@ -343,7 +343,7 @@ Source: [`packages/core/session/src/types.ts:269`](../packages/core/session/src/ 'request/header': { header: EpochHeader; reason: RequestHeaderReason } ``` -Source: [`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:312`](../packages/core/session/src/types.ts) ### `sandbox/*` @@ -399,7 +399,7 @@ Source: [`packages/session-title/session-title-llm/src/index.ts:44`](../packages 'steering/message': PromptMessageData & { turn: number } ``` -Source: [`packages/core/session/src/types.ts:306`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:305`](../packages/core/session/src/types.ts) ### `step/*` @@ -410,7 +410,7 @@ Source: [`packages/core/session/src/types.ts:306`](../packages/core/session/src/ 'step/end': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:254`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:253`](../packages/core/session/src/types.ts) #### `step/start` — log-only @@ -419,7 +419,7 @@ Source: [`packages/core/session/src/types.ts:254`](../packages/core/session/src/ 'step/start': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:252`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:251`](../packages/core/session/src/types.ts) ### `todo/*` @@ -432,7 +432,7 @@ Source: [`packages/core/session/src/types.ts:252`](../packages/core/session/src/ Types: [TodoItem](core-data-structures/session.md) -Source: [`packages/core/session/src/types.ts:308`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:307`](../packages/core/session/src/types.ts) ### `tool/*` @@ -449,7 +449,7 @@ Source: [`packages/core/session/src/types.ts:308`](../packages/core/session/src/ Types: [CallId](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:284`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:283`](../packages/core/session/src/types.ts) #### `tool/code-dispatch` — log-only @@ -503,7 +503,7 @@ Source: [`packages/core/tools/src/code-mode.ts:34`](../packages/core/tools/src/c Types: [CallId](core-data-structures/core.md) · [ContentBlock](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:296`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:295`](../packages/core/session/src/types.ts) ### `turn/*` @@ -521,7 +521,7 @@ Source: [`packages/core/session/src/types.ts:296`](../packages/core/session/src/ Types: [TurnEndReason](core-data-structures/session.md) -Source: [`packages/core/session/src/types.ts:250`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:249`](../packages/core/session/src/types.ts) #### `turn/start` — log-only @@ -537,7 +537,7 @@ Source: [`packages/core/session/src/types.ts:250`](../packages/core/session/src/ Types: [TurnTrigger](core-data-structures/session.md) -Source: [`packages/core/session/src/types.ts:243`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:242`](../packages/core/session/src/types.ts) ### `user/*` @@ -556,4 +556,4 @@ Source: [`packages/core/session/src/types.ts:243`](../packages/core/session/src/ 'user/message': PromptMessageData ``` -Source: [`packages/core/session/src/types.ts:264`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:263`](../packages/core/session/src/types.ts) diff --git a/docs/postmortem/0001-acp-default-export-drops-inject.i18n.yaml b/docs/postmortem/0001-acp-default-export-drops-inject.i18n.yaml new file mode 100644 index 0000000000..42e2dfa56a --- /dev/null +++ b/docs/postmortem/0001-acp-default-export-drops-inject.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 2d36f24fa54814e39345d7fe68792023c2cf0194 +0001-acp-default-export-drops-inject.zh.md: c528f8be04013803274e80e51970754e92a935ae diff --git a/docs/postmortem/0001-acp-default-export-drops-inject.md b/docs/postmortem/0001-acp-default-export-drops-inject.md index 10e88c390c..2d36f24fa5 100644 --- a/docs/postmortem/0001-acp-default-export-drops-inject.md +++ b/docs/postmortem/0001-acp-default-export-drops-inject.md @@ -1,5 +1,7 @@ # Post-mortem 0001: ACP server crashed on connect — `export default` dropped the plugin's `inject` +English | [中文](0001-acp-default-export-drops-inject.zh.md) + Status: resolved (fix in PR #41 `feat/acp-2-bridge`) ## Executive summary @@ -24,7 +26,7 @@ The ACP server could not create or load a single session — the two RPCs an edi ## Root cause #1 — `export default apply` drops the plugin's `inject` (broke `session/new`) -`packages/ui/acp/src/index.ts` is a *namespace plugin*: it exports `name`, `inject`, `Config`, and `apply` as separate named exports — the same shape as every other plugin in the repo (`invariants`, `llm-deepseek`, `tool-bash`, `tui`, …). But it *also* ended with one extra line no other plugin had: +`packages/acp/acp/src/index.ts` is a *namespace plugin*: it exports `name`, `inject`, `Config`, and `apply` as separate named exports — the same shape as every other plugin in the repo (`invariants`, `llm-deepseek`, `tool-bash`, `tui`, …). But it *also* ended with one extra line no other plugin had: ```ts ignore-check export const name = 'acp' @@ -97,7 +99,7 @@ Both bugs share one root process gap: **no test exercised the plugin through its ## Guardrails added -- **Removed `export default apply`** (`packages/ui/acp/src/index.ts`) — the Bug #1 fix. +- **Removed `export default apply`** (`packages/acp/acp/src/index.ts`) — the Bug #1 fix. - **`AgentLoop.resume` reads `this.ctx.get('sessionPersistence')`** (`packages/core/agent-loop/src/index.ts`) — the Bug #2 fix, with a comment explaining the shadow-walk trap. - **No-key `session/new` e2e over real stdio** (`examples/acp-agent/tests/acp.e2e.ts`): boots the example as a subprocess through the real Loader and asserts `session/new` resolves. This fails loudly on Bug #1 with no API key. Verified it fails when `export default apply` is restored. - **`TSX_TSCONFIG_PATH` in the e2e spawn**: the subprocess runs from a temp cwd, where tsx cannot find the repo-root tsconfig `paths` map by searching upward — so dsh-* imports silently fell back to built `lib/`. Pointing tsx at the repo tsconfig makes resolution cwd-independent and ensures the test runs *source*, not a possibly-stale build. diff --git a/docs/postmortem/0001-acp-default-export-drops-inject.zh.md b/docs/postmortem/0001-acp-default-export-drops-inject.zh.md new file mode 100644 index 0000000000..c528f8be04 --- /dev/null +++ b/docs/postmortem/0001-acp-default-export-drops-inject.zh.md @@ -0,0 +1,113 @@ +# 事故复盘(postmortem) 0001:ACP(Agent Client Protocol)服务器在连接时崩溃——`export default` 丢弃了插件的 `inject` + +[English](0001-acp-default-export-drops-inject.md) | 中文 + +Status: resolved (fix in PR(Pull Request) #41 `feat/acp-2-bridge`) + +## 摘要 + +两个集成错误在单元测试全覆盖的情况下仍然导致 ACP 崩溃:一个 default export 使 Loader 丢弃了 `inject`,一个经 traceable 代理的可选服务查找在 shadow 边界上失败。手动挂载的测试绕过了这两条路径。修复方案增加了无需 API key 的真实 Loader 覆盖率,并为插件导出和可选服务访问制定了包(package)级规则。 + +## 概述 + +ACP 服务器(`examples/acp-agent`、`@deepseek-ai/dsh-acp`)在真实编辑器(Zed)连接的瞬间崩溃:第一个 `session/new` 请求返回 `Internal error: cannot get property "agents" without inject`,`session/load` 对 `sessionPersistence` 返回同样的错误。尽管有 178 个绿色单元测试和 100% 行覆盖率,bridge 在生产环境中完全无法工作。两个独立的 bug 隐藏在同一个错误字符串背后,测试套件之所以两个都没捕获,原因也相同:所有测试都通过一条不会触及插件真实加载方式和服务真实解析方式的路径来挂载插件。 + +## 影响 + +ACP 服务器无法创建或加载任何一个会话——而这正是编辑器最先调用的两个 RPC。任何将 agent(智能体)接入 Zed 的人都会立即遭遇硬性失败。无数据丢失(崩溃前没有任何内容被持久化);代价完全是「功能不可用」加上两次定位原因的调试时间。 + +## 时间线 + +- bridge(RFC 010)落地时附带完整的单元测试套件(codec、内存传输、基于属性的协议形状测试、失败路径、HMR(热模块替换))、一个需要 key 的真实 API e2e 测试,以及一个无需 key 的 stdout 纯净性 e2e 测试。全部绿色,100% 覆盖率。 +- 真实 Zed 会话在 `session/new` 上立即失败,报错 `cannot get property "agents" without inject`。 +- 调查最初追踪了一个 Cordis「traceable/shadow」理论(看似合理,且该机制确实存在——见 Bug #2),随后在 vendor 的 `reflect.ts` 中对实际 fiber 遍历做了插桩,并运行了真实子进程。trace 显示 throw 发生在 `apply()` 第 179 行、*插件加载时*,位于 ROOT fiber 且没有 shadow——推翻了 shadow 理论对 `session/new` 的解释。 +- 找到根因 #1:一行多余的 `export default apply`。删除后 `session/new` 修复。 +- 删除后暴露了 Bug #2:`session/load` 仍然在 `sessionPersistence` 上抛错——这是一个真正不同的机制(shadow 遍历),通过隔离修复并重新运行真实子进程得到确认。 + +## 根因 #1——`export default apply` 丢弃了插件的 `inject`(导致 `session/new` 崩溃) + +`packages/acp/acp/src/index.ts` 是一个*命名空间插件*:它将 `name`、`inject`、`Config` 和 `apply` 作为独立的命名导出——与仓库中其他所有插件(`invariants`、`llm-deepseek`、`tool-bash`、`tui` 等)形状相同。但它*还*多了一行其他插件都没有的代码: + +```ts ignore-check +export const name = 'acp' +export const inject = ['agents', 'sessions', 'sessionPersistence'] +export function apply(ctx: Context, config: AcpConfig): void { /* … */ } +// … +export default apply // ← the bug +``` + +当插件从 `cordis.yml` 加载时,Cordis Loader 通过 `Loader.unwrapExports`(`vendor/loader/src/index.ts`)对导入的模块进行规范化: + +```ts ignore-check +unwrapExports(exports: any) { + if (isNullable(exports)) return exports + exports = exports.default ?? exports // ← prefers `.default` + if (!exports.__esModule) return exports + return exports.default ?? exports +} +``` + +存在 default export 时,`exports.default ?? exports` 解析为**裸 `apply` 函数**。裸函数没有 `inject`、没有 `name`、没有 `Config` 属性——这些作为*兄弟*命名导出存在于模块命名空间上,而 unwrap 到 `.default` 把整个命名空间丢弃了。Loader 随后基于空的 `inject` 构建了插件的 fiber。 + +因此 `apply` 在一个**没有注入任何服务**的 fiber 中运行。第一行 `const agents = ctx.agents` 遍历 fiber 树(ROOT → Include → Loader → ROOT),在所有 fiber 的 store 中都找不到 `agents`,到达根 fiber(`runtime === null`)后抛出 `cannot get property "agents" without inject`。崩溃发生在*加载时*,而非后续的请求处理器中——请求只是恰好触发了加载。 + +**修复:** 删除 `export default apply`。Loader 随后使用模块命名空间,正确识别 `inject`/`name`/`Config`,`apply` 在一个真正授予了声明服务的 fiber 中运行。 + +## 根因 #2——可选服务读取通过 traceable shadow 触发 inject 守卫(导致 `session/load` 崩溃) + +修复 #1 后,`session/new` 正常工作,但 `session/load` 仍然抛出 `cannot get property "sessionPersistence" without inject`。这个问题*确实*是 Cordis 的 traceable/shadow 机制,值得精确理解。 + +`session/load` 调用 `agents.resume(...)`,后者委托给 `AgentLoop.resume()`,其中读取了 `this.ctx.sessionPersistence`。`AgentLoop` 的 `static inject` 故意不包含 `sessionPersistence`——注入它会导致非持久化的演示永远挂起,等待一个永远不会加载的后端。该服务由一个独立的兄弟插件/fiber 提供,以机会性方式读取。 + +Cordis 中的服务访问通过上下文代理(`vendor/cordis/src/reflect.ts`)进行。当通过从外部 fiber 获取的 *traceable 代理*调用服务方法时(此处:bridge fiber 调用 `ctx.agents.resume`,注册表返回 `this.factory`——即 `AgentLoop`——重新包装为绑定到调用方的新 traceable 代理),`createShadowMethod`(`vendor/cordis/src/utils.ts`)将 `this` 重新绑定到一个 *shadow* 对象,其 `ctx` 携带 `[symbols.shadow]` 指向 `AgentLoop` 自身的构造上下文。在 `resume` 内部,`this.ctx.sessionPersistence` 的解析从 shadow 的 fiber 开始遍历: + +```ts ignore-check +// reflect.ts get handler +let fiber = (ctx[symbols.shadow] as Context ?? ctx).fiber // ← starts at AgentLoop's fiber +while (true) { + const impl = fiber.store?.[prop] + if (impl) return getTraceable(ctx, impl.value) + if (prop in fiber.inject) { /* inactive-context error */ } + if (!fiber.runtime) throw error // ← reached root, throw + if (fiber.parent[symbols.isolate][prop] !== key) throw error + fiber = fiber.parent.fiber // ← ancestor-only +} +``` + +遍历**仅向祖先方向**进行。`sessionPersistence` 既不在 `AgentLoop` 的 fiber store 中(不在其 `static inject` 中),也不在通往 root 的任何祖先上(它位于一个*兄弟*分支),因此遍历到达根 fiber 后抛错。 + +为什么内存中的 `AgentLoop` 恢复测试没有捕获这个问题?因为它们从测试代码直接调用 `ctx.agents.resume(...)`——*在任何插件 fiber 之外*。此时 `ctx.fiber.runtime` 为 `null`,代理处理器走了一条提前绕过的路径: + +```ts ignore-check +if (!ctx.fiber.runtime) return ctx.reflect.get(prop, false) // ← direct global-store lookup, no fiber walk +``` + +`ctx.reflect.get(name, false)` 是基于 isolate symbol 的全局服务 store 直接查找——完全忽略 fiber 拓扑,能找到服务。因此从顶层测试读取可以成功;而从真实插件 fiber 内部、经由 shadow 到达时则抛错。bridge 恰好是后者。 + +**修复:** 使用 `ctx.get('sessionPersistence')` 读取可选服务,该方法使用全局 isolate-keyed store 同时保留活跃状态检查。对于插件声明注入集中的服务,直接属性读取仍然适用。 + +## 为什么所有测试都没有捕获(真正的失败) + +两个 bug 共享同一个流程缺口:**没有任何测试通过插件的真实加载路径或真实调用拓扑来驱动它。** + +- 内存 harness 通过手动构建插件对象来挂载 bridge:`ctx.plugin({ name, inject, apply })`。这手动提供了 `inject`,因此永远无法复现 Bug #1——`unwrapExports` 只被 *Loader* 调用,`ctx.plugin` 从不调用它。即使 `ctx.plugin(NamespaceImport)` 也无法捕获。 +- 同一个 harness 将所有内容平铺挂载在一个根上下文上,因此从中触达的 `AgentLoop` 恢复要么运行在顶层(`!runtime` 绕过),要么通过一个 origin 仍然解析在 root 上的 shadow——掩盖了 Bug #2 的祖先遍历失败。 +- 唯一的无 key e2e 发送 `initialize` 并检查 stdout 纯净性。`initialize` 从不触达 factory,因此两个 bug 都安然通过。 +- 唯一驱动 `session/new`/`session/load` 的测试需要 key 才能运行,因此 CI(无 key)跳过了它——而本地它之所以「通过」,只是因为一个陈旧的已构建 `lib/`(包含旧代码)恰好满足了模块解析。 + +100% 行覆盖率始终满足。覆盖率证明代码行*被执行过*;它不能说明功能是否*按交付方式正常工作*。 + +## 新增的防护措施 + +- **删除 `export default apply`**(`packages/acp/acp/src/index.ts`)——Bug #1 的修复。 +- **`AgentLoop.resume` 使用 `this.ctx.get('sessionPersistence')`**(`packages/core/agent-loop/src/index.ts`)——Bug #2 的修复,附注释说明 shadow 遍历陷阱。 +- **无需 key 的 `session/new` e2e,通过真实 stdio 运行**(`examples/acp-agent/tests/acp.e2e.ts`):以子进程方式通过真实 Loader 启动示例,并断言 `session/new` 正常返回。无需 API key 即可在 Bug #1 上大声失败。已验证恢复 `export default apply` 时测试失败。 +- **e2e spawn 中设置 `TSX_TSCONFIG_PATH`**:子进程从临时 cwd 运行,tsx 无法通过向上搜索找到仓库根的 tsconfig `paths` 映射——因此 dsh-* 的 import 静默回退到已构建的 `lib/`。将 tsx 指向仓库 tsconfig 使解析不依赖 cwd,确保测试运行的是*源码*而非可能陈旧的构建产物。 +- **[docs/testing.md](../testing.md) 规则**:「测试真实入口路径」,行覆盖率不等于行为覆盖率——将这一教训编纂为所有未来插件的规则。 + +## 经验教训 + +- 命名空间插件与 default export 在 Cordis Loader 下互斥。选择命名空间形式(`name`/`inject`/`Config`/`apply`),不要添加 `export default`——`unwrapExports` 会丢弃命名空间。 +- 对于插件机会性读取但未在 `static inject` 中声明的服务,使用 `ctx.get(name)`,绝不使用 `ctx.<name>`。属性代理通过仅向祖先方向的 fiber 遍历解析,经由外部 shadow 时会失败;`ctx.get(name)` 是拓扑无关的查找(且默认严格——非活跃后端读取为 `undefined`,而非在 teardown 过程中被交出)。 +- 手动构建插件的测试无法验证插件的加载方式。至少一个测试必须端到端地驱动真实的 Loader/export 路径。当核心操作不调用模型时,该测试无需 API key——因此它属于 CI,而非 key 门控之后。 +- 相信 trace,不要相信理论。优雅的 shadow 解释是真实的,但它是*第二个* bug;*第一个*是一行导出错误,在数小时看似合理但实际错误的推理之后,一个 fiber 遍历的 `console.error` 在几分钟内就找到了它。 diff --git a/docs/postmortem/0002-js-expression-disabled-filesystem-tools.i18n.yaml b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.i18n.yaml new file mode 100644 index 0000000000..2aad7141c5 --- /dev/null +++ b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: 30ff9d920821a8d55c4bea5f120f1aeeca6634b3 +0002-js-expression-disabled-filesystem-tools.zh.md: b103ec6de5d6d6406ba48ec34f6ebb479e472352 diff --git a/docs/postmortem/0002-js-expression-disabled-filesystem-tools.md b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.md index ccdb725bfb..30ff9d9208 100644 --- a/docs/postmortem/0002-js-expression-disabled-filesystem-tools.md +++ b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.md @@ -1,5 +1,7 @@ # Post-mortem 0002: Filesystem snapshot tools were permanently disabled +English | [中文](0002-js-expression-disabled-filesystem-tools.zh.md) + Status: resolved ## Executive summary diff --git a/docs/postmortem/0002-js-expression-disabled-filesystem-tools.zh.md b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.zh.md new file mode 100644 index 0000000000..b103ec6de5 --- /dev/null +++ b/docs/postmortem/0002-js-expression-disabled-filesystem-tools.zh.md @@ -0,0 +1,47 @@ +# 事故复盘(postmortem) 0002:文件系统快照工具被永久禁用 + +[English](0002-js-expression-disabled-filesystem-tools.md) | 中文 + +Status: resolved + +## 摘要 + +ACP(Agent Client Protocol)示例试图通过 `disabled: !!js ...` 有条件地启用文件系统插件,但 Cordis 仅在插件 `config` 内部对 JavaScript 表达式求值。原始的表达式对象为 truthy,因此文件系统栈始终处于禁用状态。快照刷新随后将 `UNKNOWN_TOOL` 结果接受为新的预期输出。修复方案改用显式的文件系统 overlay,并增加了静态配置守卫和快照结果守卫。 + +## 概述 + +默认的 ACP 组合有意只启用 bash,因为其沙箱无法约束进程内的文件系统提供方。文件系统快照场景仍然需要 `read`、`write` 和 `edit`,因此这些插件被放在默认的 `cordis.yml` 中,并附带一个 `disabled` 表达式,意图仅在全权限启动和快照模式下启用它们。 + +Cordis Include 将每个 `!!js` 标量解析为一个表达式对象。Loader 递归地对插件的 `config` 进行插值,但直接消费 `disabled` 等入口元数据。因此每个文件系统入口看到的都是一个 truthy 对象,在所有模式下均保持禁用。 + +## 影响 + +七个文件系统场景和一个混合工作区编辑场景调用了注册表中不存在的工具。其结构化会话日志携带 `ToolNotFoundError`(code 为 `UNKNOWN_TOOL`),stdout 渲染出通用的失败工具卡片。快照套件通过了,因为结构化会话日志和 stdout 渲染出的通用失败工具卡片均与刷新后的 fixture(测试前置数据)匹配;它证明的是回归的确定性回放,而非文件系统行为的正确性。 + +实际运行的受限默认模式并未获得意外的文件系统访问权限。一个简单的插值修复反而会制造该风险:权限预设在运行时更新 bash 沙箱和审批状态,但无法挂载、卸载或约束文件系统栈。 + +## 时间线 + +- PR(Pull Request) #261 整合了 ACP 组合并刷新了文件系统快照,同时引入了条件式文件系统入口。 +- 所有单元测试、覆盖率、快照、文档、构建和 hygiene 检查均通过。 +- 对刷新后的文件系统预期输出的评审发现了通用的失败卡片和结构化的 `UNKNOWN_TOOL` 结果。 +- 一次真实的 Loader 启动确认:每个 `disabled` 值仍为表达式对象,每个文件系统 fiber 均未创建。 + +## 根因 + +实现时假设 `!!js` 适用于整个 Loader 入口。其实际边界更窄:`Entry._resolveConfig()` 仅对 `entry.options.config` 进行插值;`Entry.disabled` 直接测试 `entry.options.disabled`,不经过插值。YAML 标签在语法上合法,因此加载过程不产生任何诊断信息。 + +快照框架将任何确定性的 transcript(文本记录)视为有效行为。Header pin 验证了组合后的工具 schema,但文件系统场景共享来自默认组合的 pin,因此未独立证明其所需工具已注册。刷新在任何语义断言拒绝缺失工具之前,就已重写了预期的 stdout 和会话日志。 + +## 已添加的防护措施 + +- 文件系统场景启动 `fs.cordis.yml`:一个显式的固定全权限 overlay,配有对应的回放配置和独立的 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` 结果,防止其被提交为预期输出。 + +## 教训 + +- 语法上被接受的配置值不一定在该位置被求值;应记录并验证插值边界。 +- 快照刷新是 fixture 的生产过程,不是正确性审查。诸如已注册工具缺失这类语义上不可能的结果,需要独立于预期输出的断言。 +- 权限控制只应描述其实际管辖的能力。组合时的文件系统访问无法安全地跟随运行时的 bash-only 预设。 diff --git a/docs/postmortem/README.i18n.yaml b/docs/postmortem/README.i18n.yaml new file mode 100644 index 0000000000..e68d3a1a07 --- /dev/null +++ b/docs/postmortem/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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: df0e2fcb8540aeed005153dbecc451d781ca5ff1 +README.zh.md: 2ce6de475c705b02cd9dabfb2181929d81478e2c diff --git a/docs/postmortem/README.md b/docs/postmortem/README.md index 7114f65916..df0e2fcb85 100644 --- a/docs/postmortem/README.md +++ b/docs/postmortem/README.md @@ -1,5 +1,7 @@ # Post-mortems +English | [中文](README.zh.md) + Incident write-ups: a bug reached a place it shouldn't have (a real user, a merged PR, a release), and the interesting part is *why our process let it through*, not just the one-line fix. A post-mortem is NOT an [Agent Note](../../.agents/notes/README.md) (which records a deliberate design decision and its rejected alternatives, or proposes future work). It is a backward-looking record of a failure: what broke, the mechanism, why every safety net missed it, and the concrete guardrails added so the same class of bug fails loudly next time. diff --git a/docs/postmortem/README.zh.md b/docs/postmortem/README.zh.md new file mode 100644 index 0000000000..2ce6de475c --- /dev/null +++ b/docs/postmortem/README.zh.md @@ -0,0 +1,16 @@ +# 事故复盘(postmortem) + +[English](README.md) | 中文 + +事故复盘:一个 bug 到达了它不该到达的地方(真实用户、已合并的 PR(Pull Request)、已发布的版本),值得关注的是*为什么我们的流程放过了它*,而不仅仅是那一行修复。 + +事故复盘不是 [Agent Note(agent 决策记录)](../../.agents/notes/README.md)(Agent Note 记录一个经过深思熟虑的设计决策及其被否决的替代方案,或提出未来工作)。它是一份回顾性的失败记录:什么坏了、机制是什么、为什么每道安全网都没拦住、以及加了哪些具体的防护措施使同类 bug 下次能被显式暴露。 + +当一个 bug 满足以下条件时,请撰写事故复盘:**隐蔽**(机制不显而易见,即使是细心的工程师也得费力重新推导)、**系统性**(逃逸的原因是测试/工具/约定的缺口,而非一次性的笔误)、**重新发现的代价高**(它消耗了真实的调试时间,且下次还会如此)。请链接该事故复盘所推动建立的防护措施(测试、AGENTS.md 规则、ADR)。 + +每篇事故复盘以一段**摘要**开头:一个简短段落,让忙碌的读者在三十秒内吸收要点——什么坏了、用直白的话说根因是什么、为什么逃逸了、持久的教训是什么——然后才是后续的详细「概述 / 时间线 / 根因 / 防护措施」各节。 + +| # | 标题 | +|---|---| +| [0001](0001-acp-default-export-drops-inject.md) | ACP(Agent Client Protocol)服务器在连接时崩溃:`export default` 丢失了插件的 `inject` | +| [0002](0002-js-expression-disabled-filesystem-tools.md) | 文件系统快照工具被一个字面量 `!!js` 对象永久禁用 | diff --git a/docs/testing.i18n.yaml b/docs/testing.i18n.yaml new file mode 100644 index 0000000000..ecb6ee40c0 --- /dev/null +++ b/docs/testing.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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 +testing.md: ac5324c6ad2cc0718d9ad4f2d699120abb033374 +testing.zh.md: 54e7a91b69480893a871d73b95696b10ffd69926 diff --git a/docs/testing.md b/docs/testing.md index 85798cee3e..ac5324c6ad 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1,21 +1,23 @@ # Testing policy +English | [中文](testing.zh.md) + How this repo tests, tier by tier, and the rules that keep a green suite meaningful. Commands live in root [AGENTS.md](../AGENTS.md); linked Agent Notes carry the rationale. ## Tiers -- **Unit** (`pnpm run test`): vitest over `packages|examples/*/tests/**/*.spec.ts`, colocated with what they test. Every registry gets an HMR-safety test (dispose the contributing fiber, assert cleanup). Prefer edge cases, error paths, event ordering, concurrency races, and permanent contract regressions (see `packages/core/agent-loop/tests/contract-regressions.spec.ts`). +- **Unit** (`pnpm run test`): vitest over package and example specs under their `tests/**` directories plus repository script specs under `scripts/**/*.spec.ts`; tests stay with the code area they exercise. Every registry gets an HMR-safety test (dispose the contributing fiber, assert cleanup). Prefer edge cases, error paths, event ordering, concurrency races, and permanent contract regressions (see `packages/core/agent-loop/tests/contract-regressions.spec.ts`). - **Coverage gate** (`pnpm run test:coverage`): the gating run, per-file 100% on `packages/*/*/src`. An uncovered line is often dead code the gate is correctly flagging for deletion, not a missing test to bolt on. Line coverage is necessary, never sufficient — it proves lines ran, not that the feature works as shipped. - **Real-API e2e** (`pnpm run test:e2e`): with-key tests against live provider APIs — the DeepSeek model plus provider-specific smokes that gate on their own keys (`EXA_API_KEY`, `PERPLEXITY_API_KEY`, …); each suite self-skips without its key so keyless CI stays green ([real-API e2e Agent Note](../.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md)). -- **Snapshot** (`pnpm run test:snapshot`): transport-specific keyless expected outputs cover external presentation. ACP suites boot the real example subprocess, replay a recorded session, and diff normalized JSON-RPC plus the re-persisted log ([ACP snapshot Agent Note](../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md)); the headless suite independently pins `stream-json` through its real one-shot subprocess. TUI completed journeys replay recorded primary/child JSONL through the real agent loop and tools before projecting ANSI into semantic terminal-state expected outputs; package-local snapshots retain transient renderer states, and a real PTY conversation covers the process boundary ([TUI snapshot Agent Note](../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md)). Use `pnpm run test:snapshot:record` when a model transcript must change and `pnpm run test:snapshot:refresh` when committed replay input remains correct; review every JSONL and expected-output diff. System-prompt/tool-schema content is pinned by one ACP scenario (`text-turn`) and tokenized in every other fixture, so a prompt or schema edit churns one committed line ([pinned-header Agent Note](../.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)). +- **Snapshot** (`pnpm run test:snapshot`): keyless expected outputs cover external behavior — transport contracts and presentation, while persisted logs pin assembled backend behavior. ACP boots the real automation-server example, replays a recorded session, and diffs normalized JSON-RPC plus the re-persisted log ([ACP snapshot Agent Note](../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md)); headless pins `stream-json` through its real one-shot process. TUI journeys replay primary/child JSONL through the real loop and tools, then project ANSI into semantic terminal-state outputs; package snapshots retain transient states and a real PTY covers the process boundary ([TUI snapshot Agent Note](../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md)). Use `pnpm run test:snapshot:record` when a model transcript changes and `pnpm run test:snapshot:refresh` when replay input remains valid; review every JSONL and expected-output diff. One ACP scenario (`text-turn`) pins full system-prompt/tool-schema content; other fixtures tokenize it so an edit churns one line ([pinned-header Agent Note](../.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)). ## The with-key policy: inference is cheap here -We are DeepSeek — do not ration real-API tests. A no-key test proves plumbing; only a with-key run proves the agent works against a real model. Write many: file-writing prompts, multi-turn conversations, tool use, cancellation mid-stream. Highest-value are **smoke tests** that boot the real example, send one real prompt, and check the world — they catch the "green unit tests, broken product" class that mocks structurally cannot ([postmortem 0001](postmortem/0001-acp-default-export-drops-inject.md)). The self-skip exists only so secretless CI and keyless contributors aren't blocked; it is not a cost signal. Every example ships both a keyless smoke and a with-key smoke ([examples/AGENTS.md](../examples/AGENTS.md)). +We are DeepSeek — do not ration real-API tests. A no-key test proves plumbing; only a with-key run proves the agent works against a real model. Cover file-writing prompts, multi-turn conversations, tool use, and mid-stream cancellation. Highest-value are **smoke tests** that boot the real example, send one prompt, and check the world — they catch the "green unit tests, broken product" class that mocks cannot ([postmortem 0001](postmortem/0001-acp-default-export-drops-inject.md)). Self-skip keeps secretless CI and keyless contributors unblocked; it is not a cost signal. Every example ships keyless and with-key smokes ([examples/AGENTS.md](../examples/AGENTS.md)). ## Prefer the real implementation over a mock -Mock only the genuinely expensive or non-deterministic boundary (the LLM adapter, the network, the clock); keep everything downstream real. A hand-rolled stand-in proves the bridge moves bytes, not that the shipping tool behaves as asserted — the two drift while the test stays green. Example: bridge tool-call tests run the scripted mock MODEL but the real tool + real executor (`makeBridgeHarness({ withBash: true })` plugs `dsh-bash-local` + `dsh-tool-bash` and runs an actual `echo`). +Mock only the expensive or non-deterministic boundary (LLM adapter, network, clock); keep everything downstream real. A hand-rolled stand-in proves the bridge moves bytes, not that the shipping tool behaves as asserted. Bridge tool-call tests use the scripted mock model with the real tool and executor: `makeBridgeHarness({ withBash: true })` plugs in `dsh-bash-local` and `dsh-tool-bash`, then runs `echo`. Recovery tests separate pre/post-chunk failures by step and prove failed chunks derive no message or tool side effect. Cover exhaustion, cancellation, policy composition, persistence, status, wire counts, transport-closing idle timeouts, and shipping Loader composition. @@ -41,4 +43,4 @@ An e2e assertion re-runs the command or re-reads the file externally; a keyword ## When a snapshot test is required -Every non-trivial model- or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock/test-only compositions, and PR rationale do not replace the assembled transcript; extend the harness when needed. ACP surfaces use `examples/<name>/tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory (`examples/acp-agent` is primary); `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. Completed interactive-terminal journeys use JSONL-driven scenarios under `examples/tui-agent/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when input, Loader selection, or terminal teardown changes. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness can express it before implementation. +Every non-trivial model-, protocol-, or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock/test-only compositions, and PR rationale do not replace the assembled transcript; extend the harness when needed. ACP automation scenarios use `examples/<name>/tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory (`examples/acp-agent` is primary); `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. Completed interactive-terminal journeys use JSONL-driven scenarios under `examples/tui-agent/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when input, Loader selection, or terminal teardown changes. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness can express it before implementation. diff --git a/docs/testing.zh.md b/docs/testing.zh.md new file mode 100644 index 0000000000..54e7a91b69 --- /dev/null +++ b/docs/testing.zh.md @@ -0,0 +1,46 @@ +# 测试策略 + +[English](testing.md) | 中文 + +本文说明本仓库的分层测试方式,以及保持绿色测试套件有意义的规则。命令见根目录 [AGENTS.md](../AGENTS.md);相关 Agent Note(agent 决策记录)承载设计动机。 + +## 层级 + +- **单元测试**(`pnpm run test`):vitest 运行包(package)和示例各自的 `tests/**` 目录下的测试,以及匹配 `scripts/**/*.spec.ts` 的仓库脚本测试;测试文件与其所覆盖的代码区域放在一起。每个注册表都有一个 HMR(热模块替换)安全测试(dispose(资源释放)贡献的 fiber,断言清理完成)。优先覆盖边界情况、错误路径、事件顺序、并发竞态,以及永久性契约回归(见 `packages/core/agent-loop/tests/contract-regressions.spec.ts`)。 +- **覆盖率门禁**(`pnpm run test:coverage`):门禁级运行,对 `packages/*/*/src` 按文件 100% 覆盖。未覆盖的行往往是门禁正确标记出的死代码(应删除),而非需要补写的测试。行覆盖率是必要条件,但永远不是充分条件:它证明行被执行过,不证明功能按交付预期工作。 +- **真实 API e2e**(`pnpm run test:e2e`):带密钥测试调用真实提供方 API,包括 DeepSeek 模型以及各提供方特有的冒烟测试;这些测试各自由自己的密钥控制(`EXA_API_KEY`、`PERPLEXITY_API_KEY` 等),缺少密钥时套件会自动跳过,使 keyless CI 保持绿色([真实 API e2e Agent Note](../.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md))。 +- **快照**(`pnpm run test:snapshot`):无密钥预期输出覆盖对外行为(传输契约与呈现),持久化日志则固定组装后的后端行为。ACP 启动真实的自动化服务器示例、回放录制会话,并对归一化 JSON-RPC 与重新持久化的日志执行 diff([ACP 快照 Agent Note](../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md));headless 通过真实单次运行进程固定 `stream-json`。TUI 旅程通过真实循环与工具回放主会话与子会话 JSONL,再将 ANSI 投影为语义化终端状态输出;包级快照保留瞬态状态,真实 PTY 覆盖进程边界([TUI 快照 Agent Note](../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md))。当模型 transcript(文本记录)发生变化时使用 `pnpm run test:snapshot:record`,回放输入仍然有效时使用 `pnpm run test:snapshot:refresh`;请审查每一处 JSONL 与预期输出差异。一个 ACP 场景(`text-turn`)固定完整的系统提示词与工具 schema 内容;其他 fixture(测试前置数据)将其 token 化,因此修改只会扰动一行([pinned-header Agent Note](../.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md))。 + +## 带密钥策略:推理在这里很便宜 + +我们是 DeepSeek,不要吝惜真实 API 测试。无密钥测试只能证明底层通路;只有带密钥运行才能证明 agent(智能体)能对接真实模型正常工作。覆盖文件写入提示词、包含多个轮次的对话、工具使用和流中取消。价值最高的是**冒烟测试**:启动真实示例、发送一条提示词,并检查外部世界;它们能捕获「单元测试全绿、产品却坏了」这一类 mock 无法发现的问题([事故复盘 0001](postmortem/0001-acp-default-export-drops-inject.md))。自动跳过让无密钥 CI 和无密钥贡献者不受阻塞;它不是成本信号。每个示例都提供无密钥和带密钥冒烟测试([examples/AGENTS.md](../examples/AGENTS.md))。 + +## 优先使用真实实现而非 mock + +只 mock 开销高或不确定的边界(LLM(大语言模型)适配器、网络、时钟);下游一切保持真实。手写替身只能证明桥接层在搬运字节,不能证明交付的工具行为符合断言。桥接工具调用测试将脚本化 mock 模型与真实工具和执行器配合使用:`makeBridgeHarness({ withBash: true })` 接入 `dsh-bash-local` 与 `dsh-tool-bash`,然后运行 `echo`。 + +恢复测试按步骤区分分片前与分片后的失败,并证明失败分片不会派生出消息或工具副作用。覆盖耗尽、取消、策略组合、持久化、状态、协议计数、会关闭传输的空闲超时,以及交付的 Loader 组合。 + +## 验证外部世界,而非自我报告 + +e2e 断言应重新运行命令或从外部重新读取文件;对 agent 自身输出做关键词探测会让作弊的 agent 通过。断言未修改的文件逐字节一致。e2e 测试自行管理资源:在测试中创建 harness,在 `afterEach` 中 dispose(即使失败/重试/超时也要释放);共享 fixture 放在普通的 `tests/harness.ts` 中,绝不放在另一个 `*.e2e.ts` 中(导入一个 spec 会重新注册其 `describe`,导致真实 API 调用重复执行)。 + +## 测试真实入口路径 + +- 产品可见的插件必须有一个非单元的真实组合测试。手动构建的 `ctx.plugin(...)` 套件不够:通过 Loader 和 app/process 启动仅用于测试的 `cordis.yml`,只 mock 外部/不确定边界,断言模型可见的请求/日志、持久状态或用户可见输出。不要把 opt-in 选项混入交付默认值。 +- 一个守卫只有在回归真的能让它失败时才有效。对于没有 `inject` 的插件(bundle/组合插件),Loader 冒烟测试在导出形状损坏时仍然绿着——需要添加显式的 `expect('default' in mod).toBe(false)` 加 `unwrapExports` 往返断言,并证明它有效:引入回归、观察变红、回退。 +- 「真实入口路径」指已发布的产物:包的 `bin` 所运行的是构建后的 `lib/bin.js`,并由普通 `node` 执行,从而暴露 tsx 会掩盖的失败(等待稳定时的竞态、模块解析、被吞掉的加载失败)。同样的规则适用于非 index 运行时入口(worker-thread 的同级文件 `lib/worker.cjs`),也适用于多个 bundle 共享的单例模块(`packages/ui/jsonrpc/tests/built-scope-carrier.e2e.ts`)。保持构建产物冒烟测试绿色(`packages/ui/*/tests/built-bin.e2e.ts`、`packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts`),并断言真正缺失的配置以非零状态退出。 + +## 测试解析:仅限源码 + +- 每个 vitest 配置都将 vite-tsconfig-paths 指向 `tsconfig.base.json`;工作区包的裸导入解析到 `src`([布局](development.md#typescript-project-layout)),绝不会经由包的 `exports` 解析到构建后的 `lib/`,因为其中的陈旧产物会加载第二份模块单例。构建产物只在显式指定时使用:以 `lib` 模式运行的子进程,以及下文的构建产物冒烟测试。 + +## 测试子进程启动模式 + +- CI 与已有构建产物的测试通道通过共享双模式启动器,从构建后的 `lib/` 运行每个示例或 Cordis 配置子进程。不要为这些子进程手写 `--import tsx`。 +- 不加载 Cordis 的协议与操作系统 fixture 直接通过 Node 运行使用可擦除语法的 `.ts` 文件,不经过 tsx 或根路径映射。 +- 只有测试对象本身是源码路径解析时,才可以选择 `src`;在测试中写明这一契约。 + +## 何时需要快照测试 + +每项非平凡的模型可见、协议可见或人类可见变更,都必须在同一 PR 中,通过可运行示例所属的快照套件添加或更新无密钥场景。包测试、e2e 断言、mock 与仅测试组合、PR 理由都不能取代组装后的 transcript;必要时应扩展 harness。ACP 自动化场景使用 `examples/<name>/tests/snapshots/`,即基于 [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) 套件工厂的场景表(`examples/acp-agent` 为主套件);`examples/headless-agent` 拥有 `stream-json` 快照与回放 fixture。已完成的交互式终端旅程使用 `examples/tui-agent/tests/snapshots/` 下由 JSONL 驱动的场景;瞬态呈现使用包内语义矩阵,输入、Loader 选择或终端清理发生变化时还要添加 PTY 用例。新的能力 seam、生命周期形态或 transcript 呈现接口在计划阶段就要列出每个覆盖层级,并在实现前验证 harness 能够表达它们。 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index a802c7d4ee..06a0ec989c 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -30,7 +30,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-session-query` | `session_event_read`, `session_event_search`, `session_event_trace`, `session_search`, `session_trace` | `ctx.tools`, `ctx.systemPrompt`, `ctx.sessionQuery`, `a calling Agent for workspace authority` | `tool/call`, `tool/result` | - | The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. Default ACP, TUI, and Web compositions enforce the declared search timeout and apply the generic tool-result spill policy. | | `@deepseek-ai/dsh-tool-subagent` | `subagent` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The registered tool name is the load-time `toolName` config (default `subagent`); the schema above is that default. The shipped example agents load this package once per subagent backend, so the model additionally sees `subagent_fork` (bound to the fork backend) with an identical schema — see `examples/tui-agent/cordis.yml` and `examples/acp-agent/cordis.yml`. | | `@deepseek-ai/dsh-tool-tasks` | `task_kill`, `task_list`, `task_output` | `ctx.tools`, `ctx.tasks`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `user/message via agent.inject() for background completion notices` | - | The kind-agnostic background-task control surface: background bash commands, PTY sends, and subagents are read, listed, and killed through the same three tools. Loading the plugin attaches the control surface that arms producers' `ctx.tasks.start()`. | -| `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist or ACP plan. | +| `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist. | | `@deepseek-ai/dsh-tool-workflow` | `workflow` | `ctx.tools`, `ctx.workflows`, `ctx.systemPrompt`, `a calling Agent (exec.agent parents the script children)` | `tool/call`, `tool/result` | - | - | | `@deepseek-ai/dsh-tool-web` | `web_fetch`, `web_search` | `ctx.tools`, `ctx.web`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | web_search and web_fetch keep provider selection behind ctx.web so model-visible schemas stay stable across backend swaps. | @@ -1163,7 +1163,7 @@ Record and update a structured task list for the current work. Send the ENTIRE l Source: [`packages/todo/tool-todo/src/index.ts`](../packages/todo/tool-todo/src/index.ts) -todo_write is session-owned state; UIs render the latest todo/write event as a checklist or ACP plan. +todo_write is session-owned state; UIs render the latest todo/write event as a checklist. ## `@deepseek-ai/dsh-tool-workflow` diff --git a/docs/user/develop/basic/tool.i18n.yaml b/docs/user/develop/basic/tool.i18n.yaml index 73970f99d8..697c88e98f 100644 --- a/docs/user/develop/basic/tool.i18n.yaml +++ b/docs/user/develop/basic/tool.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 -tool.md: 7b211cfef54306f7c316dc08da1df759dcbf1b06 -tool.zh.md: 214b35b28de0c647737bc8297b13b4997947b52e +tool.md: 0d7cbc3f0b86f88fb67aeff6aa61181dff2912ee +tool.zh.md: 30cc871d7b417bdf7f33025b22e3f0965e2b8805 diff --git a/docs/user/develop/basic/tool.md b/docs/user/develop/basic/tool.md index 7b211cfef5..0d7cbc3f0b 100644 --- a/docs/user/develop/basic/tool.md +++ b/docs/user/develop/basic/tool.md @@ -158,7 +158,7 @@ Do not repeat type validation inside `execute`. ## Presentation -A tool can define UI presentation methods for terminal and ACP clients: +A tool can define transport-neutral presentation methods for terminal and web clients: ```ts ignore-check defineTool({ diff --git a/docs/user/develop/basic/tool.zh.md b/docs/user/develop/basic/tool.zh.md index 214b35b28d..30cc871d7b 100644 --- a/docs/user/develop/basic/tool.zh.md +++ b/docs/user/develop/basic/tool.zh.md @@ -158,7 +158,7 @@ async execute(args) { ## 展示层 (Presentation) -Tool 可以定义 UI 渲染方法,用于在终端或 ACP 客户端中展示 tool call 和 result: +Tool 可以定义与传输方式无关的展示方法,供终端和 Web 客户端使用: ```ts ignore-check defineTool({ diff --git a/docs/user/guide/config.i18n.yaml b/docs/user/guide/config.i18n.yaml index cf2658bf4d..695584a6e6 100644 --- a/docs/user/guide/config.i18n.yaml +++ b/docs/user/guide/config.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 -config.md: 8958729d04224215ca420c3103d253a8a5783405 -config.zh.md: 530f2b335453d5064acdac28a60d7df51cd915f0 +config.md: a884cb9c2ec31bd4b12a31cce6290df1d134cf9a +config.zh.md: 3fb9ce69e5f7cb6b92f055ef18595e5ff07d9bbf diff --git a/docs/user/guide/config.md b/docs/user/guide/config.md index 8958729d04..a884cb9c2e 100644 --- a/docs/user/guide/config.md +++ b/docs/user/guide/config.md @@ -10,7 +10,7 @@ The repository examples are runnable configurations and the most reliable starti - [tui-agent](../../../examples/tui-agent/cordis.yml) combines the DeepSeek model, Bash, filesystem, compaction, subagents, workflows, and the interactive TUI. - [headless-agent](../../../examples/headless-agent/cordis.yml) exposes the coding composition as a one-shot task. -- [acp-agent](../../../examples/acp-agent/cordis.yml) connects to editor clients over ACP. +- [acp-agent](../../../examples/acp-agent/cordis.yml) exposes fresh sessions to programmatic ACP clients. A minimal configuration is a list of plugin entries: diff --git a/docs/user/guide/config.zh.md b/docs/user/guide/config.zh.md index 530f2b3354..3fb9ce69e5 100644 --- a/docs/user/guide/config.zh.md +++ b/docs/user/guide/config.zh.md @@ -10,7 +10,7 @@ Harness 使用 `cordis.yml` 描述 Agent 加载哪些插件以及每个插件的 - [tui-agent](../../../examples/tui-agent/cordis.yml) 组合 DeepSeek 模型、Bash、文件系统、压缩、子代理、工作流和交互式 TUI。 - [headless-agent](../../../examples/headless-agent/cordis.yml) 以单次任务形式暴露 coding 组装。 -- [acp-agent](../../../examples/acp-agent/cordis.yml) 通过 ACP 接入编辑器客户端。 +- [acp-agent](../../../examples/acp-agent/cordis.yml) 向程序化 ACP(Agent Client Protocol)客户端提供全新会话。 最小配置由一组插件条目组成: diff --git a/examples/README.md b/examples/README.md index b895259965..8630f235b4 100644 --- a/examples/README.md +++ b/examples/README.md @@ -26,8 +26,8 @@ Run with: `pnpm run demo:cordis` (needs `DEEPSEEK_API_KEY`). See [cordis-agent/R ## acp-agent -An agent demo exposed as an **Agent Client Protocol (ACP)** server over JSON-RPC stdio, via the [`@deepseek-ai/dsh-acp-demo`](../packages/examples/acp-demo) app — drive it from Zed or any other ACP client. It owns the ACP keyless snapshot suite. +An agent exposed as an **Agent Client Protocol (ACP)** automation server over JSON-RPC stdio, via [`@deepseek-ai/dsh-acp-demo`](../packages/examples/acp-demo). Programmatic clients create fresh sessions, send text prompts, consume committed assistant text, answer one-shot permission requests, and cancel work. It owns the ACP keyless snapshot suite. -Run with: `pnpm run demo:acp` (needs `DEEPSEEK_API_KEY`); `pnpm run demo:code-mode acp` boots the same server in Code Mode via the `code-mode.cordis.yml` overlay. See [acp-agent/README.md](acp-agent/README.md) for the Zed setup and the snapshot-test design. +Run with: `pnpm run demo:acp` (needs `DEEPSEEK_API_KEY`); `pnpm run demo:code-mode acp` boots the same server in Code Mode via the `code-mode.cordis.yml` overlay. See [acp-agent/README.md](acp-agent/README.md) for the protocol and snapshot-test contracts. -The default `cordis.yml` composes [`@deepseek-ai/dsh-plan-mode`](../packages/plan/plan-mode), [`@deepseek-ai/dsh-sandbox-local`](../packages/sandbox/sandbox-local), [`@deepseek-ai/dsh-bash-sandbox`](../packages/bash/bash-sandbox), [`@deepseek-ai/dsh-user-approval`](../packages/ui/user-approval), and [`@deepseek-ai/dsh-permission`](../packages/ui/permission). A capable client gets a `default` / `plan` mode picker plus one independent `Permissions` select: plan adds model guidance and the reviewed `exit_plan_mode` crossing without changing enforcement, while `workspace-write` confines bash to the configured workspace and asks before a wider retry. See [acp-agent/README.md](acp-agent/README.md#plan-mode) for the plan-review and elicitation flow. +The default `cordis.yml` composes [`@deepseek-ai/dsh-sandbox-local`](../packages/sandbox/sandbox-local), [`@deepseek-ai/dsh-bash-sandbox`](../packages/bash/bash-sandbox), and [`@deepseek-ai/dsh-user-approval`](../packages/ui/user-approval). `workspace-write` confines bash and filesystem mutations to each session workspace; a wider retry becomes a one-shot machine permission request over ACP. diff --git a/examples/acp-agent/README.md b/examples/acp-agent/README.md index d803da3d0e..52cc51db15 100644 --- a/examples/acp-agent/README.md +++ b/examples/acp-agent/README.md @@ -1,56 +1,28 @@ # acp-agent example -The DeepSeek Harness SDK agent demo exposed as an **Agent Client Protocol (ACP)** server over JSON-RPC stdio — drive it from Zed or any other ACP client. +Automation-oriented [Agent Client Protocol](https://agentclientprotocol.com) server over JSON-RPC stdio. It is intended for parent agents, subagent providers, and other programmatic clients, not as the product UI. ```sh -pnpm run demo:acp # needs DEEPSEEK_API_KEY (repo-root .env or env) -pnpm run demo:code-mode acp # the same server in Code Mode: one wire tool, run_code +pnpm run demo:acp # needs DEEPSEEK_API_KEY (repo-root .env or env) +pnpm run demo:code-mode acp # same protocol with the Code Mode tool transport ``` -The leaf config loads the ACP app, DeepSeek adapter, plan mode, sandboxed bash, the sandboxed filesystem stack, approval and permission services, model-facing tools, and repeat guard. The app bundles the agent spine, JSONL persistence, and bridge, creates agents on `session/new`, and keeps stdout logger-free. [`fs.cordis.yml`](fs.cordis.yml) adds local tool-result spill storage for its dedicated scenarios; [`code-mode.cordis.yml`](code-mode.cordis.yml) adds `run_code` and its generated TypeScript SDK. See [Code Mode](../../packages/core/tools/README.md#code-mode). +The leaf loads the ACP app, DeepSeek adapter, sandboxed bash and filesystem stacks, one-shot approval policy, compaction, subagents, workflows, hooks, a derived session-query index, workspace-authorized session-query tools, generic timeout and local spill policies, and repeat guard. The app creates one fresh agent per `session/new`, persists sessions to JSONL, and keeps stdout protocol-pure. [`fs.cordis.yml`](fs.cordis.yml) redirects spill storage and lowers the inline threshold for dedicated filesystem scenarios; [`code-mode.cordis.yml`](code-mode.cordis.yml) adds `run_code` and its generated TypeScript SDK. -## stdout is the protocol +## Protocol channel -This example loads **no stdout logger** — `stdout` carries the JSON-RPC frames, and any other write corrupts them. `@deepseek-ai/dsh-acp-demo` includes no logger entry, so this leaf has none to get wrong by default; do not add one (use a stderr exporter if you need logs). +Stdout carries only newline-delimited ACP JSON-RPC. `@deepseek-ai/dsh-acp-demo` installs no stdout logger; leaf additions must use stderr for diagnostics. -## Zed configuration +The automation contract — supported methods, baseline prompt content, committed-text output, and the intentionally absent UI surfaces — lives in [`@deepseek-ai/dsh-acp`](../../packages/acp/acp/README.md). -Add to your Zed `settings.json` under `agent_servers`: +## Session workspaces and permissions -```json -{ - "agent_servers": { - "DeepSeek Harness": { - "command": "pnpm", - "args": ["--dir", "/path/to/deepseek-harness", "run", "demo:acp"], - "env": { "DEEPSEEK_API_KEY": "sk-…" } - } - } -} -``` +Each `session/new` supplies an absolute `cwd`. Sandboxed bash and filesystem mutations resolve `workspace-write` against that session cwd, so concurrent sessions can use separate project roots; platform temporary roots remain shared writable scratch space ([sandbox contract](../../packages/sandbox/sandbox/README.md)). `DSH_PERMISSION_MODE` selects `workspace-write` or `danger-full-access` for deployment and tests. -The editor sets each session's `cwd` to the project it opens. That directory is both bash's default workdir and the session's primary `workspace-write` boundary: every bash or filesystem mutation carries one policy resolved from the calling session, so a single server process may serve concurrent projects. Projects outside the platform temporary areas do not grant either session writes into the other; `/tmp` and `os.tmpdir()` remain shared writable scratch roots under `workspace-write`, so projects placed there are not mutually isolated ([writable-root contract](../../packages/sandbox/sandbox/README.md)). The configured `workspaceRoot: process.cwd()` remains the fallback for calls without a session cwd. The filesystem tools ride the same policy through [`@deepseek-ai/dsh-fs-sandbox`](../../packages/fs/fs-sandbox/), so `read`/`write`/`edit` are available under every mode and confined to the same policy. +Under `workspace-write`, a model retry requesting wider sandbox access triggers `session/request_permission` with `allow_once` and `reject_once`. The client decides programmatically; dismissal or an unavailable answer fails closed. The selected outcome applies only to that retry and is recorded through the normal tool-result/audit path. The server never exposes a permission picker or persists client policy. -## Plan mode +## Snapshot tests -The same `demo:acp` server composes [`@deepseek-ai/dsh-plan-mode`](../../packages/plan/plan-mode/), so a capable client advertises `default` and `plan` in its mode picker. ACP owns those protocol ids and projects them onto the plugin's boolean plan state. This composition owns the complete plan instructions in [`cordis.yml`](cordis.yml): remain in plan mode, inspect before asking, avoid mutations, resolve discoverable repository facts, and submit a decision-complete plan through `exit_plan_mode`. Those are the instrumental behaviors shared by the local Codex and Claude Code references; product-specific plan files, phase machinery, and protocol tags stay out of the plugin contract. +This example owns the ACP snapshot suite. It boots the real automation server, replays committed model streams through `dsh-llm-replay`, and compares both normalized protocol output and re-persisted session logs. Recording uses the real model; refresh reuses committed replay input. Overrides cover throw/hang behavior, and optional `workspace/` fixtures seed world-state checks. -Plan mode adds only that configured guidance section. Every tool, including `exit_plan_mode`, keeps the same schema while plan mode is inactive or active; the exit tool describes itself as plan-only and rejects if called while inactive. Stable native schemas and Code Mode SDK bindings avoid tool-catalog churn at the transition. `ask_user_question` carries blocking user-owned choices through ACP elicitation, while `exit_plan_mode` renders the exact logged plan for approval and returns keep-planning feedback to the model. The mode picker and permission select remain independent: switching plan state never changes sandbox or approval state, and deployments that need a hard read-only planning floor configure that policy separately. The [plan-mode Agent Note](../../.agents/notes/implemented/feature/2026-07-07-plan-mode.md) owns the state and review contract. - -## Snapshot tests (record-once / replay-deterministic) - -This example hosts the ACP snapshot suite, including the picker advertisement and both plan-review branches. It replays through `dsh-llm-replay`, which reconstructs model streams from `assistant/chunk` events in each scenario's session JSONL. Recording runs the real ACP agent and harvests its logs; refresh keeps the committed transcript as mock input and rewrites current replay outputs. `replay.override.json` covers throw and hang cases that chunks cannot express, and an optional `workspace/` seeds files. The [snapshot Agent Note](../../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md) owns the ACP harness design. - -## Permissions and sandboxing - -The default tree composes [`@deepseek-ai/dsh-sandbox-local`](../../packages/sandbox/sandbox-local/), [`@deepseek-ai/dsh-sandbox-policy`](../../packages/sandbox/sandbox-policy/), [`@deepseek-ai/dsh-bash-sandbox`](../../packages/bash/bash-sandbox/), [`@deepseek-ai/dsh-fs-sandbox`](../../packages/fs/fs-sandbox/), [`@deepseek-ai/dsh-user-approval`](../../packages/ui/user-approval/), and [`@deepseek-ai/dsh-permission`](../../packages/ui/permission/). Bash and the `read`/`write`/`edit` tools start in `workspace-write`; a denied operation returns a structured marker, and a retry with `sandbox_permissions` plus `justification` becomes a one-shot `session/request_permission` prompt in the editor. "Allow once" runs exactly that retry under the wider mode ([sandbox Agent Note § Escalation](../../.agents/notes/implemented/feature/2026-07-06-sandbox.md)). - -- **One session config option is live**: a capable client shows one `Permissions` select. `workspace-write` means workspace-confined bash plus `ask`; `danger-full-access` means unconfined bash plus `never`. Switching writes one `permission/preset` event through to the sandbox-mode and approval-policy events, and `session/load` reports the resumed value. -- **Every approval is one-shot**: the choices are `Allow once` and `Reject`; a dismissal, rejection, missing editor, or unavailable runner fails closed. -- **The boundary spans bash and the filesystem tools per session**: bash confines through the OS runner and the `read`/`write`/`edit` tools through an in-process path fence ([`dsh-fs-sandbox`](../../packages/fs/fs-sandbox/)); both receive the calling session's cwd as `workspaceRoot`. - -`tests/escalation.e2e.ts` boots this default tree keyless, drives the permission select, and—with a key and usable runner—proves both approval outcomes against the filesystem. The agent-spine e2e independently boots one context with two home-directory project sessions and world-verifies concurrent own-root success plus sibling-root denial through both shipped tool families. The keyless `session-sandbox-root` ACP snapshot places its generated project under the user home while an overlay points the deployment fallback at `/tmp`; its successful `workspace-write` call proves the assembled app used the session cwd. Most snapshots start at `danger-full-access` so bash fixtures remain runner-independent. No fixture pins real runner denial text because its dialect is platform-specific. - -## MVP limitations - -The bridge supports N concurrent sessions per connection, each with its own `cwd` (RFC 011). Prompts support ACP's baseline `text` and `resource_link` blocks only; `additionalDirectories` and `mcpServers` are rejected. See [`packages/ui/acp/README.md`](../../packages/ui/acp/README.md) for the full contract. +Most scenarios pin backend behavior rather than ACP-specific behavior; the [automation-only ACP decision](../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md#snapshot-boundary) owns why that coverage remains transport-coupled. diff --git a/examples/acp-agent/composition.md b/examples/acp-agent/composition.md index b81676f382..ba9ece13b5 100644 --- a/examples/acp-agent/composition.md +++ b/examples/acp-agent/composition.md @@ -1,9 +1,9 @@ <!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand. Run `pnpm run gen-doc-graphs` to regenerate. --> -# ACP Agent App Composition +# ACP Automation App Composition -The ACP demo exposes the same agent spine over JSON-RPC stdio, with no stdout logger and no pre-created agent; clients create sessions through the ACP bridge. +The ACP demo exposes fresh baseline-prompt agent sessions to programmatic clients over JSON-RPC stdio, with no stdout logger, human UI, or pre-created agent. ```mermaid flowchart LR @@ -18,13 +18,11 @@ flowchart LR cfg --> plugin_acp_bash plugin_acp_approval["approval<br/>@deepseek-ai/dsh-user-approval"] cfg --> plugin_acp_approval - plugin_acp_permission["permission<br/>@deepseek-ai/dsh-permission"] - cfg --> plugin_acp_permission plugin_acp_acp_agent["acp-agent<br/>@deepseek-ai/dsh-acp-demo"] cfg --> plugin_acp_acp_agent plugin_acp_acp_agent --> bundle_agent_core["@deepseek-ai/dsh-agent-spine-demo"] plugin_acp_acp_agent --> bundle_jsonl["@deepseek-ai/dsh-session-persistence-jsonl"] - plugin_acp_acp_agent --> frontdoor_acp["@deepseek-ai/dsh-acp<br/>JSON-RPC stdio bridge<br/>sessions created by client"] + plugin_acp_acp_agent --> frontdoor_acp["@deepseek-ai/dsh-acp<br/>automation-only JSON-RPC stdio<br/>fresh sessions created by client"] bundle_agent_core --> spine_llm["ctx.llm"] bundle_agent_core --> spine_sessions["ctx.sessions"] bundle_agent_core --> spine_tools["ctx.tools + tool-bash"] @@ -37,10 +35,6 @@ flowchart LR cfg --> plugin_acp_spill_local plugin_acp_spill_policy["spill-policy<br/>@deepseek-ai/dsh-spill-policy"] cfg --> plugin_acp_spill_policy - plugin_acp_plan_mode["plan-mode<br/>@deepseek-ai/dsh-plan-mode"] - cfg --> plugin_acp_plan_mode - plugin_acp_tool_ask_user["tool-ask-user<br/>@deepseek-ai/dsh-tool-ask-user"] - cfg --> plugin_acp_tool_ask_user plugin_acp_token_meter["token-meter<br/>@deepseek-ai/dsh-token-meter"] cfg --> plugin_acp_token_meter plugin_acp_compact_basic["compact-basic<br/>@deepseek-ai/dsh-compact-basic"] @@ -84,14 +78,11 @@ flowchart LR | `sandbox-policy` | `@deepseek-ai/dsh-sandbox-policy` | | `bash` | `@deepseek-ai/dsh-bash-sandbox` | | `approval` | `@deepseek-ai/dsh-user-approval` | -| `permission` | `@deepseek-ai/dsh-permission` | | `acp-agent` | `@deepseek-ai/dsh-acp-demo` | | `tool-session-query` | `@deepseek-ai/dsh-tool-session-query` | | `timeout-policy` | `@deepseek-ai/dsh-timeout-policy` | | `spill-local` | `@deepseek-ai/dsh-spill-local` | | `spill-policy` | `@deepseek-ai/dsh-spill-policy` | -| `plan-mode` | `@deepseek-ai/dsh-plan-mode` | -| `tool-ask-user` | `@deepseek-ai/dsh-tool-ask-user` | | `token-meter` | `@deepseek-ai/dsh-token-meter` | | `compact-basic` | `@deepseek-ai/dsh-compact-basic` | | `subagent` | `@deepseek-ai/dsh-subagent` | diff --git a/examples/acp-agent/cordis.yml b/examples/acp-agent/cordis.yml index 3e7235c35c..484809db04 100644 --- a/examples/acp-agent/cordis.yml +++ b/examples/acp-agent/cordis.yml @@ -1,7 +1,8 @@ -# ACP server and snapshot-record composition. With `DSH_SNAPSHOT=record`, the -# app bin runs the real DeepSeek adapter and the harness harvests its persisted -# log. The bin loads the gitignored root `.env` before this config. This tree has -# no stdout logger or HMR because stdout carries ACP JSON-RPC. +# ACP automation server and backend snapshot-record composition. With +# `DSH_SNAPSHOT=record`, the app bin runs the real DeepSeek adapter and the +# harness harvests its persisted log. The bin loads the gitignored root `.env` +# before this config. This tree has no stdout logger or HMR because stdout +# carries ACP JSON-RPC. # The DeepSeek adapter. Shipped default: full thinking at max effort on every # request (wire-only defaults; they never enter the request header). @@ -42,10 +43,7 @@ config: policy: !!js "(process.env.DSH_PERMISSION_MODE ?? (process.env.DSH_SNAPSHOT === undefined ? 'workspace-write' : 'danger-full-access')) === 'danger-full-access' ? 'never' : 'ask'" -- id: permission - name: '@deepseek-ai/dsh-permission' - -# The ACP server app: the agent-spine-demo spine + JSONL persistence + the ACP bridge. +# The ACP automation app: agent spine + JSONL persistence + protocol bridge. # Persistence root: $DSH_SNAPSHOT_SESSIONS_ROOT when the snapshot harness sets it # (so it can harvest / isolate the log), else ./.sessions for the demo. # Snapshot modes use raw JSONL fixtures; ordinary runs keep the compressed default. @@ -65,8 +63,8 @@ Verify your work by running the code or tests. Keep answers brief and factual. -# Workspace-authorized prior-session search and exact trace/read tools. The app -# above owns ctx.sessionQuery; this leaf owns the model-facing consumer. +# The automation app opens ctx.sessionQuery before its ACP transport; this leaf +# owns the workspace-authorized model-facing consumer. - id: tool-session-query name: '@deepseek-ai/dsh-tool-session-query' @@ -77,35 +75,14 @@ - id: spill-local name: '@deepseek-ai/dsh-spill-local' + config: + root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT - id: spill-policy name: '@deepseek-ai/dsh-spill-policy' config: maxInlineBytes: 50000 -# Plan mode is additive to the canonical ACP server. The ACP bridge projects -# it onto the protocol picker; sandbox and approval remain independent options. -- id: plan-mode - name: '@deepseek-ai/dsh-plan-mode' - config: - section: | - You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. - - Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery. - - The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed only to keep the request shape stable. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode. - - Resolve discoverable facts by inspection. Use ask_user_question only for user-owned choices or material ambiguity that inspection cannot answer. Do not ask the user where code lives or how current behavior works when you can find out. - - Make the plan decision-complete: state the goal and success criteria; group implementation changes by subsystem; identify public API, schema, and data-flow changes; cover edge cases, failure modes, tests, acceptance criteria, and explicit assumptions. Keep it concise enough to review but detailed enough that another engineer can implement it without making design decisions. - - When ready, call exit_plan_mode with the complete plan markdown, starting with a # title. Make exit_plan_mode the only and final tool call in that assistant response: it presents the plan for approval, and implementation begins only in a later step after approval. Do not paste the final plan as a plain reply or ask "should I proceed?" through prose or ask_user_question. If review rejects it, incorporate the feedback and present again. If the review channel is unavailable or aborted, stay in plan mode and ask the user to switch modes manually; do not proceed with implementation. - -# Blocking plan decisions and ordinary clarifications share ACP's elicitation -# provider through the model-facing question tool. -- id: tool-ask-user - name: '@deepseek-ai/dsh-tool-ask-user' - # Replay-aware request pressure; the routed adapter supplies model capacity. - id: token-meter name: '@deepseek-ai/dsh-token-meter' @@ -163,7 +140,7 @@ - id: tool-ralph name: '@deepseek-ai/dsh-tool-ralph' -# `todo_write` replaces the logged whole list and surfaces an ACP `plan` update. +# `todo_write` replaces the logged whole list for later model requests. - id: tool-todo name: '@deepseek-ai/dsh-tool-todo' diff --git a/examples/acp-agent/fs.cordis.snapshot.yml b/examples/acp-agent/fs.cordis.snapshot.yml index 0417074edd..29cef3fe82 100644 --- a/examples/acp-agent/fs.cordis.snapshot.yml +++ b/examples/acp-agent/fs.cordis.snapshot.yml @@ -1,7 +1,6 @@ -# Keyless filesystem snapshots apply the spill and replay overlays directly -# because include patches cannot target entries behind a nested include. The -# sandboxed filesystem stack already lives in the base cordis.yml. This file also -# re-pins the acp-agent model to `deepseek-v4-flash`: `cordis.yml` ships +# Keyless filesystem snapshots patch the base spill stack and apply the replay +# overlay directly. The sandboxed filesystem stack already lives in the base +# cordis.yml. This file also re-pins the acp-agent model to `deepseek-v4-flash`: `cordis.yml` ships # `deepseek-v4-pro`, but the recorded corpus was captured on flash, and a config # patch replaces the whole app config, so the base fields are restated verbatim. - id: base @@ -25,15 +24,15 @@ You are a coding assistant powered by the {{model}} model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. Verify your work by running the code or tests. Keep answers brief and factual. + - id: spill-local + name: '@deepseek-ai/dsh-spill-local' + config: + root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT ?? './.spill' + - id: spill-policy + name: '@deepseek-ai/dsh-spill-policy' + config: + maxInlineBytes: 800 - insert: - - id: spill-local - name: '@deepseek-ai/dsh-spill-local' - config: - root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT ?? './.spill' - - id: spill-policy - name: '@deepseek-ai/dsh-spill-policy' - config: - maxInlineBytes: 800 - id: llm-replay name: '@deepseek-ai/dsh-llm-replay' config: diff --git a/examples/acp-agent/fs.cordis.yml b/examples/acp-agent/fs.cordis.yml index 0d667255c8..4528ccf7c0 100644 --- a/examples/acp-agent/fs.cordis.yml +++ b/examples/acp-agent/fs.cordis.yml @@ -1,17 +1,16 @@ -# Filesystem-scenario overlay: the sandboxed filesystem stack already lives in -# the base cordis.yml, so this overlay adds only the local tool-result spill -# storage those scenarios exercise. +# Filesystem-scenario overlay: the sandboxed filesystem and generic spill stacks +# already live in the base cordis.yml, so this overlay only redirects spill +# storage and lowers the inline threshold for dedicated scenarios. - id: base name: '@cordisjs/plugin-include' config: path: ./cordis.yml patches: - - insert: - - id: spill-local - name: '@deepseek-ai/dsh-spill-local' - config: - root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT ?? './.spill' - - id: spill-policy - name: '@deepseek-ai/dsh-spill-policy' - config: - maxInlineBytes: !!js process.env.DSH_SNAPSHOT && 800 || 50000 + - id: spill-local + name: '@deepseek-ai/dsh-spill-local' + config: + root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT ?? './.spill' + - id: spill-policy + name: '@deepseek-ai/dsh-spill-policy' + config: + maxInlineBytes: !!js process.env.DSH_SNAPSHOT && 800 || 50000 diff --git a/examples/acp-agent/package.json b/examples/acp-agent/package.json index 8ee54f5650..1bbb85d6a9 100644 --- a/examples/acp-agent/package.json +++ b/examples/acp-agent/package.json @@ -1,6 +1,6 @@ { "name": "acp-agent-example", - "description": "Runnable demo: an agent as an ACP server over JSON-RPC stdio (Zed & other ACP editors)", + "description": "Runnable demo: an ACP automation server over JSON-RPC stdio", "private": true, "version": "0.0.1", "type": "module" diff --git a/examples/acp-agent/tests/acp.e2e.ts b/examples/acp-agent/tests/acp.e2e.ts index 46592e4704..b51498e90c 100644 --- a/examples/acp-agent/tests/acp.e2e.ts +++ b/examples/acp-agent/tests/acp.e2e.ts @@ -66,8 +66,8 @@ describe('acp-agent over real stdio (no key required)', () => { }, 30_000) it('session/new succeeds over real stdio (no model call)', async () => { - // REGRESSION GUARD (this exact RPC crashed a real Zed session with - // "cannot get property \"agents\" without inject"): `session/new` drives the + // REGRESSION GUARD (this exact RPC exposed the missing-inject Loader bug): + // `session/new` drives the // full bridge → `ctx.agents.create({sessionId, meta:{cwd}})` → AgentLoop → // registry/persistence path, ALL of which run from the JSON-RPC read loop // OUTSIDE the bridge plugin's injection scope. A lazy `ctx.<service>` read @@ -118,60 +118,9 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('acp-agent e2e: real prompt over const proof = await readFile(join(workdir, 'proof.txt'), 'utf8') expect(proof).toContain('ACP_OK') - // And the client saw tool-call activity stream through. - const toolCalls = updates.filter(u => u.sessionUpdate === 'tool_call') - expect(toolCalls.length).toBeGreaterThan(0) - - // Tool-call UI quality (the tool owns its presentation): the bash tool's - // `presentCall` sets the title to the exact command (an execute card hides - // rawInput, so the command IS the title) — NOT the bare tool name "bash". - // A `bash` call must therefore carry an execute kind, a non-"bash" title, - // and a string rawInput (the command). `toolCalls` is already narrowed to - // the `tool_call` shape by the filter above, so these fields are reachable. - const bashCall = toolCalls.find(u => u.kind === 'execute') - expect(bashCall).toBeDefined() - if (bashCall === undefined) throw new Error('expected an execute tool_call') - expect(typeof bashCall.title).toBe('string') - expect(bashCall.title.length).toBeGreaterThan(0) - expect(bashCall.title).not.toBe('bash') // the old, unhelpful title - expect(typeof bashCall.rawInput).toBe('string') // the exact command - // Capability OFF: no terminal _meta — the ```console text path renders. - expect((bashCall as { _meta?: unknown })._meta).toBeUndefined() - }, 180_000) - - it('with the terminal_output capability, a real bash call renders as a terminal card (content + _meta + exit)', async () => { - workdir = await mkdtemp(join(tmpdir(), 'acp-e2e-')) - spawned = launchAcpTestAgent({ agent: AGENT, cwd: workdir, env: DANGER_FULL_ACCESS_ENV }) - const { client, updates } = spawned - - // Advertise the Zed `_meta.terminal_output` capability so the bridge emits - // the terminal card for the real bash tool. - await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: { _meta: { terminal_output: true } } }) - const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] }) - const res = await client.prompt({ - sessionId, - prompt: [{ type: 'text', text: 'Use the bash tool to run: echo ACP_TERMINAL_OK. Then stop.' }], - }) - expect(['end_turn', 'max_tokens']).toContain(res.stopReason) - - // A bash tool_call now carries a terminal content block + _meta.terminal_info - // with the session cwd as the header; the matching update streams the output - // on _meta.terminal_output. - const bashCall = updates.find(u => u.sessionUpdate === 'tool_call' && u.kind === 'execute') - if (bashCall?.sessionUpdate !== 'tool_call') throw new Error('expected an execute tool_call') - // The content carries the description text block AND a terminal block (the - // description renders above the card) — find the terminal block by type, not - // by position. - const blocks = (bashCall.content ?? []) as { type: string; terminalId?: string }[] - const terminalBlock = blocks.find(b => b.type === 'terminal') - expect(terminalBlock).toBeDefined() - expect(typeof terminalBlock?.terminalId).toBe('string') - const info = (bashCall._meta as { terminal_info?: { terminal_id: string; cwd?: string } }).terminal_info - expect(info?.cwd).toBe(workdir) - const updatesForTerminal = updates.filter(u => u.sessionUpdate === 'tool_call_update' && (u._meta as { terminal_output?: unknown } | undefined)?.terminal_output !== undefined) - expect(updatesForTerminal.length).toBeGreaterThan(0) - // The completed update also carries the parsed exit on _meta.terminal_exit. - const exitUpdate = updates.find(u => u.sessionUpdate === 'tool_call_update' && (u._meta as { terminal_exit?: unknown } | undefined)?.terminal_exit !== undefined) - expect(exitUpdate).toBeDefined() + // The transport exposes only committed assistant text; tool execution is + // proved by the world effect above and remains session-log data. + expect(updates.length).toBeGreaterThan(0) + expect(updates.every(update => update.sessionUpdate === 'agent_message_chunk')).toBe(true) }, 180_000) }) diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index 236eb55644..bd422100a5 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -42,6 +42,9 @@ const LSP_CONFIG = fileURLToPath(new URL('./lsp.cordis.yml', import.meta.url)) const SNAPSHOTS_DIR = join(dirname(fileURLToPath(import.meta.url)), 'snapshots') const PACKED_CHUNKS_SOURCE = 'hook-cc-pretool-deny' +// FIXME: Migrate backend-oriented scenarios to the headless stream-json suite; +// this ACP suite should eventually retain only automation-protocol contracts. + function fixtureRecords(name: string): unknown[] { return readFileSync(join(SNAPSHOTS_DIR, name, 'session.jsonl'), 'utf8') .trimEnd() @@ -67,22 +70,6 @@ function snapshotModeFromEnv(value: string | undefined): SnapshotSuiteOptions['m const SCENARIOS: Scenario[] = [ { name: 'handshake', hasModelTurn: false, recorded: false }, { name: 'reject-extra-dirs', hasModelTurn: false, recorded: false }, - // Direct command dispatch reports goal state without spending a model turn. - { name: 'goal-command-status', hasModelTurn: false, recorded: false }, - // Protocol-only (keyless, authored): session/new advertises the mode picker, - // session/set_mode acknowledges a valid selection, and an unknown mode id - // fails loudly. With no model turn, its membership in the plan header class - // is vacuous; the class still needs one explicit pin below. - { name: 'modes-advertise', hasModelTurn: false, recorded: false, headerClass: 'plan' }, - // The plan header pin covers the full arc: setMode(plan), a real read under - // the independently configured sandbox, plan review through exit_plan_mode, - // an approved boundary flip back to default, and a real edit in the next - // step. Leaving plan removes the policy section and exit tool, producing one - // changed request header. - { name: 'plan-mode', hasModelTurn: true, recorded: true, pinsHeader: true, headerClass: 'plan', expectedHeaderChanges: 1 }, - // Free-text review feedback returns as a corrective error and leaves the - // session in plan mode, so this scenario shares the pinned plan header. - { name: 'plan-mode-reject', hasModelTurn: true, recorded: true, headerClass: 'plan' }, // text-turn is the pinned-header scenario: the minimal single text turn. // Its prompt and tool-schema sidecars pin the composed header. { name: 'text-turn', hasModelTurn: true, recorded: true, pinsHeader: true }, @@ -115,15 +102,14 @@ const SCENARIOS: Scenario[] = [ headerClass: 'pty', configPath: PTY_CONFIG, }, - { name: 'fs-terminal-card', hasModelTurn: true, recorded: true }, - { name: 'todo-plan', hasModelTurn: true, recorded: true }, + { name: 'bash-tool-turn', hasModelTurn: true, recorded: true }, + { name: 'todo-write', hasModelTurn: true, recorded: true }, { name: 'skill-load', hasModelTurn: true, recorded: false, pinsHeader: true, headerClass: 'skill' }, { name: 'lsp-definition', hasModelTurn: true, recorded: false, pinsHeader: true, headerClass: 'lsp', configPath: LSP_CONFIG }, { name: 'workspace-edit', hasModelTurn: true, recorded: true, - pinsNativeWindowsStdout: true, }, { name: 'fs-read', hasModelTurn: true, recorded: true }, { name: 'fs-write', hasModelTurn: true, recorded: true }, @@ -132,17 +118,6 @@ const SCENARIOS: Scenario[] = [ { name: 'fs-read-window', hasModelTurn: true, recorded: true }, { name: 'fs-policy-reject', hasModelTurn: true, recorded: true }, { name: 'multi-turn', hasModelTurn: true, recorded: true }, - // ACP exposes the adapter catalog as a session-scoped model select. This - // scenario pins the default flash request, the switch response, and the - // resulting changed request-header snapshot for pro. - { - name: 'model-switching', - hasModelTurn: true, - recorded: true, - pinsHeader: true, - expectedHeaderChanges: 1, - headerClass: 'model-switching', - }, { name: 'error-finish', hasModelTurn: true, recorded: false, overridden: true }, // Keyless, authored (like error-finish/cancel): deterministically forcing a // LIVE model to repeat one call three times is not a stable recording, so @@ -238,16 +213,30 @@ const SCENARIOS: Scenario[] = [ configPath: CODE_MODE_WORKSPACE_CONTEXT_CONFIG, }, { name: 'both-mode-turn', hasModelTurn: true, recorded: true, pinsHeader: true, headerClass: 'both', configPath: BOTH_MODE_CONFIG }, - // The default tree also owns the Permissions select. Snapshot mode starts in - // danger-full-access so established fixtures stay runner-independent; these - // policy scenarios switch to workspace-write in their input scripts. - // Real-kernel confinement remains in escalation.e2e.ts and the sandbox - // packages' e2e suites. - { name: 'config-options', hasModelTurn: false, recorded: false, headerClass: 'sandbox' }, - { name: 'permission-switching', hasModelTurn: true, recorded: true, pinsHeader: true, expectedHeaderChanges: 1, headerClass: 'sandbox' }, - { name: 'escalation-approved', hasModelTurn: true, recorded: true, headerClass: 'sandbox' }, - { name: 'escalation-rejected', hasModelTurn: true, recorded: true, headerClass: 'sandbox' }, - { name: 'fs-escalation-approved', hasModelTurn: true, recorded: true, headerClass: 'sandbox' }, + // Machine permission scenarios use an explicit deployment policy; there is + // no session-scoped UI picker on the automation protocol. + { + name: 'escalation-approved', + hasModelTurn: true, + recorded: true, + pinsHeader: true, + headerClass: 'sandbox', + env: { DSH_PERMISSION_MODE: 'workspace-write' }, + }, + { + name: 'escalation-rejected', + hasModelTurn: true, + recorded: true, + headerClass: 'sandbox', + env: { DSH_PERMISSION_MODE: 'workspace-write' }, + }, + { + name: 'fs-escalation-approved', + hasModelTurn: true, + recorded: true, + headerClass: 'sandbox', + env: { DSH_PERMISSION_MODE: 'workspace-write' }, + }, // Unlike ordinary snapshots, this session cwd is outside the platform temp // roots that workspace-write always grants. The overlay points the // deployment fallback at /tmp, so a successful relative write proves the @@ -259,6 +248,7 @@ const SCENARIOS: Scenario[] = [ overridden: true, headerClass: 'sandbox', configPath: SESSION_SANDBOX_ROOT_CONFIG, + env: { DSH_PERMISSION_MODE: 'workspace-write' }, workspaceParent: homedir(), }, ] diff --git a/examples/acp-agent/tests/escalation.e2e.ts b/examples/acp-agent/tests/escalation.e2e.ts index 1bf0a5ac16..ee2d6122bc 100644 --- a/examples/acp-agent/tests/escalation.e2e.ts +++ b/examples/acp-agent/tests/escalation.e2e.ts @@ -25,7 +25,7 @@ import { cleanupAcpExampleTest } from './cleanup.ts' * model nor a sandbox runner is ever exercised. * * With-key escalation flow (self-skips without DEEPSEEK_API_KEY or a usable - * platform runner): a scripted ACP client plays the human. The subprocess + * platform runner): a scripted ACP client supplies machine policy. The subprocess * starts read-only, its first real bash write is denied, the model retries with * `sandbox_permissions` + `justification`, and the bridge prompts THIS client * over `session/request_permission`. An approved workspace-write retry must @@ -74,8 +74,8 @@ function launchExampleAcpAgent( requestPermission(params) { permissionRequests.push(params) const option = params.options.find(o => o.optionId === answer) - // The scripted human: pick the requested option when the prompt offers - // it; an unexpected prompt shape cancels (fail closed, never grants). + // The scripted machine policy selects the requested option; an + // unexpected request shape cancels (fail closed, never grants). if (option === undefined) return Promise.resolve({ outcome: { outcome: 'cancelled' } }) return Promise.resolve({ outcome: { outcome: 'selected', optionId: option.optionId } }) }, @@ -89,11 +89,6 @@ function escalationPrompt(path: string, content: string): string { + 'with sandbox_permissions set to workspace-write and a one-sentence justification.' } -function includesReadOnlyDenial(updates: LaunchedAcpTestAgent['updates']): boolean { - return updates.some(update => update.sessionUpdate === 'tool_call_update' - && JSON.stringify(update.content).includes('[sandbox: file access denied under read-only mode]')) -} - let spawned: Spawned | undefined let workdir: string | undefined @@ -112,46 +107,20 @@ describe('default sandbox composition keyless smoke (real cordis.yml via the Loa const { client } = spawned // A dummy key boots the adapter; no prompt is ever sent, so no model call // and no sandbox runner probe happen. This drives the fiber tree the same - // way an editor would, which is what catches a broken export/inject shape. + // way an ACP caller would, which catches a broken export/inject shape. const init = await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) expect(init.protocolVersion).toBe(PROTOCOL_VERSION) + expect(init.agentCapabilities).toEqual({ + promptCapabilities: { image: false, audio: false, embeddedContext: false }, + }) const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] }) expect(sessionId.length).toBeGreaterThan(0) }, 30_000) - it('advertises model and Permissions selects and honors a permission switch without a model call', async () => { - workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-config-')) - spawned = launchExampleAcpAgent(workdir, 'reject-once') - const { client } = spawned - await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - // This tree composes the permission presets over bash-sandbox + approval → - // ONE select advertises, current from the configured default preset. - const created = await client.newSession({ cwd: workdir, mcpServers: [] }) - const advertised = created.configOptions ?? [] - const modelValue = JSON.stringify(['deepseek', 'deepseek-v4-pro']) - expect(advertised.map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined])) - .toEqual([['model', modelValue], ['permission', 'workspace-write']]) - // A switch responds with the COMPLETE refreshed state (the spec contract), - // and the new current survives in the response of a second switch. - const afterFullAccess = await client.setSessionConfigOption({ - sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access', - }) - expect(afterFullAccess.configOptions?.find(option => option.id === 'permission')) - .toMatchObject({ currentValue: 'danger-full-access' }) - const again = await client.setSessionConfigOption({ - sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access', - }) - expect((again.configOptions ?? []).map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined])) - .toEqual([['model', modelValue], ['permission', 'danger-full-access']]) - // An out-of-vocabulary value is a protocol error, never a silent default. - await expect(client.setSessionConfigOption({ - sessionId: created.sessionId, configId: 'permission', value: 'plan', - })).rejects.toThrow(/unknown permission value/) - }, 30_000) }) describe.skipIf(!process.env.DEEPSEEK_API_KEY || !hasRunner)('default sandbox composition e2e: the live approval loop', () => { - it('denial → model escalation → editor prompt → allow-once → the retried write lands on disk', async () => { + it('denial → model escalation → machine allow-once → the retried write lands on disk', async () => { workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-')) spawned = launchExampleAcpAgent(workdir, 'allow-once', 'read-only') const { client, permissionRequests, updates } = spawned @@ -166,14 +135,14 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || !hasRunner)('default sandbox co }], }) expect(['end_turn', 'max_tokens']).toContain(res.stopReason) - expect(includesReadOnlyDenial(updates)).toBe(true) + expect(updates.every(update => update.sessionUpdate === 'agent_message_chunk')).toBe(true) // The WORLD: the approved escalated retry landed the write. const proof = await readFile(join(workdir, 'escalated.txt'), 'utf8') expect(proof).toContain('ACP_ESCALATION_OK') // The CHANNEL: the grant came through a real session/request_permission - // prompt attached to the escalating tool call, offering exactly the + // request attached to the escalating tool call, offering exactly the // one-shot options. expect(permissionRequests.length).toBeGreaterThan(0) const prompt = permissionRequests[0] @@ -198,11 +167,11 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || !hasRunner)('default sandbox co }], }) expect(['end_turn', 'max_tokens']).toContain(res.stopReason) - expect(includesReadOnlyDenial(updates)).toBe(true) + expect(updates.every(update => update.sessionUpdate === 'agent_message_chunk')).toBe(true) // The WORLD: rejected means the file never appeared. await expect(readFile(join(workdir, 'refused.txt'), 'utf8')).rejects.toThrow() - // And the rejection really flowed through a prompt (not a missing channel). + // And the rejection flowed through the machine-policy channel. expect(permissionRequests.length).toBeGreaterThan(0) }, 240_000) }) diff --git a/examples/acp-agent/tests/fixtures/live-mode-switching-2026-07-07.session.jsonl b/examples/acp-agent/tests/fixtures/live-mode-switching-2026-07-07.session.jsonl deleted file mode 100644 index cb28e3c646..0000000000 --- a/examples/acp-agent/tests/fixtures/live-mode-switching-2026-07-07.session.jsonl +++ /dev/null @@ -1,2212 +0,0 @@ -{"type":"session","version":0,"id":"ed16a7e7-a76f-459f-b889-d4c424d66ef6","createdAt":1783421406247,"cwd":"/Users/wwl/workspace/deepseek-harness","delegationDepth":0} -{"type":"turn/start","seq":0,"time":1783421410388,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":1,"time":1783421410388,"data":{"content":[{"type":"text","text":"你好"}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"step/start","seq":2,"time":1783421410389,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":3,"time":1783421410389,"data":{"header":{"config":{"model":"deepseek-v4-flash"},"system":"You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou are a coding assistant powered by the deepseek-v4-flash model. Your working\ndirectory is /Users/wwl/workspace/deepseek-harness. Your bash tool runs under a file sandbox — a\n`[sandbox: file access denied …]` result is policy, not a command bug.\n\nVerify your work by running the code or tests. Keep answers brief and\nfactual.\n\n\nCheck the [exit code: N] marker on every bash result; investigate failures before moving on.\n\nBash commands run under the \"read-only\" file sandbox.","tools":[{"name":"bash","description":"Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way (a background task reports the same marker via bash_output once it has finished). Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; poll it with `bash_output` and stop it with `bash_kill`. The ONE sanctioned exception to a sandbox denial: retry the exact same command once with `sandbox_permissions` (the wider mode it needs) plus a one-sentence `justification` — the user is asked to approve that single run. Never request escalation before a real denial, and treat a rejected escalation as final: stop and explain instead of working around it.","parameters":{"type":"object","properties":{"command":{"type":"string","description":"The bash command to execute."},"description":{"type":"string","description":"Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"."},"timeoutMs":{"type":"number","description":"Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry."},"workdir":{"type":"string","description":"Working directory for this command. Defaults to the session workspace; a relative path is resolved against it."},"run_in_background":{"type":"boolean","description":"Run in the background and return a task id immediately. No timeout applies."},"sandbox_permissions":{"type":"string","description":"The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.","enum":["workspace-write","danger-full-access"]},"justification":{"type":"string","description":"Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access."}},"required":["command","description"]}},{"name":"bash_output","description":"Read new output from a background bash task started with `bash` + `run_in_background`. Returns only output produced since the previous bash_output call, plus the task status. Tasks keep running while you do other work; poll again later for more output.","parameters":{"type":"object","properties":{"task_id":{"type":"string","description":"Task id returned by the bash tool."}},"required":["task_id"]}},{"name":"bash_kill","description":"Ask the executor to kill a running background bash task by task id.","parameters":{"type":"object","properties":{"task_id":{"type":"string","description":"Task id returned by the bash tool."}},"required":["task_id"]}}]},"reason":"initial"}} -{"type":"assistant/chunk","seq":4,"time":1783421411079,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":5,"time":1783421411079,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":6,"time":1783421411233,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":7,"time":1783421411262,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" is"}}} -{"type":"assistant/chunk","seq":8,"time":1783421411262,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" greeting"}}} -{"type":"assistant/chunk","seq":9,"time":1783421411263,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":10,"time":1783421411263,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" in"}}} -{"type":"assistant/chunk","seq":11,"time":1783421411290,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Chinese"}}} -{"type":"assistant/chunk","seq":12,"time":1783421411290,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":13,"time":1783421411290,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} -{"type":"assistant/chunk","seq":14,"time":1783421411290,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":15,"time":1783421411290,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" respond"}}} -{"type":"assistant/chunk","seq":16,"time":1783421411291,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" in"}}} -{"type":"assistant/chunk","seq":17,"time":1783421411318,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Chinese"}}} -{"type":"assistant/chunk","seq":18,"time":1783421411318,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" as"}}} -{"type":"assistant/chunk","seq":19,"time":1783421411347,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" well"}}} -{"type":"assistant/chunk","seq":20,"time":1783421411347,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":21,"time":1783421411347,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":22,"time":1783421411347,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"你好"}}} -{"type":"assistant/chunk","seq":23,"time":1783421411347,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"!"}}} -{"type":"assistant/chunk","seq":24,"time":1783421411347,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"我是"}}} -{"type":"assistant/chunk","seq":25,"time":1783421411405,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"基于"}}} -{"type":"assistant/chunk","seq":26,"time":1783421411405,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":" Deep"}}} -{"type":"assistant/chunk","seq":27,"time":1783421411405,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"Se"}}} -{"type":"assistant/chunk","seq":28,"time":1783421411405,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"ek"}}} -{"type":"assistant/chunk","seq":29,"time":1783421411405,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":" Har"}}} -{"type":"assistant/chunk","seq":30,"time":1783421411429,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"ness"}}} -{"type":"assistant/chunk","seq":31,"time":1783421411429,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":" SDK"}}} -{"type":"assistant/chunk","seq":32,"time":1783421411429,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":33,"time":1783421411429,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"的"}}} -{"type":"assistant/chunk","seq":34,"time":1783421411429,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":" AI"}}} -{"type":"assistant/chunk","seq":35,"time":1783421411430,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":36,"time":1783421411456,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"助手"}}} -{"type":"assistant/chunk","seq":37,"time":1783421411457,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":38,"time":1783421411457,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"由"}}} -{"type":"assistant/chunk","seq":39,"time":1783421411485,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":" deep"}}} -{"type":"assistant/chunk","seq":40,"time":1783421411485,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"seek"}}} -{"type":"assistant/chunk","seq":41,"time":1783421411486,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"-v"}}} -{"type":"assistant/chunk","seq":42,"time":1783421411486,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"4"}}} -{"type":"assistant/chunk","seq":43,"time":1783421411486,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"-fl"}}} -{"type":"assistant/chunk","seq":44,"time":1783421411486,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"ash"}}} -{"type":"assistant/chunk","seq":45,"time":1783421411513,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":46,"time":1783421411513,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"模型"}}} -{"type":"assistant/chunk","seq":47,"time":1783421411513,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"驱动"}}} -{"type":"assistant/chunk","seq":48,"time":1783421411513,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"。"}}} -{"type":"assistant/chunk","seq":49,"time":1783421411513,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"有什么"}}} -{"type":"assistant/chunk","seq":50,"time":1783421411513,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"可以"}}} -{"type":"assistant/chunk","seq":51,"time":1783421411540,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"帮"}}} -{"type":"assistant/chunk","seq":52,"time":1783421411541,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"你的"}}} -{"type":"assistant/chunk","seq":53,"time":1783421411541,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"吗"}}} -{"type":"assistant/chunk","seq":54,"time":1783421411569,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"?"}}} -{"type":"assistant/chunk","seq":55,"time":1783421411570,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user is greeting me in Chinese. Let me respond in Chinese as well."}}}} -{"type":"assistant/chunk","seq":56,"time":1783421411570,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"你好!我是基于 DeepSeek Harness SDK 的 AI 助手,由 deepseek-v4-flash 模型驱动。有什么可以帮你的吗?"}}}} -{"type":"assistant/chunk","seq":57,"time":1783421411570,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1133,"outputTokens":50,"cacheReadTokens":0,"reasoningTokens":16}}}} -{"type":"assistant/chunk","seq":58,"time":1783421411570,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":59,"time":1783421411572,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user is greeting me in Chinese. Let me respond in Chinese as well."},{"type":"text","text":"你好!我是基于 DeepSeek Harness SDK 的 AI 助手,由 deepseek-v4-flash 模型驱动。有什么可以帮你的吗?"}],"usage":{"inputTokens":1133,"outputTokens":50,"cacheReadTokens":0,"reasoningTokens":16}},"sourceEventSeqs":[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58],"surfaceOp":"append"} -{"type":"step/end","seq":60,"time":1783421411572,"data":{"turn":1,"step":1}} -{"type":"turn/end","seq":61,"time":1783421411573,"data":{"turn":1,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":62,"time":1783421423227,"data":{"turn":2,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":63,"time":1783421423227,"data":{"content":[{"type":"text","text":"帮我创建一个 a.md"}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"step/start","seq":64,"time":1783421423228,"data":{"turn":2,"step":1}} -{"type":"assistant/chunk","seq":65,"time":1783421423837,"data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":66,"time":1783421423837,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":67,"time":1783421423966,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"想"}}} -{"type":"assistant/chunk","seq":68,"time":1783421423990,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"创建一个"}}} -{"type":"assistant/chunk","seq":69,"time":1783421423990,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":70,"time":1783421424016,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":71,"time":1783421424017,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":72,"time":1783421424017,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":73,"time":1783421424017,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"我的"}}} -{"type":"assistant/chunk","seq":74,"time":1783421424044,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"工作"}}} -{"type":"assistant/chunk","seq":75,"time":1783421424045,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":76,"time":1783421424045,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"是"}}} -{"type":"assistant/chunk","seq":77,"time":1783421424045,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" /"}}} -{"type":"assistant/chunk","seq":78,"time":1783421424073,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"Users"}}} -{"type":"assistant/chunk","seq":79,"time":1783421424074,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"/"}}} -{"type":"assistant/chunk","seq":80,"time":1783421424074,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ww"}}} -{"type":"assistant/chunk","seq":81,"time":1783421424074,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"l"}}} -{"type":"assistant/chunk","seq":82,"time":1783421424101,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"/"}}} -{"type":"assistant/chunk","seq":83,"time":1783421424102,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"works"}}} -{"type":"assistant/chunk","seq":84,"time":1783421424102,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"pace"}}} -{"type":"assistant/chunk","seq":85,"time":1783421424102,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"/de"}}} -{"type":"assistant/chunk","seq":86,"time":1783421424102,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ep"}}} -{"type":"assistant/chunk","seq":87,"time":1783421424102,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"seek"}}} -{"type":"assistant/chunk","seq":88,"time":1783421424129,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-h"}}} -{"type":"assistant/chunk","seq":89,"time":1783421424129,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ar"}}} -{"type":"assistant/chunk","seq":90,"time":1783421424129,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ness"}}} -{"type":"assistant/chunk","seq":91,"time":1783421424130,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":92,"time":1783421424130,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"我需要"}}} -{"type":"assistant/chunk","seq":93,"time":1783421424130,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"使用"}}} -{"type":"assistant/chunk","seq":94,"time":1783421424157,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" bash"}}} -{"type":"assistant/chunk","seq":95,"time":1783421424158,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":96,"time":1783421424158,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"工具"}}} -{"type":"assistant/chunk","seq":97,"time":1783421424186,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"来"}}} -{"type":"assistant/chunk","seq":98,"time":1783421424186,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":99,"time":1783421424186,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"这个"}}} -{"type":"assistant/chunk","seq":100,"time":1783421424186,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":101,"time":1783421424186,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":102,"time":1783421424187,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"不过"}}} -{"type":"assistant/chunk","seq":103,"time":1783421424214,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"我需要"}}} -{"type":"assistant/chunk","seq":104,"time":1783421424248,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"确认"}}} -{"type":"assistant/chunk","seq":105,"time":1783421424271,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"一下"}}} -{"type":"assistant/chunk","seq":106,"time":1783421424271,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" sand"}}} -{"type":"assistant/chunk","seq":107,"time":1783421424300,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} -{"type":"assistant/chunk","seq":108,"time":1783421424300,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":109,"time":1783421424300,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"权限"}}} -{"type":"assistant/chunk","seq":110,"time":1783421424300,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"的情况"}}} -{"type":"assistant/chunk","seq":111,"time":1783421424327,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":112,"time":1783421424355,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"先"}}} -{"type":"assistant/chunk","seq":113,"time":1783421424355,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"试试"}}} -{"type":"assistant/chunk","seq":114,"time":1783421424383,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"看"}}} -{"type":"assistant/chunk","seq":115,"time":1783421424383,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":116,"time":1783421424467,"data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":117,"time":1783421424468,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":118,"time":1783421424496,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":119,"time":1783421424496,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":120,"time":1783421424496,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":121,"time":1783421424496,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":122,"time":1783421424496,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":123,"time":1783421424526,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":124,"time":1783421424527,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"touch"}}} -{"type":"assistant/chunk","seq":125,"time":1783421424527,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":126,"time":1783421424527,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"Users"}}} -{"type":"assistant/chunk","seq":127,"time":1783421424555,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":128,"time":1783421424555,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"ww"}}} -{"type":"assistant/chunk","seq":129,"time":1783421424555,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"l"}}} -{"type":"assistant/chunk","seq":130,"time":1783421424555,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":131,"time":1783421424555,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":132,"time":1783421424555,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":133,"time":1783421424582,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"/de"}}} -{"type":"assistant/chunk","seq":134,"time":1783421424582,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"ep"}}} -{"type":"assistant/chunk","seq":135,"time":1783421424582,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"seek"}}} -{"type":"assistant/chunk","seq":136,"time":1783421424582,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"-h"}}} -{"type":"assistant/chunk","seq":137,"time":1783421424582,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"ar"}}} -{"type":"assistant/chunk","seq":138,"time":1783421424582,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"ness"}}} -{"type":"assistant/chunk","seq":139,"time":1783421424610,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"/a"}}} -{"type":"assistant/chunk","seq":140,"time":1783421424610,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":141,"time":1783421424610,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":142,"time":1783421424637,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":143,"time":1783421424638,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":144,"time":1783421424638,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":145,"time":1783421424669,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":146,"time":1783421424669,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":147,"time":1783421424669,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":148,"time":1783421424669,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":149,"time":1783421424694,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":" a"}}} -{"type":"assistant/chunk","seq":150,"time":1783421424694,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":151,"time":1783421424694,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":152,"time":1783421424694,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":153,"time":1783421424694,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":154,"time":1783421424721,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":155,"time":1783421424780,"data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"用户想创建一个文件 a.md。我的工作目录是 /Users/wwl/workspace/deepseek-harness。我需要使用 bash 工具来创建这个文件。不过我需要确认一下 sandbox 权限的情况。先试试看。"}}}} -{"type":"assistant/chunk","seq":156,"time":1783421424780,"data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/a.md\", \"description\": \"创建 a.md 文件\"}"}}}} -{"type":"assistant/chunk","seq":157,"time":1783421424780,"data":{"turn":2,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":150,"outputTokens":129,"cacheReadTokens":1024,"reasoningTokens":50}}}} -{"type":"assistant/chunk","seq":158,"time":1783421424780,"data":{"turn":2,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":159,"time":1783421424780,"data":{"turn":2,"step":1,"content":[{"type":"reasoning","text":"用户想创建一个文件 a.md。我的工作目录是 /Users/wwl/workspace/deepseek-harness。我需要使用 bash 工具来创建这个文件。不过我需要确认一下 sandbox 权限的情况。先试试看。"},{"type":"tool-call","id":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/a.md\", \"description\": \"创建 a.md 文件\"}"}],"usage":{"inputTokens":150,"outputTokens":129,"cacheReadTokens":1024,"reasoningTokens":50}},"sourceEventSeqs":[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158],"surfaceOp":"append"} -{"type":"tool/call","seq":160,"time":1783421424780,"data":{"turn":2,"step":1,"callId":"call_00_RcKdFJb419Z4TsbFjsiD5503","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/a.md\", \"description\": \"创建 a.md 文件\"}"}} -{"type":"tool/result","seq":161,"time":1783421424968,"data":{"turn":2,"step":1,"callId":"call_00_RcKdFJb419Z4TsbFjsiD5503","content":[{"type":"text","text":"[stderr]\ntouch: /Users/wwl/workspace/deepseek-harness/a.md: Operation not permitted\n[sandbox: file access denied under read-only mode]\n[exit code: 1]"}],"isError":false},"sourceEventSeqs":[160],"surfaceOp":"append"} -{"type":"step/end","seq":162,"time":1783421424969,"data":{"turn":2,"step":1}} -{"type":"step/start","seq":163,"time":1783421424969,"data":{"turn":2,"step":2}} -{"type":"assistant/chunk","seq":164,"time":1783421425508,"data":{"turn":2,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":165,"time":1783421425508,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":166,"time":1783421425639,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":167,"time":1783421425666,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"被"}}} -{"type":"assistant/chunk","seq":168,"time":1783421425666,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"沙"}}} -{"type":"assistant/chunk","seq":169,"time":1783421425666,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"盒"}}} -{"type":"assistant/chunk","seq":170,"time":1783421425692,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"阻止"}}} -{"type":"assistant/chunk","seq":171,"time":1783421425693,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"了"}}} -{"type":"assistant/chunk","seq":172,"time":1783421425693,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":173,"time":1783421425694,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"因为"}}} -{"type":"assistant/chunk","seq":174,"time":1783421425720,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"当前"}}} -{"type":"assistant/chunk","seq":175,"time":1783421425720,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"是"}}} -{"type":"assistant/chunk","seq":176,"time":1783421425749,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"只"}}} -{"type":"assistant/chunk","seq":177,"time":1783421425749,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"读"}}} -{"type":"assistant/chunk","seq":178,"time":1783421425749,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"模式"}}} -{"type":"assistant/chunk","seq":179,"time":1783421425749,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":180,"time":1783421425749,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"我需要"}}} -{"type":"assistant/chunk","seq":181,"time":1783421425749,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"申请"}}} -{"type":"assistant/chunk","seq":182,"time":1783421425776,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"写"}}} -{"type":"assistant/chunk","seq":183,"time":1783421425804,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"权限"}}} -{"type":"assistant/chunk","seq":184,"time":1783421425804,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":185,"time":1783421425832,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"根据"}}} -{"type":"assistant/chunk","seq":186,"time":1783421425860,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"规则"}}} -{"type":"assistant/chunk","seq":187,"time":1783421425860,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":188,"time":1783421425860,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"我需要"}}} -{"type":"assistant/chunk","seq":189,"time":1783421425860,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"使用"}}} -{"type":"assistant/chunk","seq":190,"time":1783421425887,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" sand"}}} -{"type":"assistant/chunk","seq":191,"time":1783421425915,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} -{"type":"assistant/chunk","seq":192,"time":1783421425916,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"_per"}}} -{"type":"assistant/chunk","seq":193,"time":1783421425916,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"missions"}}} -{"type":"assistant/chunk","seq":194,"time":1783421425916,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":195,"time":1783421425916,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"参数"}}} -{"type":"assistant/chunk","seq":196,"time":1783421425942,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"并"}}} -{"type":"assistant/chunk","seq":197,"time":1783421425942,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"提供一个"}}} -{"type":"assistant/chunk","seq":198,"time":1783421425970,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"理由"}}} -{"type":"assistant/chunk","seq":199,"time":1783421425999,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":200,"time":1783421425999,"data":{"turn":2,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":201,"time":1783421425999,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"当前"}}} -{"type":"assistant/chunk","seq":202,"time":1783421426026,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"环境"}}} -{"type":"assistant/chunk","seq":203,"time":1783421426072,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"为"}}} -{"type":"assistant/chunk","seq":204,"time":1783421426082,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"只"}}} -{"type":"assistant/chunk","seq":205,"time":1783421426082,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"读"}}} -{"type":"assistant/chunk","seq":206,"time":1783421426082,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"模式"}}} -{"type":"assistant/chunk","seq":207,"time":1783421426082,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":208,"time":1783421426082,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"无法"}}} -{"type":"assistant/chunk","seq":209,"time":1783421426082,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"直接"}}} -{"type":"assistant/chunk","seq":210,"time":1783421426109,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"写入"}}} -{"type":"assistant/chunk","seq":211,"time":1783421426140,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":212,"time":1783421426141,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"。"}}} -{"type":"assistant/chunk","seq":213,"time":1783421426141,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"我需要"}}} -{"type":"assistant/chunk","seq":214,"time":1783421426141,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"申请"}}} -{"type":"assistant/chunk","seq":215,"time":1783421426167,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"一次"}}} -{"type":"assistant/chunk","seq":216,"time":1783421426168,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"写"}}} -{"type":"assistant/chunk","seq":217,"time":1783421426195,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"权限"}}} -{"type":"assistant/chunk","seq":218,"time":1783421426195,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"来"}}} -{"type":"assistant/chunk","seq":219,"time":1783421426243,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":220,"time":1783421426244,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"这个"}}} -{"type":"assistant/chunk","seq":221,"time":1783421426244,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":222,"time":1783421426244,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"。"}}} -{"type":"assistant/chunk","seq":223,"time":1783421426280,"data":{"turn":2,"step":2,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":224,"time":1783421426280,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":225,"time":1783421426306,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":226,"time":1783421426307,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":227,"time":1783421426307,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":228,"time":1783421426335,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":229,"time":1783421426335,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":230,"time":1783421426335,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":231,"time":1783421426335,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"touch"}}} -{"type":"assistant/chunk","seq":232,"time":1783421426361,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":233,"time":1783421426362,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"Users"}}} -{"type":"assistant/chunk","seq":234,"time":1783421426362,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":235,"time":1783421426362,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"ww"}}} -{"type":"assistant/chunk","seq":236,"time":1783421426362,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"l"}}} -{"type":"assistant/chunk","seq":237,"time":1783421426362,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":238,"time":1783421426389,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":239,"time":1783421426389,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":240,"time":1783421426389,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"/de"}}} -{"type":"assistant/chunk","seq":241,"time":1783421426389,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"ep"}}} -{"type":"assistant/chunk","seq":242,"time":1783421426389,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"seek"}}} -{"type":"assistant/chunk","seq":243,"time":1783421426390,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"-h"}}} -{"type":"assistant/chunk","seq":244,"time":1783421426417,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"ar"}}} -{"type":"assistant/chunk","seq":245,"time":1783421426418,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"ness"}}} -{"type":"assistant/chunk","seq":246,"time":1783421426418,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"/a"}}} -{"type":"assistant/chunk","seq":247,"time":1783421426418,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":248,"time":1783421426418,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":249,"time":1783421426472,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":250,"time":1783421426473,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":251,"time":1783421426473,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":252,"time":1783421426473,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":253,"time":1783421426473,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":254,"time":1783421426500,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":255,"time":1783421426501,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":256,"time":1783421426501,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":" a"}}} -{"type":"assistant/chunk","seq":257,"time":1783421426501,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":258,"time":1783421426501,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":259,"time":1783421426501,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":260,"time":1783421426528,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":261,"time":1783421426555,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":262,"time":1783421426556,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":263,"time":1783421426556,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"sand"}}} -{"type":"assistant/chunk","seq":264,"time":1783421426556,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"box"}}} -{"type":"assistant/chunk","seq":265,"time":1783421426556,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"_per"}}} -{"type":"assistant/chunk","seq":266,"time":1783421426584,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"missions"}}} -{"type":"assistant/chunk","seq":267,"time":1783421426584,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":268,"time":1783421426584,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":269,"time":1783421426584,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":270,"time":1783421426612,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":271,"time":1783421426612,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":272,"time":1783421426612,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"-w"}}} -{"type":"assistant/chunk","seq":273,"time":1783421426612,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"rite"}}} -{"type":"assistant/chunk","seq":274,"time":1783421426612,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":275,"time":1783421426667,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":276,"time":1783421426668,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":277,"time":1783421426668,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"just"}}} -{"type":"assistant/chunk","seq":278,"time":1783421426668,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"ification"}}} -{"type":"assistant/chunk","seq":279,"time":1783421426668,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":280,"time":1783421426668,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":281,"time":1783421426697,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":282,"time":1783421426698,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"用户"}}} -{"type":"assistant/chunk","seq":283,"time":1783421426698,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"要求"}}} -{"type":"assistant/chunk","seq":284,"time":1783421426698,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":285,"time":1783421426734,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":" a"}}} -{"type":"assistant/chunk","seq":286,"time":1783421426735,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":287,"time":1783421426735,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":288,"time":1783421426735,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":289,"time":1783421426735,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":","}}} -{"type":"assistant/chunk","seq":290,"time":1783421426735,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"需要"}}} -{"type":"assistant/chunk","seq":291,"time":1783421426753,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"写"}}} -{"type":"assistant/chunk","seq":292,"time":1783421426782,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"权限"}}} -{"type":"assistant/chunk","seq":293,"time":1783421426782,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"来"}}} -{"type":"assistant/chunk","seq":294,"time":1783421426782,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"在工作"}}} -{"type":"assistant/chunk","seq":295,"time":1783421426808,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":296,"time":1783421426809,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"中"}}} -{"type":"assistant/chunk","seq":297,"time":1783421426809,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":298,"time":1783421426836,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"该"}}} -{"type":"assistant/chunk","seq":299,"time":1783421426836,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":300,"time":1783421426836,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"。"}}} -{"type":"assistant/chunk","seq":301,"time":1783421426836,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":302,"time":1783421426867,"data":{"turn":2,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":303,"time":1783421426894,"data":{"turn":2,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"文件创建被沙盒阻止了,因为当前是只读模式。我需要申请写权限。根据规则,我需要使用 sandbox_permissions 参数并提供一个理由。"}}}} -{"type":"assistant/chunk","seq":304,"time":1783421426894,"data":{"turn":2,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"当前环境为只读模式,无法直接写入文件。我需要申请一次写权限来创建这个文件。"}}}} -{"type":"assistant/chunk","seq":305,"time":1783421426894,"data":{"turn":2,"step":2,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/a.md\", \"description\": \"创建 a.md 文件\", \"sandbox_permissions\": \"workspace-write\", \"justification\": \"用户要求创建 a.md 文件,需要写权限来在工作目录中创建该文件。\"}"}}}} -{"type":"assistant/chunk","seq":306,"time":1783421426894,"data":{"turn":2,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":80,"outputTokens":191,"cacheReadTokens":1280,"reasoningTokens":35}}}} -{"type":"assistant/chunk","seq":307,"time":1783421426894,"data":{"turn":2,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":308,"time":1783421426895,"data":{"turn":2,"step":2,"content":[{"type":"reasoning","text":"文件创建被沙盒阻止了,因为当前是只读模式。我需要申请写权限。根据规则,我需要使用 sandbox_permissions 参数并提供一个理由。"},{"type":"text","text":"当前环境为只读模式,无法直接写入文件。我需要申请一次写权限来创建这个文件。"},{"type":"tool-call","id":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/a.md\", \"description\": \"创建 a.md 文件\", \"sandbox_permissions\": \"workspace-write\", \"justification\": \"用户要求创建 a.md 文件,需要写权限来在工作目录中创建该文件。\"}"}],"usage":{"inputTokens":80,"outputTokens":191,"cacheReadTokens":1280,"reasoningTokens":35}},"sourceEventSeqs":[164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307],"surfaceOp":"append"} -{"type":"tool/call","seq":309,"time":1783421426895,"data":{"turn":2,"step":2,"callId":"call_00_Bm860a1oOrGFTnCY3xlU4459","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/a.md\", \"description\": \"创建 a.md 文件\", \"sandbox_permissions\": \"workspace-write\", \"justification\": \"用户要求创建 a.md 文件,需要写权限来在工作目录中创建该文件。\"}"}} -{"type":"approval/asked","seq":310,"time":1783421426895,"data":{"id":"fcb14c8f-9080-4260-b870-852432d8a46c","toolName":"bash","callId":"call_00_Bm860a1oOrGFTnCY3xlU4459","reason":"escalate sandbox to workspace-write: 用户要求创建 a.md 文件,需要写权限来在工作目录中创建该文件。"}} -{"type":"approval/decided","seq":311,"time":1783421428529,"data":{"id":"fcb14c8f-9080-4260-b870-852432d8a46c","outcome":"allowed-once"}} -{"type":"tool/result","seq":312,"time":1783421428617,"data":{"turn":2,"step":2,"callId":"call_00_Bm860a1oOrGFTnCY3xlU4459","content":[{"type":"text","text":"(no output)"}],"isError":false},"sourceEventSeqs":[309],"surfaceOp":"append"} -{"type":"step/end","seq":313,"time":1783421428617,"data":{"turn":2,"step":2}} -{"type":"step/start","seq":314,"time":1783421428617,"data":{"turn":2,"step":3}} -{"type":"assistant/chunk","seq":315,"time":1783421429001,"data":{"turn":2,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":316,"time":1783421429001,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":317,"time":1783421429121,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":318,"time":1783421429149,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"成功了"}}} -{"type":"assistant/chunk","seq":319,"time":1783421429149,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":320,"time":1783421429149,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"没有"}}} -{"type":"assistant/chunk","seq":321,"time":1783421429149,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"报"}}} -{"type":"assistant/chunk","seq":322,"time":1783421429178,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"错"}}} -{"type":"assistant/chunk","seq":323,"time":1783421429178,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":324,"time":1783421429178,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"让我"}}} -{"type":"assistant/chunk","seq":325,"time":1783421429178,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"验证"}}} -{"type":"assistant/chunk","seq":326,"time":1783421429178,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"一下"}}} -{"type":"assistant/chunk","seq":327,"time":1783421429205,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":328,"time":1783421429205,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"是否存在"}}} -{"type":"assistant/chunk","seq":329,"time":1783421429205,"data":{"turn":2,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":330,"time":1783421429205,"data":{"turn":2,"step":3,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":331,"time":1783421429205,"data":{"turn":2,"step":3,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":332,"time":1783421429205,"data":{"turn":2,"step":3,"chunk":{"type":"text-delta","index":1,"text":"已"}}} -{"type":"assistant/chunk","seq":333,"time":1783421429233,"data":{"turn":2,"step":3,"chunk":{"type":"text-delta","index":1,"text":"成功"}}} -{"type":"assistant/chunk","seq":334,"time":1783421429233,"data":{"turn":2,"step":3,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":335,"time":1783421429233,"data":{"turn":2,"step":3,"chunk":{"type":"text-delta","index":1,"text":"!"}}} -{"type":"assistant/chunk","seq":336,"time":1783421429233,"data":{"turn":2,"step":3,"chunk":{"type":"text-delta","index":1,"text":"验证"}}} -{"type":"assistant/chunk","seq":337,"time":1783421429261,"data":{"turn":2,"step":3,"chunk":{"type":"text-delta","index":1,"text":"一下"}}} -{"type":"assistant/chunk","seq":338,"time":1783421429261,"data":{"turn":2,"step":3,"chunk":{"type":"text-delta","index":1,"text":":"}}} -{"type":"assistant/chunk","seq":339,"time":1783421429317,"data":{"turn":2,"step":3,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":340,"time":1783421429317,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":341,"time":1783421429345,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":342,"time":1783421429345,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":343,"time":1783421429345,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":344,"time":1783421429345,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":345,"time":1783421429345,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":346,"time":1783421429373,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":347,"time":1783421429373,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"验证"}}} -{"type":"assistant/chunk","seq":348,"time":1783421429373,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":" a"}}} -{"type":"assistant/chunk","seq":349,"time":1783421429373,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":350,"time":1783421429400,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":351,"time":1783421429401,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":352,"time":1783421429401,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"已"}}} -{"type":"assistant/chunk","seq":353,"time":1783421429429,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":354,"time":1783421429429,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":355,"time":1783421429457,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":356,"time":1783421429457,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":357,"time":1783421429457,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":358,"time":1783421429457,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":359,"time":1783421429488,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":360,"time":1783421429488,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":361,"time":1783421429488,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"ls"}}} -{"type":"assistant/chunk","seq":362,"time":1783421429488,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":" -"}}} -{"type":"assistant/chunk","seq":363,"time":1783421429512,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"la"}}} -{"type":"assistant/chunk","seq":364,"time":1783421429512,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":365,"time":1783421429512,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"Users"}}} -{"type":"assistant/chunk","seq":366,"time":1783421429512,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":367,"time":1783421429512,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"ww"}}} -{"type":"assistant/chunk","seq":368,"time":1783421429540,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"l"}}} -{"type":"assistant/chunk","seq":369,"time":1783421429541,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":370,"time":1783421429541,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":371,"time":1783421429541,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":372,"time":1783421429541,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"/de"}}} -{"type":"assistant/chunk","seq":373,"time":1783421429568,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"ep"}}} -{"type":"assistant/chunk","seq":374,"time":1783421429569,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"seek"}}} -{"type":"assistant/chunk","seq":375,"time":1783421429569,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"-h"}}} -{"type":"assistant/chunk","seq":376,"time":1783421429569,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"ar"}}} -{"type":"assistant/chunk","seq":377,"time":1783421429569,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"ness"}}} -{"type":"assistant/chunk","seq":378,"time":1783421429569,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"/a"}}} -{"type":"assistant/chunk","seq":379,"time":1783421429596,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":380,"time":1783421429596,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":381,"time":1783421429624,"data":{"turn":2,"step":3,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":382,"time":1783421429654,"data":{"turn":2,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"文件创建成功了,没有报错。让我验证一下文件是否存在。"}}}} -{"type":"assistant/chunk","seq":383,"time":1783421429654,"data":{"turn":2,"step":3,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"文件已成功创建!验证一下:"}}}} -{"type":"assistant/chunk","seq":384,"time":1783421429654,"data":{"turn":2,"step":3,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","arguments":"{\"description\": \"验证 a.md 文件已创建\", \"command\": \"ls -la /Users/wwl/workspace/deepseek-harness/a.md\"}"}}}} -{"type":"assistant/chunk","seq":385,"time":1783421429654,"data":{"turn":2,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":29,"outputTokens":104,"cacheReadTokens":1536,"reasoningTokens":14}}}} -{"type":"assistant/chunk","seq":386,"time":1783421429654,"data":{"turn":2,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":387,"time":1783421429655,"data":{"turn":2,"step":3,"content":[{"type":"reasoning","text":"文件创建成功了,没有报错。让我验证一下文件是否存在。"},{"type":"text","text":"文件已成功创建!验证一下:"},{"type":"tool-call","id":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","arguments":"{\"description\": \"验证 a.md 文件已创建\", \"command\": \"ls -la /Users/wwl/workspace/deepseek-harness/a.md\"}"}],"usage":{"inputTokens":29,"outputTokens":104,"cacheReadTokens":1536,"reasoningTokens":14}},"sourceEventSeqs":[315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386],"surfaceOp":"append"} -{"type":"tool/call","seq":388,"time":1783421429655,"data":{"turn":2,"step":3,"callId":"call_00_ufORNimSmbklA2zLkAEA3773","name":"bash","arguments":"{\"description\": \"验证 a.md 文件已创建\", \"command\": \"ls -la /Users/wwl/workspace/deepseek-harness/a.md\"}"}} -{"type":"tool/result","seq":389,"time":1783421429745,"data":{"turn":2,"step":3,"callId":"call_00_ufORNimSmbklA2zLkAEA3773","content":[{"type":"text","text":"-rw-r--r--@ 1 wwl staff 0 Jul 7 18:50 /Users/wwl/workspace/deepseek-harness/a.md\n"}],"isError":false},"sourceEventSeqs":[388],"surfaceOp":"append"} -{"type":"step/end","seq":390,"time":1783421429745,"data":{"turn":2,"step":3}} -{"type":"step/start","seq":391,"time":1783421429746,"data":{"turn":2,"step":4}} -{"type":"assistant/chunk","seq":392,"time":1783421430100,"data":{"turn":2,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":393,"time":1783421430100,"data":{"turn":2,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":394,"time":1783421430202,"data":{"turn":2,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"已"}}} -{"type":"assistant/chunk","seq":395,"time":1783421430241,"data":{"turn":2,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"成功"}}} -{"type":"assistant/chunk","seq":396,"time":1783421430241,"data":{"turn":2,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":397,"time":1783421430241,"data":{"turn":2,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":398,"time":1783421430241,"data":{"turn":2,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"大小为"}}} -{"type":"assistant/chunk","seq":399,"time":1783421430257,"data":{"turn":2,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"0"}}} -{"type":"assistant/chunk","seq":400,"time":1783421430258,"data":{"turn":2,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"字节"}}} -{"type":"assistant/chunk","seq":401,"time":1783421430286,"data":{"turn":2,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":402,"time":1783421430286,"data":{"turn":2,"step":4,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":403,"time":1783421430286,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":404,"time":1783421430286,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":405,"time":1783421430344,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"a"}}} -{"type":"assistant/chunk","seq":406,"time":1783421430345,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":407,"time":1783421430345,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":408,"time":1783421430345,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":409,"time":1783421430345,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"已"}}} -{"type":"assistant/chunk","seq":410,"time":1783421430345,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"成功"}}} -{"type":"assistant/chunk","seq":411,"time":1783421430345,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":412,"time":1783421430345,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"在"}}} -{"type":"assistant/chunk","seq":413,"time":1783421430374,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":" `/"}}} -{"type":"assistant/chunk","seq":414,"time":1783421430375,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"Users"}}} -{"type":"assistant/chunk","seq":415,"time":1783421430375,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":416,"time":1783421430375,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"ww"}}} -{"type":"assistant/chunk","seq":417,"time":1783421430375,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"l"}}} -{"type":"assistant/chunk","seq":418,"time":1783421430375,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":419,"time":1783421430400,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"works"}}} -{"type":"assistant/chunk","seq":420,"time":1783421430400,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"pace"}}} -{"type":"assistant/chunk","seq":421,"time":1783421430400,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"/de"}}} -{"type":"assistant/chunk","seq":422,"time":1783421430400,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"ep"}}} -{"type":"assistant/chunk","seq":423,"time":1783421430400,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"seek"}}} -{"type":"assistant/chunk","seq":424,"time":1783421430400,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"-h"}}} -{"type":"assistant/chunk","seq":425,"time":1783421430427,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"ar"}}} -{"type":"assistant/chunk","seq":426,"time":1783421430427,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"ness"}}} -{"type":"assistant/chunk","seq":427,"time":1783421430427,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":428,"time":1783421430427,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":429,"time":1783421430427,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":430,"time":1783421430427,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":431,"time":1783421430455,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"下"}}} -{"type":"assistant/chunk","seq":432,"time":1783421430455,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"。"}}} -{"type":"assistant/chunk","seq":433,"time":1783421430494,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"目前"}}} -{"type":"assistant/chunk","seq":434,"time":1783421430494,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"是"}}} -{"type":"assistant/chunk","seq":435,"time":1783421430510,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"空"}}} -{"type":"assistant/chunk","seq":436,"time":1783421430510,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":437,"time":1783421430510,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":438,"time":1783421430510,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"需要"}}} -{"type":"assistant/chunk","seq":439,"time":1783421430538,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"我"}}} -{"type":"assistant/chunk","seq":440,"time":1783421430538,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"往"}}} -{"type":"assistant/chunk","seq":441,"time":1783421430538,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"里面"}}} -{"type":"assistant/chunk","seq":442,"time":1783421430538,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"写"}}} -{"type":"assistant/chunk","seq":443,"time":1783421430567,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"点"}}} -{"type":"assistant/chunk","seq":444,"time":1783421430567,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"内容"}}} -{"type":"assistant/chunk","seq":445,"time":1783421430567,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"吗"}}} -{"type":"assistant/chunk","seq":446,"time":1783421430567,"data":{"turn":2,"step":4,"chunk":{"type":"text-delta","index":1,"text":"?"}}} -{"type":"assistant/chunk","seq":447,"time":1783421430568,"data":{"turn":2,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"文件已成功创建,大小为0字节。"}}}} -{"type":"assistant/chunk","seq":448,"time":1783421430568,"data":{"turn":2,"step":4,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"文件 `a.md` 已成功创建在 `/Users/wwl/workspace/deepseek-harness/` 目录下。目前是空文件,需要我往里面写点内容吗?"}}}} -{"type":"assistant/chunk","seq":449,"time":1783421430568,"data":{"turn":2,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":55,"outputTokens":54,"cacheReadTokens":1664,"reasoningTokens":9}}}} -{"type":"assistant/chunk","seq":450,"time":1783421430568,"data":{"turn":2,"step":4,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":451,"time":1783421430568,"data":{"turn":2,"step":4,"content":[{"type":"reasoning","text":"文件已成功创建,大小为0字节。"},{"type":"text","text":"文件 `a.md` 已成功创建在 `/Users/wwl/workspace/deepseek-harness/` 目录下。目前是空文件,需要我往里面写点内容吗?"}],"usage":{"inputTokens":55,"outputTokens":54,"cacheReadTokens":1664,"reasoningTokens":9}},"sourceEventSeqs":[392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450],"surfaceOp":"append"} -{"type":"step/end","seq":452,"time":1783421430568,"data":{"turn":2,"step":4}} -{"type":"turn/end","seq":453,"time":1783421430568,"data":{"turn":2,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":454,"time":1783421439538,"data":{"turn":3,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":455,"time":1783421439538,"data":{"content":[{"type":"text","text":"帮我创建一个b.md"}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"step/start","seq":456,"time":1783421439538,"data":{"turn":3,"step":1}} -{"type":"assistant/chunk","seq":457,"time":1783421439995,"data":{"turn":3,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":458,"time":1783421439995,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":459,"time":1783421440126,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"想"}}} -{"type":"assistant/chunk","seq":460,"time":1783421440153,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"再"}}} -{"type":"assistant/chunk","seq":461,"time":1783421440154,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"创建一个"}}} -{"type":"assistant/chunk","seq":462,"time":1783421440154,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" b"}}} -{"type":"assistant/chunk","seq":463,"time":1783421440154,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":464,"time":1783421440181,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":465,"time":1783421440182,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":466,"time":1783421440182,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":467,"time":1783421440182,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"同样"}}} -{"type":"assistant/chunk","seq":468,"time":1783421440182,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"需要"}}} -{"type":"assistant/chunk","seq":469,"time":1783421440209,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"写"}}} -{"type":"assistant/chunk","seq":470,"time":1783421440238,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"权限"}}} -{"type":"assistant/chunk","seq":471,"time":1783421440239,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":472,"time":1783421440321,"data":{"turn":3,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":473,"time":1783421440321,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":474,"time":1783421440350,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":475,"time":1783421440351,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":476,"time":1783421440351,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":477,"time":1783421440382,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":478,"time":1783421440382,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":479,"time":1783421440382,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":480,"time":1783421440382,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"touch"}}} -{"type":"assistant/chunk","seq":481,"time":1783421440459,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":482,"time":1783421440459,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"Users"}}} -{"type":"assistant/chunk","seq":483,"time":1783421440459,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":484,"time":1783421440459,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"ww"}}} -{"type":"assistant/chunk","seq":485,"time":1783421440459,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"l"}}} -{"type":"assistant/chunk","seq":486,"time":1783421440459,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":487,"time":1783421440474,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":488,"time":1783421440475,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":489,"time":1783421440475,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"/de"}}} -{"type":"assistant/chunk","seq":490,"time":1783421440475,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"ep"}}} -{"type":"assistant/chunk","seq":491,"time":1783421440475,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"seek"}}} -{"type":"assistant/chunk","seq":492,"time":1783421440475,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"-h"}}} -{"type":"assistant/chunk","seq":493,"time":1783421440505,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"ar"}}} -{"type":"assistant/chunk","seq":494,"time":1783421440506,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"ness"}}} -{"type":"assistant/chunk","seq":495,"time":1783421440506,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"/b"}}} -{"type":"assistant/chunk","seq":496,"time":1783421440506,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":497,"time":1783421440506,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":498,"time":1783421440560,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":499,"time":1783421440561,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":500,"time":1783421440561,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":501,"time":1783421440561,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":502,"time":1783421440561,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":503,"time":1783421440588,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":504,"time":1783421440589,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":505,"time":1783421440589,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":" b"}}} -{"type":"assistant/chunk","seq":506,"time":1783421440589,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":507,"time":1783421440589,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":508,"time":1783421440589,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":509,"time":1783421440619,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":510,"time":1783421440648,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":511,"time":1783421440649,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":512,"time":1783421440649,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"sand"}}} -{"type":"assistant/chunk","seq":513,"time":1783421440649,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"box"}}} -{"type":"assistant/chunk","seq":514,"time":1783421440649,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"_per"}}} -{"type":"assistant/chunk","seq":515,"time":1783421440677,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"missions"}}} -{"type":"assistant/chunk","seq":516,"time":1783421440677,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":517,"time":1783421440678,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":518,"time":1783421440678,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":519,"time":1783421440704,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":520,"time":1783421440704,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":521,"time":1783421440704,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"-w"}}} -{"type":"assistant/chunk","seq":522,"time":1783421440704,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"rite"}}} -{"type":"assistant/chunk","seq":523,"time":1783421440704,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":524,"time":1783421440761,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":525,"time":1783421440761,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":526,"time":1783421440761,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"just"}}} -{"type":"assistant/chunk","seq":527,"time":1783421440761,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"ification"}}} -{"type":"assistant/chunk","seq":528,"time":1783421440761,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":529,"time":1783421440761,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":530,"time":1783421440790,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":531,"time":1783421440790,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"用户"}}} -{"type":"assistant/chunk","seq":532,"time":1783421440790,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"要求"}}} -{"type":"assistant/chunk","seq":533,"time":1783421440790,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":534,"time":1783421440790,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":" b"}}} -{"type":"assistant/chunk","seq":535,"time":1783421440818,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":536,"time":1783421440818,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":537,"time":1783421440818,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":538,"time":1783421440818,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":","}}} -{"type":"assistant/chunk","seq":539,"time":1783421440818,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"需要"}}} -{"type":"assistant/chunk","seq":540,"time":1783421440818,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"写"}}} -{"type":"assistant/chunk","seq":541,"time":1783421440846,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"权限"}}} -{"type":"assistant/chunk","seq":542,"time":1783421440846,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"来完成"}}} -{"type":"assistant/chunk","seq":543,"time":1783421440875,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"。"}}} -{"type":"assistant/chunk","seq":544,"time":1783421440875,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":545,"time":1783421440875,"data":{"turn":3,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":546,"time":1783421440938,"data":{"turn":3,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"用户想再创建一个 b.md 文件。同样需要写权限。"}}}} -{"type":"assistant/chunk","seq":547,"time":1783421440938,"data":{"turn":3,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/b.md\", \"description\": \"创建 b.md 文件\", \"sandbox_permissions\": \"workspace-write\", \"justification\": \"用户要求创建 b.md 文件,需要写权限来完成。\"}"}}}} -{"type":"assistant/chunk","seq":548,"time":1783421440938,"data":{"turn":3,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":108,"outputTokens":143,"cacheReadTokens":1664,"reasoningTokens":14}}}} -{"type":"assistant/chunk","seq":549,"time":1783421440939,"data":{"turn":3,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":550,"time":1783421440939,"data":{"turn":3,"step":1,"content":[{"type":"reasoning","text":"用户想再创建一个 b.md 文件。同样需要写权限。"},{"type":"tool-call","id":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/b.md\", \"description\": \"创建 b.md 文件\", \"sandbox_permissions\": \"workspace-write\", \"justification\": \"用户要求创建 b.md 文件,需要写权限来完成。\"}"}],"usage":{"inputTokens":108,"outputTokens":143,"cacheReadTokens":1664,"reasoningTokens":14}},"sourceEventSeqs":[457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549],"surfaceOp":"append"} -{"type":"tool/call","seq":551,"time":1783421440939,"data":{"turn":3,"step":1,"callId":"call_00_xYndEeP8bz9o7WtBSExK3908","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/b.md\", \"description\": \"创建 b.md 文件\", \"sandbox_permissions\": \"workspace-write\", \"justification\": \"用户要求创建 b.md 文件,需要写权限来完成。\"}"}} -{"type":"approval/asked","seq":552,"time":1783421440939,"data":{"id":"c69fb956-43c4-4f62-8585-7758accd2116","toolName":"bash","callId":"call_00_xYndEeP8bz9o7WtBSExK3908","reason":"escalate sandbox to workspace-write: 用户要求创建 b.md 文件,需要写权限来完成。"}} -{"type":"approval/decided","seq":553,"time":1783421443589,"data":{"id":"c69fb956-43c4-4f62-8585-7758accd2116","outcome":"rejected"}} -{"type":"tool/result","seq":554,"time":1783421443589,"data":{"turn":3,"step":1,"callId":"call_00_xYndEeP8bz9o7WtBSExK3908","content":[{"type":"text","text":"Error: the user rejected escalating this command to \"workspace-write\""}],"isError":true},"sourceEventSeqs":[551],"surfaceOp":"append"} -{"type":"step/end","seq":555,"time":1783421443589,"data":{"turn":3,"step":1}} -{"type":"step/start","seq":556,"time":1783421443590,"data":{"turn":3,"step":2}} -{"type":"assistant/chunk","seq":557,"time":1783421444172,"data":{"turn":3,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":558,"time":1783421444172,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":559,"time":1783421444351,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"拒绝了"}}} -{"type":"assistant/chunk","seq":560,"time":1783421444380,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"写入"}}} -{"type":"assistant/chunk","seq":561,"time":1783421444380,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"权限"}}} -{"type":"assistant/chunk","seq":562,"time":1783421444407,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"的"}}} -{"type":"assistant/chunk","seq":563,"time":1783421444408,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"申请"}}} -{"type":"assistant/chunk","seq":564,"time":1783421444445,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":565,"time":1783421444445,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"这意味着"}}} -{"type":"assistant/chunk","seq":566,"time":1783421444445,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"我"}}} -{"type":"assistant/chunk","seq":567,"time":1783421444464,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"无法"}}} -{"type":"assistant/chunk","seq":568,"time":1783421444464,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"在当前"}}} -{"type":"assistant/chunk","seq":569,"time":1783421444464,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"沙"}}} -{"type":"assistant/chunk","seq":570,"time":1783421444496,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"盒"}}} -{"type":"assistant/chunk","seq":571,"time":1783421444496,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"模式下"}}} -{"type":"assistant/chunk","seq":572,"time":1783421444496,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":573,"time":1783421444496,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" b"}}} -{"type":"assistant/chunk","seq":574,"time":1783421444496,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":575,"time":1783421444496,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":576,"time":1783421444522,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":577,"time":1783421444522,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":578,"time":1783421444522,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"我需要"}}} -{"type":"assistant/chunk","seq":579,"time":1783421444522,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"如实"}}} -{"type":"assistant/chunk","seq":580,"time":1783421444549,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"告知"}}} -{"type":"assistant/chunk","seq":581,"time":1783421444549,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":582,"time":1783421444549,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"这个"}}} -{"type":"assistant/chunk","seq":583,"time":1783421444549,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"情况"}}} -{"type":"assistant/chunk","seq":584,"time":1783421444579,"data":{"turn":3,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":585,"time":1783421444580,"data":{"turn":3,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":586,"time":1783421444580,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"抱歉"}}} -{"type":"assistant/chunk","seq":587,"time":1783421444606,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":588,"time":1783421444606,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"写入"}}} -{"type":"assistant/chunk","seq":589,"time":1783421444634,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"权限"}}} -{"type":"assistant/chunk","seq":590,"time":1783421444634,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"的"}}} -{"type":"assistant/chunk","seq":591,"time":1783421444662,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"申请"}}} -{"type":"assistant/chunk","seq":592,"time":1783421444662,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"被"}}} -{"type":"assistant/chunk","seq":593,"time":1783421444662,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"拒绝了"}}} -{"type":"assistant/chunk","seq":594,"time":1783421444662,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":595,"time":1783421444663,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"我"}}} -{"type":"assistant/chunk","seq":596,"time":1783421444692,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"目前"}}} -{"type":"assistant/chunk","seq":597,"time":1783421444693,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"无法"}}} -{"type":"assistant/chunk","seq":598,"time":1783421444693,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"在"}}} -{"type":"assistant/chunk","seq":599,"time":1783421444719,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"只"}}} -{"type":"assistant/chunk","seq":600,"time":1783421444719,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"读"}}} -{"type":"assistant/chunk","seq":601,"time":1783421444719,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"沙"}}} -{"type":"assistant/chunk","seq":602,"time":1783421444747,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"盒"}}} -{"type":"assistant/chunk","seq":603,"time":1783421444747,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"环境下"}}} -{"type":"assistant/chunk","seq":604,"time":1783421444748,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":605,"time":1783421444776,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":606,"time":1783421444776,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"b"}}} -{"type":"assistant/chunk","seq":607,"time":1783421444776,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":608,"time":1783421444776,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":609,"time":1783421444776,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":610,"time":1783421444776,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":611,"time":1783421444804,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"。\n\n"}}} -{"type":"assistant/chunk","seq":612,"time":1783421444805,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"你可以"}}} -{"type":"assistant/chunk","seq":613,"time":1783421444805,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"考虑"}}} -{"type":"assistant/chunk","seq":614,"time":1783421444832,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"以下"}}} -{"type":"assistant/chunk","seq":615,"time":1783421444832,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"替代"}}} -{"type":"assistant/chunk","seq":616,"time":1783421444860,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"方案"}}} -{"type":"assistant/chunk","seq":617,"time":1783421444888,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":":\n"}}} -{"type":"assistant/chunk","seq":618,"time":1783421444889,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"1"}}} -{"type":"assistant/chunk","seq":619,"time":1783421444889,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"."}}} -{"type":"assistant/chunk","seq":620,"time":1783421444889,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":" **"}}} -{"type":"assistant/chunk","seq":621,"time":1783421444889,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"自己在"}}} -{"type":"assistant/chunk","seq":622,"time":1783421444919,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"本地"}}} -{"type":"assistant/chunk","seq":623,"time":1783421444949,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":624,"time":1783421444949,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":625,"time":1783421444978,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":":"}}} -{"type":"assistant/chunk","seq":626,"time":1783421444979,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"在"}}} -{"type":"assistant/chunk","seq":627,"time":1783421445006,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"终端"}}} -{"type":"assistant/chunk","seq":628,"time":1783421445006,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"执行"}}} -{"type":"assistant/chunk","seq":629,"time":1783421445006,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":630,"time":1783421445034,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"touch"}}} -{"type":"assistant/chunk","seq":631,"time":1783421445034,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":" /"}}} -{"type":"assistant/chunk","seq":632,"time":1783421445061,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"Users"}}} -{"type":"assistant/chunk","seq":633,"time":1783421445061,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":634,"time":1783421445061,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ww"}}} -{"type":"assistant/chunk","seq":635,"time":1783421445089,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"l"}}} -{"type":"assistant/chunk","seq":636,"time":1783421445089,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":637,"time":1783421445089,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"works"}}} -{"type":"assistant/chunk","seq":638,"time":1783421445089,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"pace"}}} -{"type":"assistant/chunk","seq":639,"time":1783421445089,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"/de"}}} -{"type":"assistant/chunk","seq":640,"time":1783421445089,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ep"}}} -{"type":"assistant/chunk","seq":641,"time":1783421445117,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"seek"}}} -{"type":"assistant/chunk","seq":642,"time":1783421445117,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"-h"}}} -{"type":"assistant/chunk","seq":643,"time":1783421445117,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ar"}}} -{"type":"assistant/chunk","seq":644,"time":1783421445117,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ness"}}} -{"type":"assistant/chunk","seq":645,"time":1783421445117,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"/b"}}} -{"type":"assistant/chunk","seq":646,"time":1783421445118,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":647,"time":1783421445146,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`\n"}}} -{"type":"assistant/chunk","seq":648,"time":1783421445146,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"2"}}} -{"type":"assistant/chunk","seq":649,"time":1783421445146,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"."}}} -{"type":"assistant/chunk","seq":650,"time":1783421445146,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":" **"}}} -{"type":"assistant/chunk","seq":651,"time":1783421445146,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"通过"}}} -{"type":"assistant/chunk","seq":652,"time":1783421445173,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"其他"}}} -{"type":"assistant/chunk","seq":653,"time":1783421445173,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"有"}}} -{"type":"assistant/chunk","seq":654,"time":1783421445201,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"写"}}} -{"type":"assistant/chunk","seq":655,"time":1783421445229,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"权限"}}} -{"type":"assistant/chunk","seq":656,"time":1783421445229,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"的工具"}}} -{"type":"assistant/chunk","seq":657,"time":1783421445258,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"或"}}} -{"type":"assistant/chunk","seq":658,"time":1783421445286,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"方式"}}} -{"type":"assistant/chunk","seq":659,"time":1783421445286,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":660,"time":1783421445286,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"来完成"}}} -{"type":"assistant/chunk","seq":661,"time":1783421445319,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":662,"time":1783421445341,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"\n\n"}}} -{"type":"assistant/chunk","seq":663,"time":1783421445341,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"如果"}}} -{"type":"assistant/chunk","seq":664,"time":1783421445341,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"后续"}}} -{"type":"assistant/chunk","seq":665,"time":1783421445370,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"需要"}}} -{"type":"assistant/chunk","seq":666,"time":1783421445370,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"我"}}} -{"type":"assistant/chunk","seq":667,"time":1783421445398,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"处理"}}} -{"type":"assistant/chunk","seq":668,"time":1783421445426,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"其他"}}} -{"type":"assistant/chunk","seq":669,"time":1783421445455,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"不"}}} -{"type":"assistant/chunk","seq":670,"time":1783421445486,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"涉及"}}} -{"type":"assistant/chunk","seq":671,"time":1783421445487,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":672,"time":1783421445487,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"写入"}}} -{"type":"assistant/chunk","seq":673,"time":1783421445515,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"的任务"}}} -{"type":"assistant/chunk","seq":674,"time":1783421445515,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":675,"time":1783421445515,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"随时"}}} -{"type":"assistant/chunk","seq":676,"time":1783421445515,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"可以"}}} -{"type":"assistant/chunk","seq":677,"time":1783421445545,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"告诉我"}}} -{"type":"assistant/chunk","seq":678,"time":1783421445545,"data":{"turn":3,"step":2,"chunk":{"type":"text-delta","index":1,"text":"!"}}} -{"type":"assistant/chunk","seq":679,"time":1783421445545,"data":{"turn":3,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"用户拒绝了写入权限的申请。这意味着我无法在当前沙盒模式下创建 b.md 文件。我需要如实告知用户这个情况。"}}}} -{"type":"assistant/chunk","seq":680,"time":1783421445545,"data":{"turn":3,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"抱歉,写入权限的申请被拒绝了,我目前无法在只读沙盒环境下创建 `b.md` 文件。\n\n你可以考虑以下替代方案:\n1. **自己在本地创建**:在终端执行 `touch /Users/wwl/workspace/deepseek-harness/b.md`\n2. **通过其他有写权限的工具或方式**来完成创建\n\n如果后续需要我处理其他不涉及文件写入的任务,随时可以告诉我!"}}}} -{"type":"assistant/chunk","seq":681,"time":1783421445545,"data":{"turn":3,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":150,"outputTokens":121,"cacheReadTokens":1792,"reasoningTokens":27}}}} -{"type":"assistant/chunk","seq":682,"time":1783421445545,"data":{"turn":3,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":683,"time":1783421445546,"data":{"turn":3,"step":2,"content":[{"type":"reasoning","text":"用户拒绝了写入权限的申请。这意味着我无法在当前沙盒模式下创建 b.md 文件。我需要如实告知用户这个情况。"},{"type":"text","text":"抱歉,写入权限的申请被拒绝了,我目前无法在只读沙盒环境下创建 `b.md` 文件。\n\n你可以考虑以下替代方案:\n1. **自己在本地创建**:在终端执行 `touch /Users/wwl/workspace/deepseek-harness/b.md`\n2. **通过其他有写权限的工具或方式**来完成创建\n\n如果后续需要我处理其他不涉及文件写入的任务,随时可以告诉我!"}],"usage":{"inputTokens":150,"outputTokens":121,"cacheReadTokens":1792,"reasoningTokens":27}},"sourceEventSeqs":[557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682],"surfaceOp":"append"} -{"type":"step/end","seq":684,"time":1783421445546,"data":{"turn":3,"step":2}} -{"type":"turn/end","seq":685,"time":1783421445546,"data":{"turn":3,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":686,"time":1783421455801,"data":{"turn":4,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"approval/policy","seq":687,"time":1783421455801,"data":{"policy":"never"}} -{"type":"user/message","seq":688,"time":1783421455801,"data":{"content":[{"type":"text","text":"帮我创建一个 c.md"}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"user/message","seq":689,"time":1783421455802,"data":{"content":[{"type":"text","text":"The approval policy changed from \"ask\" to \"never\" (changed by the user)."}],"source":{"kind":"plugin","plugin":"approval"}},"surfaceOp":"append"} -{"type":"step/start","seq":690,"time":1783421455802,"data":{"turn":4,"step":1}} -{"type":"request/header-delta","seq":691,"time":1783421455802,"data":{"system":{"keepStart":13,"keepEnd":0,"insert":["","Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation."]}}} -{"type":"assistant/chunk","seq":692,"time":1783421456825,"data":{"turn":4,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":693,"time":1783421456825,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":694,"time":1783421456957,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":695,"time":1783421456985,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":696,"time":1783421457014,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":697,"time":1783421457014,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" create"}}} -{"type":"assistant/chunk","seq":698,"time":1783421457014,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" c"}}} -{"type":"assistant/chunk","seq":699,"time":1783421457041,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":700,"time":1783421457042,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":701,"time":1783421457042,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" The"}}} -{"type":"assistant/chunk","seq":702,"time":1783421457042,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" approval"}}} -{"type":"assistant/chunk","seq":703,"time":1783421457069,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" policy"}}} -{"type":"assistant/chunk","seq":704,"time":1783421457070,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" has"}}} -{"type":"assistant/chunk","seq":705,"time":1783421457070,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" changed"}}} -{"type":"assistant/chunk","seq":706,"time":1783421457070,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":707,"time":1783421457098,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":708,"time":1783421457099,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"never"}}} -{"type":"assistant/chunk","seq":709,"time":1783421457099,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\""}}} -{"type":"assistant/chunk","seq":710,"time":1783421457099,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" which"}}} -{"type":"assistant/chunk","seq":711,"time":1783421457126,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" means"}}} -{"type":"assistant/chunk","seq":712,"time":1783421457126,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":713,"time":1783421457126,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" should"}}} -{"type":"assistant/chunk","seq":714,"time":1783421457156,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" not"}}} -{"type":"assistant/chunk","seq":715,"time":1783421457157,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" request"}}} -{"type":"assistant/chunk","seq":716,"time":1783421457184,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" escalation"}}} -{"type":"assistant/chunk","seq":717,"time":1783421457184,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":718,"time":1783421457212,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Since"}}} -{"type":"assistant/chunk","seq":719,"time":1783421457240,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":720,"time":1783421457267,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" operations"}}} -{"type":"assistant/chunk","seq":721,"time":1783421457268,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" are"}}} -{"type":"assistant/chunk","seq":722,"time":1783421457296,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" denied"}}} -{"type":"assistant/chunk","seq":723,"time":1783421457297,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" in"}}} -{"type":"assistant/chunk","seq":724,"time":1783421457297,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" read"}}} -{"type":"assistant/chunk","seq":725,"time":1783421457322,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-only"}}} -{"type":"assistant/chunk","seq":726,"time":1783421457323,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" mode"}}} -{"type":"assistant/chunk","seq":727,"time":1783421457323,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":728,"time":1783421457350,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":729,"time":1783421457351,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" can"}}} -{"type":"assistant/chunk","seq":730,"time":1783421457378,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"'t"}}} -{"type":"assistant/chunk","seq":731,"time":1783421457379,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" request"}}} -{"type":"assistant/chunk","seq":732,"time":1783421457379,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" approval"}}} -{"type":"assistant/chunk","seq":733,"time":1783421457406,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":734,"time":1783421457437,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":735,"time":1783421457438,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" need"}}} -{"type":"assistant/chunk","seq":736,"time":1783421457438,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":737,"time":1783421457438,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" inform"}}} -{"type":"assistant/chunk","seq":738,"time":1783421457466,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":739,"time":1783421457467,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":740,"time":1783421457467,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" that"}}} -{"type":"assistant/chunk","seq":741,"time":1783421457467,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":742,"time":1783421457493,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" cannot"}}} -{"type":"assistant/chunk","seq":743,"time":1783421457494,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" do"}}} -{"type":"assistant/chunk","seq":744,"time":1783421457521,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" this"}}} -{"type":"assistant/chunk","seq":745,"time":1783421457522,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" due"}}} -{"type":"assistant/chunk","seq":746,"time":1783421457522,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":747,"time":1783421457522,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" sand"}}} -{"type":"assistant/chunk","seq":748,"time":1783421457550,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} -{"type":"assistant/chunk","seq":749,"time":1783421457550,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" restrictions"}}} -{"type":"assistant/chunk","seq":750,"time":1783421457550,"data":{"turn":4,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":751,"time":1783421457551,"data":{"turn":4,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":752,"time":1783421457551,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"抱歉"}}} -{"type":"assistant/chunk","seq":753,"time":1783421457577,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":754,"time":1783421457577,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"当前"}}} -{"type":"assistant/chunk","seq":755,"time":1783421457606,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"环境"}}} -{"type":"assistant/chunk","seq":756,"time":1783421457606,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"仍"}}} -{"type":"assistant/chunk","seq":757,"time":1783421457606,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"处于"}}} -{"type":"assistant/chunk","seq":758,"time":1783421457634,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":759,"time":1783421457661,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"只"}}} -{"type":"assistant/chunk","seq":760,"time":1783421457662,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"读"}}} -{"type":"assistant/chunk","seq":761,"time":1783421457662,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"沙"}}} -{"type":"assistant/chunk","seq":762,"time":1783421457662,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"盒"}}} -{"type":"assistant/chunk","seq":763,"time":1783421457690,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"模式"}}} -{"type":"assistant/chunk","seq":764,"time":1783421457690,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":765,"time":1783421457690,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":766,"time":1783421457690,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"且"}}} -{"type":"assistant/chunk","seq":767,"time":1783421457718,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"写"}}} -{"type":"assistant/chunk","seq":768,"time":1783421457747,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"权限"}}} -{"type":"assistant/chunk","seq":769,"time":1783421457775,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"申请"}}} -{"type":"assistant/chunk","seq":770,"time":1783421457776,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"已被"}}} -{"type":"assistant/chunk","seq":771,"time":1783421457776,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"拒绝"}}} -{"type":"assistant/chunk","seq":772,"time":1783421457829,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":773,"time":1783421457829,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"我"}}} -{"type":"assistant/chunk","seq":774,"time":1783421457830,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"无法"}}} -{"type":"assistant/chunk","seq":775,"time":1783421457831,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":776,"time":1783421457831,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":777,"time":1783421457859,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"c"}}} -{"type":"assistant/chunk","seq":778,"time":1783421457859,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":779,"time":1783421457859,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":780,"time":1783421457860,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":781,"time":1783421457860,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":782,"time":1783421457887,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"。\n\n"}}} -{"type":"assistant/chunk","seq":783,"time":1783421457888,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"建议"}}} -{"type":"assistant/chunk","seq":784,"time":1783421457888,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"你在"}}} -{"type":"assistant/chunk","seq":785,"time":1783421457915,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"本地"}}} -{"type":"assistant/chunk","seq":786,"time":1783421457915,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"手动"}}} -{"type":"assistant/chunk","seq":787,"time":1783421457944,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"执行"}}} -{"type":"assistant/chunk","seq":788,"time":1783421457944,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":":\n"}}} -{"type":"assistant/chunk","seq":789,"time":1783421457944,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"```"}}} -{"type":"assistant/chunk","seq":790,"time":1783421457944,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"bash"}}} -{"type":"assistant/chunk","seq":791,"time":1783421457944,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"\n"}}} -{"type":"assistant/chunk","seq":792,"time":1783421457944,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"touch"}}} -{"type":"assistant/chunk","seq":793,"time":1783421457972,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":" /"}}} -{"type":"assistant/chunk","seq":794,"time":1783421457972,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"Users"}}} -{"type":"assistant/chunk","seq":795,"time":1783421457973,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":796,"time":1783421458003,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"ww"}}} -{"type":"assistant/chunk","seq":797,"time":1783421458003,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"l"}}} -{"type":"assistant/chunk","seq":798,"time":1783421458003,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":799,"time":1783421458003,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"works"}}} -{"type":"assistant/chunk","seq":800,"time":1783421458003,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"pace"}}} -{"type":"assistant/chunk","seq":801,"time":1783421458003,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"/de"}}} -{"type":"assistant/chunk","seq":802,"time":1783421458032,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"ep"}}} -{"type":"assistant/chunk","seq":803,"time":1783421458032,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"seek"}}} -{"type":"assistant/chunk","seq":804,"time":1783421458032,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"-h"}}} -{"type":"assistant/chunk","seq":805,"time":1783421458032,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"ar"}}} -{"type":"assistant/chunk","seq":806,"time":1783421458032,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"ness"}}} -{"type":"assistant/chunk","seq":807,"time":1783421458032,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"/c"}}} -{"type":"assistant/chunk","seq":808,"time":1783421458059,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":809,"time":1783421458060,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"\n"}}} -{"type":"assistant/chunk","seq":810,"time":1783421458060,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"```\n\n"}}} -{"type":"assistant/chunk","seq":811,"time":1783421458060,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"有其他"}}} -{"type":"assistant/chunk","seq":812,"time":1783421458087,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"不需要"}}} -{"type":"assistant/chunk","seq":813,"time":1783421458115,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"写入"}}} -{"type":"assistant/chunk","seq":814,"time":1783421458115,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":815,"time":1783421458143,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"的任务"}}} -{"type":"assistant/chunk","seq":816,"time":1783421458144,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"需要"}}} -{"type":"assistant/chunk","seq":817,"time":1783421458172,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"我"}}} -{"type":"assistant/chunk","seq":818,"time":1783421458172,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"帮忙"}}} -{"type":"assistant/chunk","seq":819,"time":1783421458172,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"吗"}}} -{"type":"assistant/chunk","seq":820,"time":1783421458202,"data":{"turn":4,"step":1,"chunk":{"type":"text-delta","index":1,"text":"?"}}} -{"type":"assistant/chunk","seq":821,"time":1783421458203,"data":{"turn":4,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants to create c.md. The approval policy has changed to \"never\" which means I should not request escalation. Since file operations are denied in read-only mode and I can't request approval, I need to inform the user that I cannot do this due to sandbox restrictions."}}}} -{"type":"assistant/chunk","seq":822,"time":1783421458203,"data":{"turn":4,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"抱歉,当前环境仍处于**只读沙盒模式**,且写权限申请已被拒绝,我无法创建 `c.md` 文件。\n\n建议你在本地手动执行:\n```bash\ntouch /Users/wwl/workspace/deepseek-harness/c.md\n```\n\n有其他不需要写入文件的任务需要我帮忙吗?"}}}} -{"type":"assistant/chunk","seq":823,"time":1783421458203,"data":{"turn":4,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":2096,"outputTokens":128,"cacheReadTokens":0,"reasoningTokens":58}}}} -{"type":"assistant/chunk","seq":824,"time":1783421458203,"data":{"turn":4,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":825,"time":1783421458203,"data":{"turn":4,"step":1,"content":[{"type":"reasoning","text":"The user wants to create c.md. The approval policy has changed to \"never\" which means I should not request escalation. Since file operations are denied in read-only mode and I can't request approval, I need to inform the user that I cannot do this due to sandbox restrictions."},{"type":"text","text":"抱歉,当前环境仍处于**只读沙盒模式**,且写权限申请已被拒绝,我无法创建 `c.md` 文件。\n\n建议你在本地手动执行:\n```bash\ntouch /Users/wwl/workspace/deepseek-harness/c.md\n```\n\n有其他不需要写入文件的任务需要我帮忙吗?"}],"usage":{"inputTokens":2096,"outputTokens":128,"cacheReadTokens":0,"reasoningTokens":58}},"sourceEventSeqs":[692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824],"surfaceOp":"append"} -{"type":"step/end","seq":826,"time":1783421458203,"data":{"turn":4,"step":1}} -{"type":"turn/end","seq":827,"time":1783421458203,"data":{"turn":4,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":828,"time":1783421478599,"data":{"turn":5,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"bash/sandbox-mode","seq":829,"time":1783421478599,"data":{"mode":"workspace-write"}} -{"type":"user/message","seq":830,"time":1783421478599,"data":{"content":[{"type":"text","text":"帮我创建一个 d.md"}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"user/message","seq":831,"time":1783421478600,"data":{"content":[{"type":"text","text":"The bash sandbox mode changed from \"read-only\" to \"workspace-write\" (changed by the user)."}],"source":{"kind":"plugin","plugin":"tool-bash"}},"surfaceOp":"append"} -{"type":"step/start","seq":832,"time":1783421478600,"data":{"turn":5,"step":1}} -{"type":"request/header-delta","seq":833,"time":1783421478600,"data":{"system":{"keepStart":12,"keepEnd":2,"insert":["Bash commands run under the \"workspace-write\" file sandbox."]}}} -{"type":"assistant/chunk","seq":834,"time":1783421479489,"data":{"turn":5,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":835,"time":1783421479489,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"现在"}}} -{"type":"assistant/chunk","seq":836,"time":1783421479638,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"沙"}}} -{"type":"assistant/chunk","seq":837,"time":1783421479666,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"盒"}}} -{"type":"assistant/chunk","seq":838,"time":1783421479666,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"模式"}}} -{"type":"assistant/chunk","seq":839,"time":1783421479666,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"已经"}}} -{"type":"assistant/chunk","seq":840,"time":1783421479666,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"改为"}}} -{"type":"assistant/chunk","seq":841,"time":1783421479695,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" workspace"}}} -{"type":"assistant/chunk","seq":842,"time":1783421479695,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-w"}}} -{"type":"assistant/chunk","seq":843,"time":1783421479695,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"rite"}}} -{"type":"assistant/chunk","seq":844,"time":1783421479695,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":845,"time":1783421479722,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"我可以"}}} -{"type":"assistant/chunk","seq":846,"time":1783421479751,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"直接"}}} -{"type":"assistant/chunk","seq":847,"time":1783421479751,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":848,"time":1783421479751,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":849,"time":1783421479751,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"了"}}} -{"type":"assistant/chunk","seq":850,"time":1783421479751,"data":{"turn":5,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":851,"time":1783421479779,"data":{"turn":5,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":852,"time":1783421479779,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":"好的"}}} -{"type":"assistant/chunk","seq":853,"time":1783421479779,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":854,"time":1783421479779,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":"现在"}}} -{"type":"assistant/chunk","seq":855,"time":1783421479807,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":"可以在"}}} -{"type":"assistant/chunk","seq":856,"time":1783421479836,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":"工作"}}} -{"type":"assistant/chunk","seq":857,"time":1783421479836,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":858,"time":1783421479864,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":"下"}}} -{"type":"assistant/chunk","seq":859,"time":1783421479864,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":"直接"}}} -{"type":"assistant/chunk","seq":860,"time":1783421479864,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":861,"time":1783421479892,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":"了"}}} -{"type":"assistant/chunk","seq":862,"time":1783421479921,"data":{"turn":5,"step":1,"chunk":{"type":"text-delta","index":1,"text":":"}}} -{"type":"assistant/chunk","seq":863,"time":1783421479977,"data":{"turn":5,"step":1,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":864,"time":1783421479977,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":865,"time":1783421480009,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":866,"time":1783421480009,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":867,"time":1783421480009,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":868,"time":1783421480009,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":869,"time":1783421480009,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":870,"time":1783421480037,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":871,"time":1783421480037,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":872,"time":1783421480037,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":" d"}}} -{"type":"assistant/chunk","seq":873,"time":1783421480037,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":874,"time":1783421480037,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":875,"time":1783421480065,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":876,"time":1783421480065,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":877,"time":1783421480094,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":878,"time":1783421480094,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":879,"time":1783421480094,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":880,"time":1783421480094,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":881,"time":1783421480123,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":882,"time":1783421480123,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":883,"time":1783421480123,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"touch"}}} -{"type":"assistant/chunk","seq":884,"time":1783421480123,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":885,"time":1783421480150,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"Users"}}} -{"type":"assistant/chunk","seq":886,"time":1783421480150,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":887,"time":1783421480150,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"ww"}}} -{"type":"assistant/chunk","seq":888,"time":1783421480150,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"l"}}} -{"type":"assistant/chunk","seq":889,"time":1783421480179,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":890,"time":1783421480179,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":891,"time":1783421480179,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":892,"time":1783421480179,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"/de"}}} -{"type":"assistant/chunk","seq":893,"time":1783421480179,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"ep"}}} -{"type":"assistant/chunk","seq":894,"time":1783421480179,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"seek"}}} -{"type":"assistant/chunk","seq":895,"time":1783421480208,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"-h"}}} -{"type":"assistant/chunk","seq":896,"time":1783421480208,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"ar"}}} -{"type":"assistant/chunk","seq":897,"time":1783421480208,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"ness"}}} -{"type":"assistant/chunk","seq":898,"time":1783421480208,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"/d"}}} -{"type":"assistant/chunk","seq":899,"time":1783421480208,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":900,"time":1783421480234,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":901,"time":1783421480234,"data":{"turn":5,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":902,"time":1783421480294,"data":{"turn":5,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"现在沙盒模式已经改为 workspace-write,我可以直接创建文件了。"}}}} -{"type":"assistant/chunk","seq":903,"time":1783421480294,"data":{"turn":5,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"好的,现在可以在工作目录下直接创建了:"}}}} -{"type":"assistant/chunk","seq":904,"time":1783421480294,"data":{"turn":5,"step":1,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","arguments":"{\"description\": \"创建 d.md 文件\", \"command\": \"touch /Users/wwl/workspace/deepseek-harness/d.md\"}"}}}} -{"type":"assistant/chunk","seq":905,"time":1783421480294,"data":{"turn":5,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":2209,"outputTokens":105,"cacheReadTokens":0,"reasoningTokens":16}}}} -{"type":"assistant/chunk","seq":906,"time":1783421480294,"data":{"turn":5,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":907,"time":1783421480294,"data":{"turn":5,"step":1,"content":[{"type":"reasoning","text":"现在沙盒模式已经改为 workspace-write,我可以直接创建文件了。"},{"type":"text","text":"好的,现在可以在工作目录下直接创建了:"},{"type":"tool-call","id":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","arguments":"{\"description\": \"创建 d.md 文件\", \"command\": \"touch /Users/wwl/workspace/deepseek-harness/d.md\"}"}],"usage":{"inputTokens":2209,"outputTokens":105,"cacheReadTokens":0,"reasoningTokens":16}},"sourceEventSeqs":[834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906],"surfaceOp":"append"} -{"type":"tool/call","seq":908,"time":1783421480294,"data":{"turn":5,"step":1,"callId":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","name":"bash","arguments":"{\"description\": \"创建 d.md 文件\", \"command\": \"touch /Users/wwl/workspace/deepseek-harness/d.md\"}"}} -{"type":"tool/result","seq":909,"time":1783421480356,"data":{"turn":5,"step":1,"callId":"call_00_KE1pSG2tZ8MlgO1bAdFg3508","content":[{"type":"text","text":"(no output)"}],"isError":false},"sourceEventSeqs":[908],"surfaceOp":"append"} -{"type":"step/end","seq":910,"time":1783421480356,"data":{"turn":5,"step":1}} -{"type":"step/start","seq":911,"time":1783421480357,"data":{"turn":5,"step":2}} -{"type":"assistant/chunk","seq":912,"time":1783421480773,"data":{"turn":5,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":913,"time":1783421480773,"data":{"turn":5,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":914,"time":1783421480913,"data":{"turn":5,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"成功"}}} -{"type":"assistant/chunk","seq":915,"time":1783421480913,"data":{"turn":5,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":916,"time":1783421480913,"data":{"turn":5,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"验证"}}} -{"type":"assistant/chunk","seq":917,"time":1783421480913,"data":{"turn":5,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"一下"}}} -{"type":"assistant/chunk","seq":918,"time":1783421480913,"data":{"turn":5,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":919,"time":1783421480962,"data":{"turn":5,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":920,"time":1783421480962,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":921,"time":1783421480990,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":922,"time":1783421480990,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":923,"time":1783421480990,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":924,"time":1783421481020,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":925,"time":1783421481020,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":926,"time":1783421481020,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":927,"time":1783421481020,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"验证"}}} -{"type":"assistant/chunk","seq":928,"time":1783421481049,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":929,"time":1783421481077,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"已"}}} -{"type":"assistant/chunk","seq":930,"time":1783421481077,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":931,"time":1783421481077,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":932,"time":1783421481105,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":933,"time":1783421481106,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":934,"time":1783421481106,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":935,"time":1783421481134,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":936,"time":1783421481134,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":937,"time":1783421481134,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":938,"time":1783421481134,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"ls"}}} -{"type":"assistant/chunk","seq":939,"time":1783421481163,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":" -"}}} -{"type":"assistant/chunk","seq":940,"time":1783421481163,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"la"}}} -{"type":"assistant/chunk","seq":941,"time":1783421481163,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":942,"time":1783421481163,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"Users"}}} -{"type":"assistant/chunk","seq":943,"time":1783421481163,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":944,"time":1783421481163,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"ww"}}} -{"type":"assistant/chunk","seq":945,"time":1783421481194,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"l"}}} -{"type":"assistant/chunk","seq":946,"time":1783421481194,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":947,"time":1783421481195,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":948,"time":1783421481195,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":949,"time":1783421481195,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"/de"}}} -{"type":"assistant/chunk","seq":950,"time":1783421481195,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"ep"}}} -{"type":"assistant/chunk","seq":951,"time":1783421481223,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"seek"}}} -{"type":"assistant/chunk","seq":952,"time":1783421481223,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"-h"}}} -{"type":"assistant/chunk","seq":953,"time":1783421481223,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"ar"}}} -{"type":"assistant/chunk","seq":954,"time":1783421481223,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"ness"}}} -{"type":"assistant/chunk","seq":955,"time":1783421481223,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"/d"}}} -{"type":"assistant/chunk","seq":956,"time":1783421481223,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":957,"time":1783421481252,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":958,"time":1783421481252,"data":{"turn":5,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":959,"time":1783421481315,"data":{"turn":5,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"创建成功,验证一下。"}}}} -{"type":"assistant/chunk","seq":960,"time":1783421481315,"data":{"turn":5,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","arguments":"{\"description\": \"验证文件已创建\", \"command\": \"ls -la /Users/wwl/workspace/deepseek-harness/d.md\"}"}}}} -{"type":"assistant/chunk","seq":961,"time":1783421481315,"data":{"turn":5,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":24,"outputTokens":86,"cacheReadTokens":2304,"reasoningTokens":6}}}} -{"type":"assistant/chunk","seq":962,"time":1783421481315,"data":{"turn":5,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":963,"time":1783421481315,"data":{"turn":5,"step":2,"content":[{"type":"reasoning","text":"创建成功,验证一下。"},{"type":"tool-call","id":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","arguments":"{\"description\": \"验证文件已创建\", \"command\": \"ls -la /Users/wwl/workspace/deepseek-harness/d.md\"}"}],"usage":{"inputTokens":24,"outputTokens":86,"cacheReadTokens":2304,"reasoningTokens":6}},"sourceEventSeqs":[912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962],"surfaceOp":"append"} -{"type":"tool/call","seq":964,"time":1783421481315,"data":{"turn":5,"step":2,"callId":"call_00_NJbkRNICoS9tkcJjHbbz7097","name":"bash","arguments":"{\"description\": \"验证文件已创建\", \"command\": \"ls -la /Users/wwl/workspace/deepseek-harness/d.md\"}"}} -{"type":"tool/result","seq":965,"time":1783421481385,"data":{"turn":5,"step":2,"callId":"call_00_NJbkRNICoS9tkcJjHbbz7097","content":[{"type":"text","text":"-rw-r--r--@ 1 wwl staff 0 Jul 7 18:51 /Users/wwl/workspace/deepseek-harness/d.md\n"}],"isError":false},"sourceEventSeqs":[964],"surfaceOp":"append"} -{"type":"step/end","seq":966,"time":1783421481385,"data":{"turn":5,"step":2}} -{"type":"step/start","seq":967,"time":1783421481385,"data":{"turn":5,"step":3}} -{"type":"assistant/chunk","seq":968,"time":1783421482029,"data":{"turn":5,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} -{"type":"assistant/chunk","seq":969,"time":1783421482029,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":970,"time":1783421482060,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"d"}}} -{"type":"assistant/chunk","seq":971,"time":1783421482061,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":972,"time":1783421482061,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":973,"time":1783421482061,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":974,"time":1783421482061,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"已"}}} -{"type":"assistant/chunk","seq":975,"time":1783421482061,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"成功"}}} -{"type":"assistant/chunk","seq":976,"time":1783421482089,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":977,"time":1783421482089,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"!"}}} -{"type":"assistant/chunk","seq":978,"time":1783421482089,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"当前"}}} -{"type":"assistant/chunk","seq":979,"time":1783421482089,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"工作"}}} -{"type":"assistant/chunk","seq":980,"time":1783421482119,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":981,"time":1783421482119,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":982,"time":1783421482119,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"已有的"}}} -{"type":"assistant/chunk","seq":983,"time":1783421482147,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":984,"time":1783421482147,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":":\n\n"}}} -{"type":"assistant/chunk","seq":985,"time":1783421482147,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"|"}}} -{"type":"assistant/chunk","seq":986,"time":1783421482147,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":987,"time":1783421482147,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":988,"time":1783421482176,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |"}}} -{"type":"assistant/chunk","seq":989,"time":1783421482176,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":990,"time":1783421482176,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"状态"}}} -{"type":"assistant/chunk","seq":991,"time":1783421482176,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |\n"}}} -{"type":"assistant/chunk","seq":992,"time":1783421482176,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"|"}}} -{"type":"assistant/chunk","seq":993,"time":1783421482205,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"------"}}} -{"type":"assistant/chunk","seq":994,"time":1783421482205,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"|"}}} -{"type":"assistant/chunk","seq":995,"time":1783421482205,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"------"}}} -{"type":"assistant/chunk","seq":996,"time":1783421482205,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"|\n"}}} -{"type":"assistant/chunk","seq":997,"time":1783421482205,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"|"}}} -{"type":"assistant/chunk","seq":998,"time":1783421482205,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":999,"time":1783421482233,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"a"}}} -{"type":"assistant/chunk","seq":1000,"time":1783421482233,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1001,"time":1783421482233,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":1002,"time":1783421482234,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |"}}} -{"type":"assistant/chunk","seq":1003,"time":1783421482234,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" ✅"}}} -{"type":"assistant/chunk","seq":1004,"time":1783421482234,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1005,"time":1783421482262,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"已"}}} -{"type":"assistant/chunk","seq":1006,"time":1783421482262,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1007,"time":1783421482262,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |\n"}}} -{"type":"assistant/chunk","seq":1008,"time":1783421482262,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"|"}}} -{"type":"assistant/chunk","seq":1009,"time":1783421482262,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":1010,"time":1783421482262,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"b"}}} -{"type":"assistant/chunk","seq":1011,"time":1783421482291,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1012,"time":1783421482291,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":1013,"time":1783421482291,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |"}}} -{"type":"assistant/chunk","seq":1014,"time":1783421482291,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" ❌"}}} -{"type":"assistant/chunk","seq":1015,"time":1783421482291,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1016,"time":1783421482319,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"未"}}} -{"type":"assistant/chunk","seq":1017,"time":1783421482320,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1018,"time":1783421482320,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"("}}} -{"type":"assistant/chunk","seq":1019,"time":1783421482320,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"之前"}}} -{"type":"assistant/chunk","seq":1020,"time":1783421482348,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"权限"}}} -{"type":"assistant/chunk","seq":1021,"time":1783421482348,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"被"}}} -{"type":"assistant/chunk","seq":1022,"time":1783421482348,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"拒"}}} -{"type":"assistant/chunk","seq":1023,"time":1783421482378,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":")"}}} -{"type":"assistant/chunk","seq":1024,"time":1783421482378,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |\n"}}} -{"type":"assistant/chunk","seq":1025,"time":1783421482379,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"|"}}} -{"type":"assistant/chunk","seq":1026,"time":1783421482379,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":1027,"time":1783421482379,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"c"}}} -{"type":"assistant/chunk","seq":1028,"time":1783421482379,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1029,"time":1783421482405,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":1030,"time":1783421482406,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |"}}} -{"type":"assistant/chunk","seq":1031,"time":1783421482406,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" ❌"}}} -{"type":"assistant/chunk","seq":1032,"time":1783421482406,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1033,"time":1783421482406,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"未"}}} -{"type":"assistant/chunk","seq":1034,"time":1783421482434,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1035,"time":1783421482435,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |\n"}}} -{"type":"assistant/chunk","seq":1036,"time":1783421482435,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"|"}}} -{"type":"assistant/chunk","seq":1037,"time":1783421482435,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":1038,"time":1783421482435,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"d"}}} -{"type":"assistant/chunk","seq":1039,"time":1783421482435,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1040,"time":1783421482464,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":1041,"time":1783421482464,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |"}}} -{"type":"assistant/chunk","seq":1042,"time":1783421482464,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" ✅"}}} -{"type":"assistant/chunk","seq":1043,"time":1783421482464,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1044,"time":1783421482464,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"刚"}}} -{"type":"assistant/chunk","seq":1045,"time":1783421482464,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1046,"time":1783421482493,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" |\n\n"}}} -{"type":"assistant/chunk","seq":1047,"time":1783421482493,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"需要"}}} -{"type":"assistant/chunk","seq":1048,"time":1783421482493,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"我"}}} -{"type":"assistant/chunk","seq":1049,"time":1783421482493,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"帮你"}}} -{"type":"assistant/chunk","seq":1050,"time":1783421482520,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"把"}}} -{"type":"assistant/chunk","seq":1051,"time":1783421482521,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":1052,"time":1783421482521,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"b"}}} -{"type":"assistant/chunk","seq":1053,"time":1783421482550,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1054,"time":1783421482550,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":1055,"time":1783421482550,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1056,"time":1783421482550,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"或"}}} -{"type":"assistant/chunk","seq":1057,"time":1783421482551,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":1058,"time":1783421482551,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"c"}}} -{"type":"assistant/chunk","seq":1059,"time":1783421482579,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1060,"time":1783421482579,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":1061,"time":1783421482579,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1062,"time":1783421482579,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"也"}}} -{"type":"assistant/chunk","seq":1063,"time":1783421482579,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"补"}}} -{"type":"assistant/chunk","seq":1064,"time":1783421482607,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"上"}}} -{"type":"assistant/chunk","seq":1065,"time":1783421482607,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"吗"}}} -{"type":"assistant/chunk","seq":1066,"time":1783421482607,"data":{"turn":5,"step":3,"chunk":{"type":"text-delta","index":0,"text":"?"}}} -{"type":"assistant/chunk","seq":1067,"time":1783421482608,"data":{"turn":5,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"`d.md` 已成功创建!当前工作目录下已有的文件:\n\n| 文件 | 状态 |\n|------|------|\n| `a.md` | ✅ 已创建 |\n| `b.md` | ❌ 未创建(之前权限被拒) |\n| `c.md` | ❌ 未创建 |\n| `d.md` | ✅ 刚创建 |\n\n需要我帮你把 `b.md` 或 `c.md` 也补上吗?"}}}} -{"type":"assistant/chunk","seq":1068,"time":1783421482608,"data":{"turn":5,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":160,"outputTokens":101,"cacheReadTokens":2304,"reasoningTokens":0}}}} -{"type":"assistant/chunk","seq":1069,"time":1783421482608,"data":{"turn":5,"step":3,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":1070,"time":1783421482608,"data":{"turn":5,"step":3,"content":[{"type":"text","text":"`d.md` 已成功创建!当前工作目录下已有的文件:\n\n| 文件 | 状态 |\n|------|------|\n| `a.md` | ✅ 已创建 |\n| `b.md` | ❌ 未创建(之前权限被拒) |\n| `c.md` | ❌ 未创建 |\n| `d.md` | ✅ 刚创建 |\n\n需要我帮你把 `b.md` 或 `c.md` 也补上吗?"}],"usage":{"inputTokens":160,"outputTokens":101,"cacheReadTokens":2304,"reasoningTokens":0}},"sourceEventSeqs":[968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069],"surfaceOp":"append"} -{"type":"step/end","seq":1071,"time":1783421482608,"data":{"turn":5,"step":3}} -{"type":"turn/end","seq":1072,"time":1783421482608,"data":{"turn":5,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":1073,"time":1783421508052,"data":{"turn":6,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":1074,"time":1783421508052,"data":{"content":[{"type":"text","text":"帮我在 ~ 创建一个 e.md"}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"step/start","seq":1075,"time":1783421508052,"data":{"turn":6,"step":1}} -{"type":"assistant/chunk","seq":1076,"time":1783421508475,"data":{"turn":6,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":1077,"time":1783421508475,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":1078,"time":1783421508591,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"想在"}}} -{"type":"assistant/chunk","seq":1079,"time":1783421508591,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" ~"}}} -{"type":"assistant/chunk","seq":1080,"time":1783421508591,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" ("}}} -{"type":"assistant/chunk","seq":1081,"time":1783421508633,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"home"}}} -{"type":"assistant/chunk","seq":1082,"time":1783421508633,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" directory"}}} -{"type":"assistant/chunk","seq":1083,"time":1783421508637,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":")"}}} -{"type":"assistant/chunk","seq":1084,"time":1783421508637,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1085,"time":1783421508637,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":1086,"time":1783421508637,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1087,"time":1783421508637,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" e"}}} -{"type":"assistant/chunk","seq":1088,"time":1783421508637,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1089,"time":1783421508673,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1090,"time":1783421508673,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"我的"}}} -{"type":"assistant/chunk","seq":1091,"time":1783421508691,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"工作"}}} -{"type":"assistant/chunk","seq":1092,"time":1783421508720,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1093,"time":1783421508721,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"是"}}} -{"type":"assistant/chunk","seq":1094,"time":1783421508721,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" /"}}} -{"type":"assistant/chunk","seq":1095,"time":1783421508721,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"Users"}}} -{"type":"assistant/chunk","seq":1096,"time":1783421508721,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"/"}}} -{"type":"assistant/chunk","seq":1097,"time":1783421508721,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ww"}}} -{"type":"assistant/chunk","seq":1098,"time":1783421508749,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"l"}}} -{"type":"assistant/chunk","seq":1099,"time":1783421508750,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"/"}}} -{"type":"assistant/chunk","seq":1100,"time":1783421508750,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"works"}}} -{"type":"assistant/chunk","seq":1101,"time":1783421508750,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"pace"}}} -{"type":"assistant/chunk","seq":1102,"time":1783421508750,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"/de"}}} -{"type":"assistant/chunk","seq":1103,"time":1783421508750,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ep"}}} -{"type":"assistant/chunk","seq":1104,"time":1783421508777,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"seek"}}} -{"type":"assistant/chunk","seq":1105,"time":1783421508777,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-h"}}} -{"type":"assistant/chunk","seq":1106,"time":1783421508777,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ar"}}} -{"type":"assistant/chunk","seq":1107,"time":1783421508777,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ness"}}} -{"type":"assistant/chunk","seq":1108,"time":1783421508777,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":1109,"time":1783421508778,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"但"}}} -{"type":"assistant/chunk","seq":1110,"time":1783421508806,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" ~"}}} -{"type":"assistant/chunk","seq":1111,"time":1783421508835,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1112,"time":1783421508835,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"是"}}} -{"type":"assistant/chunk","seq":1113,"time":1783421508864,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" /"}}} -{"type":"assistant/chunk","seq":1114,"time":1783421508864,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"Users"}}} -{"type":"assistant/chunk","seq":1115,"time":1783421508864,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"/"}}} -{"type":"assistant/chunk","seq":1116,"time":1783421508864,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ww"}}} -{"type":"assistant/chunk","seq":1117,"time":1783421508864,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"l"}}} -{"type":"assistant/chunk","seq":1118,"time":1783421508864,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1119,"time":1783421508893,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"我需要"}}} -{"type":"assistant/chunk","seq":1120,"time":1783421508894,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"确认"}}} -{"type":"assistant/chunk","seq":1121,"time":1783421508922,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"当前"}}} -{"type":"assistant/chunk","seq":1122,"time":1783421508922,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" workspace"}}} -{"type":"assistant/chunk","seq":1123,"time":1783421508951,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-w"}}} -{"type":"assistant/chunk","seq":1124,"time":1783421508951,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"rite"}}} -{"type":"assistant/chunk","seq":1125,"time":1783421508951,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1126,"time":1783421508951,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"模式"}}} -{"type":"assistant/chunk","seq":1127,"time":1783421508980,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"是否"}}} -{"type":"assistant/chunk","seq":1128,"time":1783421508980,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"允许"}}} -{"type":"assistant/chunk","seq":1129,"time":1783421508980,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"在"}}} -{"type":"assistant/chunk","seq":1130,"time":1783421509009,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" home"}}} -{"type":"assistant/chunk","seq":1131,"time":1783421509009,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1132,"time":1783421509009,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1133,"time":1783421509041,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":1134,"time":1783421509041,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"写入"}}} -{"type":"assistant/chunk","seq":1135,"time":1783421509070,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1136,"time":1783421509071,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"先"}}} -{"type":"assistant/chunk","seq":1137,"time":1783421509121,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"试试"}}} -{"type":"assistant/chunk","seq":1138,"time":1783421509121,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"看"}}} -{"type":"assistant/chunk","seq":1139,"time":1783421509121,"data":{"turn":6,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1140,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":1141,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":1142,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":1143,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1144,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":1145,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1146,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1147,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1148,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"在"}}} -{"type":"assistant/chunk","seq":1149,"time":1783421509278,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":" home"}}} -{"type":"assistant/chunk","seq":1150,"time":1783421509310,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1151,"time":1783421509310,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":1152,"time":1783421509310,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":1153,"time":1783421509310,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":" e"}}} -{"type":"assistant/chunk","seq":1154,"time":1783421509310,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1155,"time":1783421509330,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1156,"time":1783421509359,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1157,"time":1783421509359,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1158,"time":1783421509359,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":1159,"time":1783421509359,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1160,"time":1783421509359,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1161,"time":1783421509388,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1162,"time":1783421509388,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"touch"}}} -{"type":"assistant/chunk","seq":1163,"time":1783421509388,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":" ~"}}} -{"type":"assistant/chunk","seq":1164,"time":1783421509418,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":1165,"time":1783421509418,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"e"}}} -{"type":"assistant/chunk","seq":1166,"time":1783421509418,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1167,"time":1783421509418,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1168,"time":1783421509445,"data":{"turn":6,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":1169,"time":1783421509505,"data":{"turn":6,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"用户想在 ~ (home directory) 下创建 e.md。我的工作目录是 /Users/wwl/workspace/deepseek-harness,但 ~ 是 /Users/wwl。我需要确认当前 workspace-write 模式是否允许在 home 目录下写入。先试试看。"}}}} -{"type":"assistant/chunk","seq":1170,"time":1783421509505,"data":{"turn":6,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","arguments":"{\"description\": \"在 home 目录创建 e.md\", \"command\": \"touch ~/e.md\"}"}}}} -{"type":"assistant/chunk","seq":1171,"time":1783421509505,"data":{"turn":6,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":16,"outputTokens":132,"cacheReadTokens":2560,"reasoningTokens":63}}}} -{"type":"assistant/chunk","seq":1172,"time":1783421509505,"data":{"turn":6,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":1173,"time":1783421509505,"data":{"turn":6,"step":1,"content":[{"type":"reasoning","text":"用户想在 ~ (home directory) 下创建 e.md。我的工作目录是 /Users/wwl/workspace/deepseek-harness,但 ~ 是 /Users/wwl。我需要确认当前 workspace-write 模式是否允许在 home 目录下写入。先试试看。"},{"type":"tool-call","id":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","arguments":"{\"description\": \"在 home 目录创建 e.md\", \"command\": \"touch ~/e.md\"}"}],"usage":{"inputTokens":16,"outputTokens":132,"cacheReadTokens":2560,"reasoningTokens":63}},"sourceEventSeqs":[1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172],"surfaceOp":"append"} -{"type":"tool/call","seq":1174,"time":1783421509505,"data":{"turn":6,"step":1,"callId":"call_00_Rpnlygq8KCg3enlKpw7d6792","name":"bash","arguments":"{\"description\": \"在 home 目录创建 e.md\", \"command\": \"touch ~/e.md\"}"}} -{"type":"tool/result","seq":1175,"time":1783421509591,"data":{"turn":6,"step":1,"callId":"call_00_Rpnlygq8KCg3enlKpw7d6792","content":[{"type":"text","text":"[stderr]\ntouch: /Users/wwl/e.md: Operation not permitted\n[sandbox: file access denied under workspace-write mode]\n[exit code: 1]"}],"isError":false},"sourceEventSeqs":[1174],"surfaceOp":"append"} -{"type":"step/end","seq":1176,"time":1783421509592,"data":{"turn":6,"step":1}} -{"type":"step/start","seq":1177,"time":1783421509592,"data":{"turn":6,"step":2}} -{"type":"assistant/chunk","seq":1178,"time":1783421510299,"data":{"turn":6,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":1179,"time":1783421510299,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"works"}}} -{"type":"assistant/chunk","seq":1180,"time":1783421510479,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"pace"}}} -{"type":"assistant/chunk","seq":1181,"time":1783421510507,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-w"}}} -{"type":"assistant/chunk","seq":1182,"time":1783421510508,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"rite"}}} -{"type":"assistant/chunk","seq":1183,"time":1783421510508,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1184,"time":1783421510508,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"模式"}}} -{"type":"assistant/chunk","seq":1185,"time":1783421510537,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"只"}}} -{"type":"assistant/chunk","seq":1186,"time":1783421510537,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"允许"}}} -{"type":"assistant/chunk","seq":1187,"time":1783421510573,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"在工作"}}} -{"type":"assistant/chunk","seq":1188,"time":1783421510573,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1189,"time":1783421510595,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"("}}} -{"type":"assistant/chunk","seq":1190,"time":1783421510626,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"/"}}} -{"type":"assistant/chunk","seq":1191,"time":1783421510626,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"Users"}}} -{"type":"assistant/chunk","seq":1192,"time":1783421510626,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"/"}}} -{"type":"assistant/chunk","seq":1193,"time":1783421510626,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ww"}}} -{"type":"assistant/chunk","seq":1194,"time":1783421510627,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"l"}}} -{"type":"assistant/chunk","seq":1195,"time":1783421510627,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"/"}}} -{"type":"assistant/chunk","seq":1196,"time":1783421510652,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"works"}}} -{"type":"assistant/chunk","seq":1197,"time":1783421510652,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"pace"}}} -{"type":"assistant/chunk","seq":1198,"time":1783421510652,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"/de"}}} -{"type":"assistant/chunk","seq":1199,"time":1783421510652,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ep"}}} -{"type":"assistant/chunk","seq":1200,"time":1783421510652,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"seek"}}} -{"type":"assistant/chunk","seq":1201,"time":1783421510652,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-h"}}} -{"type":"assistant/chunk","seq":1202,"time":1783421510681,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ar"}}} -{"type":"assistant/chunk","seq":1203,"time":1783421510681,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ness"}}} -{"type":"assistant/chunk","seq":1204,"time":1783421510681,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":")"}}} -{"type":"assistant/chunk","seq":1205,"time":1783421510681,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":1206,"time":1783421510681,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"写入"}}} -{"type":"assistant/chunk","seq":1207,"time":1783421510682,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":1208,"time":1783421510710,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"不允许"}}} -{"type":"assistant/chunk","seq":1209,"time":1783421510739,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"在"}}} -{"type":"assistant/chunk","seq":1210,"time":1783421510739,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" home"}}} -{"type":"assistant/chunk","seq":1211,"time":1783421510768,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1212,"time":1783421510768,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1213,"time":1783421510768,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"写入"}}} -{"type":"assistant/chunk","seq":1214,"time":1783421510797,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1215,"time":1783421510797,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"我需要"}}} -{"type":"assistant/chunk","seq":1216,"time":1783421510826,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"申请"}}} -{"type":"assistant/chunk","seq":1217,"time":1783421510858,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"更"}}} -{"type":"assistant/chunk","seq":1218,"time":1783421510858,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"高级"}}} -{"type":"assistant/chunk","seq":1219,"time":1783421510888,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"的"}}} -{"type":"assistant/chunk","seq":1220,"time":1783421510888,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"权限"}}} -{"type":"assistant/chunk","seq":1221,"time":1783421510888,"data":{"turn":6,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1222,"time":1783421510916,"data":{"turn":6,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":1223,"time":1783421510916,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"当前"}}} -{"type":"assistant/chunk","seq":1224,"time":1783421510946,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":1225,"time":1783421511021,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"works"}}} -{"type":"assistant/chunk","seq":1226,"time":1783421511022,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"pace"}}} -{"type":"assistant/chunk","seq":1227,"time":1783421511022,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"-w"}}} -{"type":"assistant/chunk","seq":1228,"time":1783421511022,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"rite"}}} -{"type":"assistant/chunk","seq":1229,"time":1783421511022,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1230,"time":1783421511022,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1231,"time":1783421511067,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"模式"}}} -{"type":"assistant/chunk","seq":1232,"time":1783421511067,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"只"}}} -{"type":"assistant/chunk","seq":1233,"time":1783421511067,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"允许"}}} -{"type":"assistant/chunk","seq":1234,"time":1783421511095,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"在工作"}}} -{"type":"assistant/chunk","seq":1235,"time":1783421511095,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":1236,"time":1783421511095,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"下"}}} -{"type":"assistant/chunk","seq":1237,"time":1783421511124,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"写入"}}} -{"type":"assistant/chunk","seq":1238,"time":1783421511124,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":1239,"time":1783421511125,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"无法"}}} -{"type":"assistant/chunk","seq":1240,"time":1783421511153,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"写入"}}} -{"type":"assistant/chunk","seq":1241,"time":1783421511183,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":" home"}}} -{"type":"assistant/chunk","seq":1242,"time":1783421511183,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1243,"time":1783421511183,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":1244,"time":1783421511183,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"。"}}} -{"type":"assistant/chunk","seq":1245,"time":1783421511212,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"我需要"}}} -{"type":"assistant/chunk","seq":1246,"time":1783421511212,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"申请"}}} -{"type":"assistant/chunk","seq":1247,"time":1783421511212,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"完全"}}} -{"type":"assistant/chunk","seq":1248,"time":1783421511242,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"访问"}}} -{"type":"assistant/chunk","seq":1249,"time":1783421511243,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"权限"}}} -{"type":"assistant/chunk","seq":1250,"time":1783421511270,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"来完成"}}} -{"type":"assistant/chunk","seq":1251,"time":1783421511300,"data":{"turn":6,"step":2,"chunk":{"type":"text-delta","index":1,"text":"。"}}} -{"type":"assistant/chunk","seq":1252,"time":1783421511357,"data":{"turn":6,"step":2,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":1253,"time":1783421511357,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":1254,"time":1783421511357,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":1255,"time":1783421511357,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1256,"time":1783421511386,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":1257,"time":1783421511386,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1258,"time":1783421511386,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1259,"time":1783421511386,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1260,"time":1783421511416,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"touch"}}} -{"type":"assistant/chunk","seq":1261,"time":1783421511416,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" ~"}}} -{"type":"assistant/chunk","seq":1262,"time":1783421511416,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":1263,"time":1783421511416,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"e"}}} -{"type":"assistant/chunk","seq":1264,"time":1783421511416,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1265,"time":1783421511444,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1266,"time":1783421511473,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1267,"time":1783421511473,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1268,"time":1783421511473,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":1269,"time":1783421511473,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1270,"time":1783421511473,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1271,"time":1783421511506,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1272,"time":1783421511506,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"在"}}} -{"type":"assistant/chunk","seq":1273,"time":1783421511506,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" home"}}} -{"type":"assistant/chunk","seq":1274,"time":1783421511506,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1275,"time":1783421511506,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":1276,"time":1783421511535,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":1277,"time":1783421511535,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" e"}}} -{"type":"assistant/chunk","seq":1278,"time":1783421511535,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1279,"time":1783421511535,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1280,"time":1783421511564,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1281,"time":1783421511564,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1282,"time":1783421511593,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"sand"}}} -{"type":"assistant/chunk","seq":1283,"time":1783421511593,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"box"}}} -{"type":"assistant/chunk","seq":1284,"time":1783421511593,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"_per"}}} -{"type":"assistant/chunk","seq":1285,"time":1783421511593,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"missions"}}} -{"type":"assistant/chunk","seq":1286,"time":1783421511593,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1287,"time":1783421511593,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1288,"time":1783421511621,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1289,"time":1783421511621,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"danger"}}} -{"type":"assistant/chunk","seq":1290,"time":1783421511621,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"-full"}}} -{"type":"assistant/chunk","seq":1291,"time":1783421511621,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"-access"}}} -{"type":"assistant/chunk","seq":1292,"time":1783421511650,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1293,"time":1783421511679,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1294,"time":1783421511679,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1295,"time":1783421511679,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"just"}}} -{"type":"assistant/chunk","seq":1296,"time":1783421511679,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"ification"}}} -{"type":"assistant/chunk","seq":1297,"time":1783421511679,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1298,"time":1783421511709,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1299,"time":1783421511709,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1300,"time":1783421511709,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"用户"}}} -{"type":"assistant/chunk","seq":1301,"time":1783421511709,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"要求在"}}} -{"type":"assistant/chunk","seq":1302,"time":1783421511737,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" home"}}} -{"type":"assistant/chunk","seq":1303,"time":1783421511737,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1304,"time":1783421511737,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":1305,"time":1783421511737,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" (~"}}} -{"type":"assistant/chunk","seq":1306,"time":1783421511766,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":")"}}} -{"type":"assistant/chunk","seq":1307,"time":1783421511766,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1308,"time":1783421511766,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"下"}}} -{"type":"assistant/chunk","seq":1309,"time":1783421511766,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":1310,"time":1783421511767,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" e"}}} -{"type":"assistant/chunk","seq":1311,"time":1783421511767,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1312,"time":1783421511796,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1313,"time":1783421511796,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":1314,"time":1783421511824,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":","}}} -{"type":"assistant/chunk","seq":1315,"time":1783421511824,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"这"}}} -{"type":"assistant/chunk","seq":1316,"time":1783421511853,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"超出了"}}} -{"type":"assistant/chunk","seq":1317,"time":1783421511883,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" workspace"}}} -{"type":"assistant/chunk","seq":1318,"time":1783421511883,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"-w"}}} -{"type":"assistant/chunk","seq":1319,"time":1783421511884,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"rite"}}} -{"type":"assistant/chunk","seq":1320,"time":1783421511884,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1321,"time":1783421511911,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"模式"}}} -{"type":"assistant/chunk","seq":1322,"time":1783421511912,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"允许"}}} -{"type":"assistant/chunk","seq":1323,"time":1783421511940,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"的范围"}}} -{"type":"assistant/chunk","seq":1324,"time":1783421511968,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":","}}} -{"type":"assistant/chunk","seq":1325,"time":1783421511997,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"需要"}}} -{"type":"assistant/chunk","seq":1326,"time":1783421511997,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"完全"}}} -{"type":"assistant/chunk","seq":1327,"time":1783421511997,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"访问"}}} -{"type":"assistant/chunk","seq":1328,"time":1783421512026,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"权限"}}} -{"type":"assistant/chunk","seq":1329,"time":1783421512026,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"。"}}} -{"type":"assistant/chunk","seq":1330,"time":1783421512026,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1331,"time":1783421512055,"data":{"turn":6,"step":2,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":1332,"time":1783421512091,"data":{"turn":6,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"workspace-write 模式只允许在工作目录(/Users/wwl/workspace/deepseek-harness)下写入,不允许在 home 目录写入。我需要申请更高级的权限。"}}}} -{"type":"assistant/chunk","seq":1333,"time":1783421512091,"data":{"turn":6,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"当前 `workspace-write` 模式只允许在工作目录下写入,无法写入 home 目录。我需要申请完全访问权限来完成。"}}}} -{"type":"assistant/chunk","seq":1334,"time":1783421512091,"data":{"turn":6,"step":2,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","arguments":"{\"command\": \"touch ~/e.md\", \"description\": \"在 home 目录创建 e.md\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"用户要求在 home 目录 (~) 下创建 e.md 文件,这超出了 workspace-write 模式允许的范围,需要完全访问权限。\"}"}}}} -{"type":"assistant/chunk","seq":1335,"time":1783421512091,"data":{"turn":6,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":69,"outputTokens":206,"cacheReadTokens":2688,"reasoningTokens":43}}}} -{"type":"assistant/chunk","seq":1336,"time":1783421512091,"data":{"turn":6,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":1337,"time":1783421512091,"data":{"turn":6,"step":2,"content":[{"type":"reasoning","text":"workspace-write 模式只允许在工作目录(/Users/wwl/workspace/deepseek-harness)下写入,不允许在 home 目录写入。我需要申请更高级的权限。"},{"type":"text","text":"当前 `workspace-write` 模式只允许在工作目录下写入,无法写入 home 目录。我需要申请完全访问权限来完成。"},{"type":"tool-call","id":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","arguments":"{\"command\": \"touch ~/e.md\", \"description\": \"在 home 目录创建 e.md\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"用户要求在 home 目录 (~) 下创建 e.md 文件,这超出了 workspace-write 模式允许的范围,需要完全访问权限。\"}"}],"usage":{"inputTokens":69,"outputTokens":206,"cacheReadTokens":2688,"reasoningTokens":43}},"sourceEventSeqs":[1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257,1258,1259,1260,1261,1262,1263,1264,1265,1266,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279,1280,1281,1282,1283,1284,1285,1286,1287,1288,1289,1290,1291,1292,1293,1294,1295,1296,1297,1298,1299,1300,1301,1302,1303,1304,1305,1306,1307,1308,1309,1310,1311,1312,1313,1314,1315,1316,1317,1318,1319,1320,1321,1322,1323,1324,1325,1326,1327,1328,1329,1330,1331,1332,1333,1334,1335,1336],"surfaceOp":"append"} -{"type":"tool/call","seq":1338,"time":1783421512092,"data":{"turn":6,"step":2,"callId":"call_00_M4DDrUt9dRI5oYmqTxwb4616","name":"bash","arguments":"{\"command\": \"touch ~/e.md\", \"description\": \"在 home 目录创建 e.md\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"用户要求在 home 目录 (~) 下创建 e.md 文件,这超出了 workspace-write 模式允许的范围,需要完全访问权限。\"}"}} -{"type":"approval/asked","seq":1339,"time":1783421512092,"data":{"id":"587a78f5-df57-499e-98d7-0464f17734e6","toolName":"bash","callId":"call_00_M4DDrUt9dRI5oYmqTxwb4616","reason":"escalate sandbox to danger-full-access: 用户要求在 home 目录 (~) 下创建 e.md 文件,这超出了 workspace-write 模式允许的范围,需要完全访问权限。"}} -{"type":"approval/decided","seq":1340,"time":1783421512092,"data":{"id":"587a78f5-df57-499e-98d7-0464f17734e6","outcome":"rejected"}} -{"type":"tool/result","seq":1341,"time":1783421512092,"data":{"turn":6,"step":2,"callId":"call_00_M4DDrUt9dRI5oYmqTxwb4616","content":[{"type":"text","text":"Error: the user rejected escalating this command to \"danger-full-access\""}],"isError":true},"sourceEventSeqs":[1338],"surfaceOp":"append"} -{"type":"step/end","seq":1342,"time":1783421512092,"data":{"turn":6,"step":2}} -{"type":"step/start","seq":1343,"time":1783421512093,"data":{"turn":6,"step":3}} -{"type":"assistant/chunk","seq":1344,"time":1783421512675,"data":{"turn":6,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":1345,"time":1783421512675,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"又被"}}} -{"type":"assistant/chunk","seq":1346,"time":1783421512781,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"拒绝了"}}} -{"type":"assistant/chunk","seq":1347,"time":1783421512813,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1348,"time":1783421512813,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"没办法"}}} -{"type":"assistant/chunk","seq":1349,"time":1783421512841,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"在"}}} -{"type":"assistant/chunk","seq":1350,"time":1783421512841,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" home"}}} -{"type":"assistant/chunk","seq":1351,"time":1783421512868,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1352,"time":1783421512868,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1353,"time":1783421512868,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":1354,"time":1783421512897,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1355,"time":1783421512897,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"文件"}}} -{"type":"assistant/chunk","seq":1356,"time":1783421512897,"data":{"turn":6,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1357,"time":1783421512926,"data":{"turn":6,"step":3,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":1358,"time":1783421512926,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"权限"}}} -{"type":"assistant/chunk","seq":1359,"time":1783421512957,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"申请"}}} -{"type":"assistant/chunk","seq":1360,"time":1783421512957,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"被"}}} -{"type":"assistant/chunk","seq":1361,"time":1783421512957,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"拒绝了"}}} -{"type":"assistant/chunk","seq":1362,"time":1783421512984,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":1363,"time":1783421512984,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"我"}}} -{"type":"assistant/chunk","seq":1364,"time":1783421513014,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"无法"}}} -{"type":"assistant/chunk","seq":1365,"time":1783421513041,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"在"}}} -{"type":"assistant/chunk","seq":1366,"time":1783421513070,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":1367,"time":1783421513070,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"~"}}} -{"type":"assistant/chunk","seq":1368,"time":1783421513070,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1369,"time":1783421513070,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" ("}}} -{"type":"assistant/chunk","seq":1370,"time":1783421513099,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"home"}}} -{"type":"assistant/chunk","seq":1371,"time":1783421513099,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1372,"time":1783421513128,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":1373,"time":1783421513128,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":")"}}} -{"type":"assistant/chunk","seq":1374,"time":1783421513128,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1375,"time":1783421513128,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"下"}}} -{"type":"assistant/chunk","seq":1376,"time":1783421513128,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":1377,"time":1783421513128,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":1378,"time":1783421513160,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"e"}}} -{"type":"assistant/chunk","seq":1379,"time":1783421513160,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":1380,"time":1783421513160,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1381,"time":1783421513160,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"。\n\n"}}} -{"type":"assistant/chunk","seq":1382,"time":1783421513161,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":1383,"time":1783421513191,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"建议"}}} -{"type":"assistant/chunk","seq":1384,"time":1783421513191,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"替代"}}} -{"type":"assistant/chunk","seq":1385,"time":1783421513191,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"方案"}}} -{"type":"assistant/chunk","seq":1386,"time":1783421513218,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":":"}}} -{"type":"assistant/chunk","seq":1387,"time":1783421513246,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"**\n"}}} -{"type":"assistant/chunk","seq":1388,"time":1783421513247,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"1"}}} -{"type":"assistant/chunk","seq":1389,"time":1783421513247,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"."}}} -{"type":"assistant/chunk","seq":1390,"time":1783421513247,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" **"}}} -{"type":"assistant/chunk","seq":1391,"time":1783421513277,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"在工作"}}} -{"type":"assistant/chunk","seq":1392,"time":1783421513307,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":1393,"time":1783421513307,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"下"}}} -{"type":"assistant/chunk","seq":1394,"time":1783421513307,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":1395,"time":1783421513337,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":1396,"time":1783421513337,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" —"}}} -{"type":"assistant/chunk","seq":1397,"time":1783421513337,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1398,"time":1783421513362,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"如果你"}}} -{"type":"assistant/chunk","seq":1399,"time":1783421513391,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"允许"}}} -{"type":"assistant/chunk","seq":1400,"time":1783421513421,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":1401,"time":1783421513421,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"我可以"}}} -{"type":"assistant/chunk","seq":1402,"time":1783421513421,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"把"}}} -{"type":"assistant/chunk","seq":1403,"time":1783421513451,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":1404,"time":1783421513452,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"e"}}} -{"type":"assistant/chunk","seq":1405,"time":1783421513452,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":1406,"time":1783421513452,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1407,"time":1783421513452,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1408,"time":1783421513452,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":1409,"time":1783421513478,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"到"}}} -{"type":"assistant/chunk","seq":1410,"time":1783421513478,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"当前"}}} -{"type":"assistant/chunk","seq":1411,"time":1783421513478,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"工作"}}} -{"type":"assistant/chunk","seq":1412,"time":1783421513507,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":1413,"time":1783421513507,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" `/"}}} -{"type":"assistant/chunk","seq":1414,"time":1783421513507,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"Users"}}} -{"type":"assistant/chunk","seq":1415,"time":1783421513507,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1416,"time":1783421513536,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"ww"}}} -{"type":"assistant/chunk","seq":1417,"time":1783421513536,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"l"}}} -{"type":"assistant/chunk","seq":1418,"time":1783421513536,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1419,"time":1783421513536,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"works"}}} -{"type":"assistant/chunk","seq":1420,"time":1783421513536,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"pace"}}} -{"type":"assistant/chunk","seq":1421,"time":1783421513536,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"/de"}}} -{"type":"assistant/chunk","seq":1422,"time":1783421513567,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"ep"}}} -{"type":"assistant/chunk","seq":1423,"time":1783421513567,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"seek"}}} -{"type":"assistant/chunk","seq":1424,"time":1783421513567,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"-h"}}} -{"type":"assistant/chunk","seq":1425,"time":1783421513567,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"ar"}}} -{"type":"assistant/chunk","seq":1426,"time":1783421513567,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"ness"}}} -{"type":"assistant/chunk","seq":1427,"time":1783421513567,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1428,"time":1783421513594,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"`\n"}}} -{"type":"assistant/chunk","seq":1429,"time":1783421513594,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"2"}}} -{"type":"assistant/chunk","seq":1430,"time":1783421513594,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"."}}} -{"type":"assistant/chunk","seq":1431,"time":1783421513594,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" **"}}} -{"type":"assistant/chunk","seq":1432,"time":1783421513594,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"自行"}}} -{"type":"assistant/chunk","seq":1433,"time":1783421513595,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"在"}}} -{"type":"assistant/chunk","seq":1434,"time":1783421513625,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"本地"}}} -{"type":"assistant/chunk","seq":1435,"time":1783421513625,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":1436,"time":1783421513626,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":1437,"time":1783421513626,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" —"}}} -{"type":"assistant/chunk","seq":1438,"time":1783421513626,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1439,"time":1783421513653,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"在"}}} -{"type":"assistant/chunk","seq":1440,"time":1783421513653,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"终端"}}} -{"type":"assistant/chunk","seq":1441,"time":1783421513653,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"执行"}}} -{"type":"assistant/chunk","seq":1442,"time":1783421513681,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":":\n"}}} -{"type":"assistant/chunk","seq":1443,"time":1783421513681,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1444,"time":1783421513681,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" ```"}}} -{"type":"assistant/chunk","seq":1445,"time":1783421513681,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"bash"}}} -{"type":"assistant/chunk","seq":1446,"time":1783421513681,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"\n"}}} -{"type":"assistant/chunk","seq":1447,"time":1783421513681,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1448,"time":1783421513681,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" touch"}}} -{"type":"assistant/chunk","seq":1449,"time":1783421513709,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" ~"}}} -{"type":"assistant/chunk","seq":1450,"time":1783421513709,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1451,"time":1783421513709,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"e"}}} -{"type":"assistant/chunk","seq":1452,"time":1783421513709,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":1453,"time":1783421513709,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"\n"}}} -{"type":"assistant/chunk","seq":1454,"time":1783421513709,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1455,"time":1783421513740,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" ```\n\n"}}} -{"type":"assistant/chunk","seq":1456,"time":1783421513740,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"需要"}}} -{"type":"assistant/chunk","seq":1457,"time":1783421513772,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"我用"}}} -{"type":"assistant/chunk","seq":1458,"time":1783421513799,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"方案"}}} -{"type":"assistant/chunk","seq":1459,"time":1783421513828,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1460,"time":1783421513828,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"1"}}} -{"type":"assistant/chunk","seq":1461,"time":1783421513828,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1462,"time":1783421513828,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"在工作"}}} -{"type":"assistant/chunk","seq":1463,"time":1783421513856,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":1464,"time":1783421513856,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"下"}}} -{"type":"assistant/chunk","seq":1465,"time":1783421513886,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":1466,"time":1783421513886,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":1467,"time":1783421513886,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"e"}}} -{"type":"assistant/chunk","seq":1468,"time":1783421513886,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":1469,"time":1783421513886,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1470,"time":1783421513886,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1471,"time":1783421513917,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"吗"}}} -{"type":"assistant/chunk","seq":1472,"time":1783421513917,"data":{"turn":6,"step":3,"chunk":{"type":"text-delta","index":1,"text":"?"}}} -{"type":"assistant/chunk","seq":1473,"time":1783421513917,"data":{"turn":6,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"又被拒绝了。没办法在 home 目录下创建文件。"}}}} -{"type":"assistant/chunk","seq":1474,"time":1783421513917,"data":{"turn":6,"step":3,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"权限申请被拒绝了,我无法在 `~` (home 目录) 下创建 `e.md`。\n\n**建议替代方案:**\n1. **在工作目录下创建** — 如果你允许,我可以把 `e.md` 创建到当前工作目录 `/Users/wwl/workspace/deepseek-harness/`\n2. **自行在本地创建** — 在终端执行:\n ```bash\n touch ~/e.md\n ```\n\n需要我用方案 1 在工作目录下创建 `e.md` 吗?"}}}} -{"type":"assistant/chunk","seq":1475,"time":1783421513917,"data":{"turn":6,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":301,"outputTokens":128,"cacheReadTokens":2688,"reasoningTokens":12}}}} -{"type":"assistant/chunk","seq":1476,"time":1783421513917,"data":{"turn":6,"step":3,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":1477,"time":1783421513918,"data":{"turn":6,"step":3,"content":[{"type":"reasoning","text":"又被拒绝了。没办法在 home 目录下创建文件。"},{"type":"text","text":"权限申请被拒绝了,我无法在 `~` (home 目录) 下创建 `e.md`。\n\n**建议替代方案:**\n1. **在工作目录下创建** — 如果你允许,我可以把 `e.md` 创建到当前工作目录 `/Users/wwl/workspace/deepseek-harness/`\n2. **自行在本地创建** — 在终端执行:\n ```bash\n touch ~/e.md\n ```\n\n需要我用方案 1 在工作目录下创建 `e.md` 吗?"}],"usage":{"inputTokens":301,"outputTokens":128,"cacheReadTokens":2688,"reasoningTokens":12}},"sourceEventSeqs":[1344,1345,1346,1347,1348,1349,1350,1351,1352,1353,1354,1355,1356,1357,1358,1359,1360,1361,1362,1363,1364,1365,1366,1367,1368,1369,1370,1371,1372,1373,1374,1375,1376,1377,1378,1379,1380,1381,1382,1383,1384,1385,1386,1387,1388,1389,1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1403,1404,1405,1406,1407,1408,1409,1410,1411,1412,1413,1414,1415,1416,1417,1418,1419,1420,1421,1422,1423,1424,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1476],"surfaceOp":"append"} -{"type":"step/end","seq":1478,"time":1783421513918,"data":{"turn":6,"step":3}} -{"type":"turn/end","seq":1479,"time":1783421513918,"data":{"turn":6,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":1480,"time":1783421524030,"data":{"turn":7,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"approval/policy","seq":1481,"time":1783421524030,"data":{"policy":"ask"}} -{"type":"user/message","seq":1482,"time":1783421524030,"data":{"content":[{"type":"text","text":"帮我在 ~ 创建一个 f.md"}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"user/message","seq":1483,"time":1783421524030,"data":{"content":[{"type":"text","text":"The approval policy changed from \"never\" to \"ask\" (changed by the user)."}],"source":{"kind":"plugin","plugin":"approval"}},"surfaceOp":"append"} -{"type":"step/start","seq":1484,"time":1783421524030,"data":{"turn":7,"step":1}} -{"type":"request/header-delta","seq":1485,"time":1783421524030,"data":{"system":{"keepStart":13,"keepEnd":0,"insert":[]}}} -{"type":"assistant/chunk","seq":1486,"time":1783421524940,"data":{"turn":7,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":1487,"time":1783421524941,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":1488,"time":1783421525045,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"又"}}} -{"type":"assistant/chunk","seq":1489,"time":1783421525073,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"想在"}}} -{"type":"assistant/chunk","seq":1490,"time":1783421525101,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" home"}}} -{"type":"assistant/chunk","seq":1491,"time":1783421525131,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1492,"time":1783421525131,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1493,"time":1783421525131,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":1494,"time":1783421525131,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1495,"time":1783421525131,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" f"}}} -{"type":"assistant/chunk","seq":1496,"time":1783421525131,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1497,"time":1783421525158,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1498,"time":1783421525159,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"之前的"}}} -{"type":"assistant/chunk","seq":1499,"time":1783421525195,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" e"}}} -{"type":"assistant/chunk","seq":1500,"time":1783421525220,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1501,"time":1783421525220,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1502,"time":1783421525220,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"因为"}}} -{"type":"assistant/chunk","seq":1503,"time":1783421525249,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"权限"}}} -{"type":"assistant/chunk","seq":1504,"time":1783421525278,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"被"}}} -{"type":"assistant/chunk","seq":1505,"time":1783421525278,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"拒"}}} -{"type":"assistant/chunk","seq":1506,"time":1783421525307,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"没有"}}} -{"type":"assistant/chunk","seq":1507,"time":1783421525307,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1508,"time":1783421525337,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"成功"}}} -{"type":"assistant/chunk","seq":1509,"time":1783421525338,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1510,"time":1783421525338,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"现在"}}} -{"type":"assistant/chunk","seq":1511,"time":1783421525338,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" policy"}}} -{"type":"assistant/chunk","seq":1512,"time":1783421525364,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1513,"time":1783421525364,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"改"}}} -{"type":"assistant/chunk","seq":1514,"time":1783421525393,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"成了"}}} -{"type":"assistant/chunk","seq":1515,"time":1783421525393,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":1516,"time":1783421525393,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ask"}}} -{"type":"assistant/chunk","seq":1517,"time":1783421525393,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\","}}} -{"type":"assistant/chunk","seq":1518,"time":1783421525422,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"所以我"}}} -{"type":"assistant/chunk","seq":1519,"time":1783421525451,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"需要"}}} -{"type":"assistant/chunk","seq":1520,"time":1783421525451,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"申请"}}} -{"type":"assistant/chunk","seq":1521,"time":1783421525480,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" danger"}}} -{"type":"assistant/chunk","seq":1522,"time":1783421525510,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-full"}}} -{"type":"assistant/chunk","seq":1523,"time":1783421525510,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-access"}}} -{"type":"assistant/chunk","seq":1524,"time":1783421525510,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1525,"time":1783421525510,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"权限"}}} -{"type":"assistant/chunk","seq":1526,"time":1783421525510,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":1527,"time":1783421525538,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":1528,"time":1783421525539,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"会被"}}} -{"type":"assistant/chunk","seq":1529,"time":1783421525570,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"询问"}}} -{"type":"assistant/chunk","seq":1530,"time":1783421525597,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"是否"}}} -{"type":"assistant/chunk","seq":1531,"time":1783421525597,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"批准"}}} -{"type":"assistant/chunk","seq":1532,"time":1783421525626,"data":{"turn":7,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1533,"time":1783421525714,"data":{"turn":7,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":1534,"time":1783421525714,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":1535,"time":1783421525714,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":1536,"time":1783421525714,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1537,"time":1783421525743,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":1538,"time":1783421525743,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1539,"time":1783421525743,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1540,"time":1783421525744,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1541,"time":1783421525775,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"touch"}}} -{"type":"assistant/chunk","seq":1542,"time":1783421525775,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" ~"}}} -{"type":"assistant/chunk","seq":1543,"time":1783421525775,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":1544,"time":1783421525775,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"f"}}} -{"type":"assistant/chunk","seq":1545,"time":1783421525775,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1546,"time":1783421525803,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1547,"time":1783421525833,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1548,"time":1783421525833,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1549,"time":1783421525833,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":1550,"time":1783421525833,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1551,"time":1783421525833,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1552,"time":1783421525864,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1553,"time":1783421525864,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"在"}}} -{"type":"assistant/chunk","seq":1554,"time":1783421525864,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" home"}}} -{"type":"assistant/chunk","seq":1555,"time":1783421525864,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1556,"time":1783421525864,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":1557,"time":1783421525891,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":1558,"time":1783421525891,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" f"}}} -{"type":"assistant/chunk","seq":1559,"time":1783421525892,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1560,"time":1783421525892,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1561,"time":1783421525920,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1562,"time":1783421525920,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1563,"time":1783421525949,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"sand"}}} -{"type":"assistant/chunk","seq":1564,"time":1783421525949,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"box"}}} -{"type":"assistant/chunk","seq":1565,"time":1783421525949,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"_per"}}} -{"type":"assistant/chunk","seq":1566,"time":1783421525949,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"missions"}}} -{"type":"assistant/chunk","seq":1567,"time":1783421525949,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1568,"time":1783421525949,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1569,"time":1783421525979,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1570,"time":1783421525979,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"danger"}}} -{"type":"assistant/chunk","seq":1571,"time":1783421525979,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"-full"}}} -{"type":"assistant/chunk","seq":1572,"time":1783421525979,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"-access"}}} -{"type":"assistant/chunk","seq":1573,"time":1783421526008,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1574,"time":1783421526037,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1575,"time":1783421526037,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1576,"time":1783421526037,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"just"}}} -{"type":"assistant/chunk","seq":1577,"time":1783421526037,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"ification"}}} -{"type":"assistant/chunk","seq":1578,"time":1783421526037,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1579,"time":1783421526065,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1580,"time":1783421526065,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1581,"time":1783421526065,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"用户"}}} -{"type":"assistant/chunk","seq":1582,"time":1783421526095,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"要求在"}}} -{"type":"assistant/chunk","seq":1583,"time":1783421526095,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" home"}}} -{"type":"assistant/chunk","seq":1584,"time":1783421526095,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1585,"time":1783421526125,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":1586,"time":1783421526125,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" (~"}}} -{"type":"assistant/chunk","seq":1587,"time":1783421526125,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":")"}}} -{"type":"assistant/chunk","seq":1588,"time":1783421526125,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1589,"time":1783421526125,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"下"}}} -{"type":"assistant/chunk","seq":1590,"time":1783421526125,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":1591,"time":1783421526153,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" f"}}} -{"type":"assistant/chunk","seq":1592,"time":1783421526153,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1593,"time":1783421526153,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1594,"time":1783421526153,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":1595,"time":1783421526153,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":","}}} -{"type":"assistant/chunk","seq":1596,"time":1783421526153,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"需要"}}} -{"type":"assistant/chunk","seq":1597,"time":1783421526181,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"完全"}}} -{"type":"assistant/chunk","seq":1598,"time":1783421526181,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"访问"}}} -{"type":"assistant/chunk","seq":1599,"time":1783421526211,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"权限"}}} -{"type":"assistant/chunk","seq":1600,"time":1783421526211,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"才能"}}} -{"type":"assistant/chunk","seq":1601,"time":1783421526211,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"写入"}}} -{"type":"assistant/chunk","seq":1602,"time":1783421526240,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" home"}}} -{"type":"assistant/chunk","seq":1603,"time":1783421526269,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1604,"time":1783421526269,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":1605,"time":1783421526269,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"。"}}} -{"type":"assistant/chunk","seq":1606,"time":1783421526269,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1607,"time":1783421526298,"data":{"turn":7,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":1608,"time":1783421526331,"data":{"turn":7,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"用户又想在 home 目录下创建 f.md。之前的 e.md 因为权限被拒没有创建成功。现在 policy 改成了 \"ask\",所以我需要申请 danger-full-access 权限,用户会被询问是否批准。"}}}} -{"type":"assistant/chunk","seq":1609,"time":1783421526331,"data":{"turn":7,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","arguments":"{\"command\": \"touch ~/f.md\", \"description\": \"在 home 目录创建 f.md\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"用户要求在 home 目录 (~) 下创建 f.md 文件,需要完全访问权限才能写入 home 目录。\"}"}}}} -{"type":"assistant/chunk","seq":1610,"time":1783421526331,"data":{"turn":7,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3120,"outputTokens":176,"cacheReadTokens":0,"reasoningTokens":46}}}} -{"type":"assistant/chunk","seq":1611,"time":1783421526331,"data":{"turn":7,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":1612,"time":1783421526331,"data":{"turn":7,"step":1,"content":[{"type":"reasoning","text":"用户又想在 home 目录下创建 f.md。之前的 e.md 因为权限被拒没有创建成功。现在 policy 改成了 \"ask\",所以我需要申请 danger-full-access 权限,用户会被询问是否批准。"},{"type":"tool-call","id":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","arguments":"{\"command\": \"touch ~/f.md\", \"description\": \"在 home 目录创建 f.md\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"用户要求在 home 目录 (~) 下创建 f.md 文件,需要完全访问权限才能写入 home 目录。\"}"}],"usage":{"inputTokens":3120,"outputTokens":176,"cacheReadTokens":0,"reasoningTokens":46}},"sourceEventSeqs":[1486,1487,1488,1489,1490,1491,1492,1493,1494,1495,1496,1497,1498,1499,1500,1501,1502,1503,1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,1515,1516,1517,1518,1519,1520,1521,1522,1523,1524,1525,1526,1527,1528,1529,1530,1531,1532,1533,1534,1535,1536,1537,1538,1539,1540,1541,1542,1543,1544,1545,1546,1547,1548,1549,1550,1551,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1563,1564,1565,1566,1567,1568,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,1591,1592,1593,1594,1595,1596,1597,1598,1599,1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1611],"surfaceOp":"append"} -{"type":"tool/call","seq":1613,"time":1783421526331,"data":{"turn":7,"step":1,"callId":"call_00_HSRl7qhjhdr20Nc8bdiY2510","name":"bash","arguments":"{\"command\": \"touch ~/f.md\", \"description\": \"在 home 目录创建 f.md\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"用户要求在 home 目录 (~) 下创建 f.md 文件,需要完全访问权限才能写入 home 目录。\"}"}} -{"type":"approval/asked","seq":1614,"time":1783421526332,"data":{"id":"d567b8a5-f25c-4317-a43f-8e9cac02df16","toolName":"bash","callId":"call_00_HSRl7qhjhdr20Nc8bdiY2510","reason":"escalate sandbox to danger-full-access: 用户要求在 home 目录 (~) 下创建 f.md 文件,需要完全访问权限才能写入 home 目录。"}} -{"type":"approval/decided","seq":1615,"time":1783421531141,"data":{"id":"d567b8a5-f25c-4317-a43f-8e9cac02df16","outcome":"allowed-once"}} -{"type":"tool/result","seq":1616,"time":1783421531215,"data":{"turn":7,"step":1,"callId":"call_00_HSRl7qhjhdr20Nc8bdiY2510","content":[{"type":"text","text":"(no output)"}],"isError":false},"sourceEventSeqs":[1613],"surfaceOp":"append"} -{"type":"step/end","seq":1617,"time":1783421531215,"data":{"turn":7,"step":1}} -{"type":"step/start","seq":1618,"time":1783421531216,"data":{"turn":7,"step":2}} -{"type":"assistant/chunk","seq":1619,"time":1783421531825,"data":{"turn":7,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":1620,"time":1783421531825,"data":{"turn":7,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"执行"}}} -{"type":"assistant/chunk","seq":1621,"time":1783421531942,"data":{"turn":7,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"成功"}}} -{"type":"assistant/chunk","seq":1622,"time":1783421531974,"data":{"turn":7,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":1623,"time":1783421531974,"data":{"turn":7,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"验证"}}} -{"type":"assistant/chunk","seq":1624,"time":1783421531999,"data":{"turn":7,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"一下"}}} -{"type":"assistant/chunk","seq":1625,"time":1783421532000,"data":{"turn":7,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1626,"time":1783421532057,"data":{"turn":7,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":1627,"time":1783421532057,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":1628,"time":1783421532086,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":1629,"time":1783421532086,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1630,"time":1783421532086,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":1631,"time":1783421532115,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1632,"time":1783421532116,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1633,"time":1783421532116,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1634,"time":1783421532116,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"验证"}}} -{"type":"assistant/chunk","seq":1635,"time":1783421532145,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":" f"}}} -{"type":"assistant/chunk","seq":1636,"time":1783421532145,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1637,"time":1783421532145,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1638,"time":1783421532145,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"已"}}} -{"type":"assistant/chunk","seq":1639,"time":1783421532173,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":1640,"time":1783421532174,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1641,"time":1783421532201,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1642,"time":1783421532201,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1643,"time":1783421532201,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":1644,"time":1783421532201,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1645,"time":1783421532230,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1646,"time":1783421532230,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1647,"time":1783421532231,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"ls"}}} -{"type":"assistant/chunk","seq":1648,"time":1783421532231,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":" -"}}} -{"type":"assistant/chunk","seq":1649,"time":1783421532276,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"la"}}} -{"type":"assistant/chunk","seq":1650,"time":1783421532276,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":" ~"}}} -{"type":"assistant/chunk","seq":1651,"time":1783421532277,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":1652,"time":1783421532277,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"f"}}} -{"type":"assistant/chunk","seq":1653,"time":1783421532277,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1654,"time":1783421532287,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1655,"time":1783421532288,"data":{"turn":7,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":1656,"time":1783421532350,"data":{"turn":7,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"执行成功,验证一下。"}}}} -{"type":"assistant/chunk","seq":1657,"time":1783421532351,"data":{"turn":7,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","arguments":"{\"description\": \"验证 f.md 已创建\", \"command\": \"ls -la ~/f.md\"}"}}}} -{"type":"assistant/chunk","seq":1658,"time":1783421532351,"data":{"turn":7,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":110,"outputTokens":76,"cacheReadTokens":3200,"reasoningTokens":6}}}} -{"type":"assistant/chunk","seq":1659,"time":1783421532351,"data":{"turn":7,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":1660,"time":1783421532351,"data":{"turn":7,"step":2,"content":[{"type":"reasoning","text":"执行成功,验证一下。"},{"type":"tool-call","id":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","arguments":"{\"description\": \"验证 f.md 已创建\", \"command\": \"ls -la ~/f.md\"}"}],"usage":{"inputTokens":110,"outputTokens":76,"cacheReadTokens":3200,"reasoningTokens":6}},"sourceEventSeqs":[1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1632,1633,1634,1635,1636,1637,1638,1639,1640,1641,1642,1643,1644,1645,1646,1647,1648,1649,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659],"surfaceOp":"append"} -{"type":"tool/call","seq":1661,"time":1783421532351,"data":{"turn":7,"step":2,"callId":"call_00_DHMK4ps74aFQdaCeYLCo9195","name":"bash","arguments":"{\"description\": \"验证 f.md 已创建\", \"command\": \"ls -la ~/f.md\"}"}} -{"type":"tool/result","seq":1662,"time":1783421532438,"data":{"turn":7,"step":2,"callId":"call_00_DHMK4ps74aFQdaCeYLCo9195","content":[{"type":"text","text":"-rw-r--r--@ 1 wwl staff 0 Jul 7 18:52 /Users/wwl/f.md\n"}],"isError":false},"sourceEventSeqs":[1661],"surfaceOp":"append"} -{"type":"step/end","seq":1663,"time":1783421532439,"data":{"turn":7,"step":2}} -{"type":"step/start","seq":1664,"time":1783421532439,"data":{"turn":7,"step":3}} -{"type":"assistant/chunk","seq":1665,"time":1783421533104,"data":{"turn":7,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":1666,"time":1783421533104,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"成功"}}} -{"type":"assistant/chunk","seq":1667,"time":1783421533247,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1668,"time":1783421533279,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"了"}}} -{"type":"assistant/chunk","seq":1669,"time":1783421533279,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" f"}}} -{"type":"assistant/chunk","seq":1670,"time":1783421533308,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1671,"time":1783421533309,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1672,"time":1783421533339,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"在"}}} -{"type":"assistant/chunk","seq":1673,"time":1783421533339,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" home"}}} -{"type":"assistant/chunk","seq":1674,"time":1783421533369,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1675,"time":1783421533369,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1676,"time":1783421533369,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":1677,"time":1783421533369,"data":{"turn":7,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1678,"time":1783421533369,"data":{"turn":7,"step":3,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":1679,"time":1783421533369,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1680,"time":1783421533397,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"f"}}} -{"type":"assistant/chunk","seq":1681,"time":1783421533397,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":1682,"time":1783421533397,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1683,"time":1783421533397,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1684,"time":1783421533397,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"已"}}} -{"type":"assistant/chunk","seq":1685,"time":1783421533398,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"成功"}}} -{"type":"assistant/chunk","seq":1686,"time":1783421533427,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":1687,"time":1783421533456,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"在"}}} -{"type":"assistant/chunk","seq":1688,"time":1783421533456,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":" home"}}} -{"type":"assistant/chunk","seq":1689,"time":1783421533487,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1690,"time":1783421533487,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":1691,"time":1783421533487,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":" (`"}}} -{"type":"assistant/chunk","seq":1692,"time":1783421533487,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1693,"time":1783421533514,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"Users"}}} -{"type":"assistant/chunk","seq":1694,"time":1783421533514,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1695,"time":1783421533514,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"ww"}}} -{"type":"assistant/chunk","seq":1696,"time":1783421533514,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"l"}}} -{"type":"assistant/chunk","seq":1697,"time":1783421533514,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"/f"}}} -{"type":"assistant/chunk","seq":1698,"time":1783421533514,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":1699,"time":1783421533547,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"`)"}}} -{"type":"assistant/chunk","seq":1700,"time":1783421533547,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"!\n\n"}}} -{"type":"assistant/chunk","seq":1701,"time":1783421533547,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"顺便"}}} -{"type":"assistant/chunk","seq":1702,"time":1783421533575,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"提"}}} -{"type":"assistant/chunk","seq":1703,"time":1783421533605,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"一下"}}} -{"type":"assistant/chunk","seq":1704,"time":1783421533605,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":1705,"time":1783421533605,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"之前"}}} -{"type":"assistant/chunk","seq":1706,"time":1783421533605,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"未"}}} -{"type":"assistant/chunk","seq":1707,"time":1783421533638,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"成功的"}}} -{"type":"assistant/chunk","seq":1708,"time":1783421533638,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":1709,"time":1783421533638,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"e"}}} -{"type":"assistant/chunk","seq":1710,"time":1783421533638,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":1711,"time":1783421533638,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1712,"time":1783421533638,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1713,"time":1783421533661,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"是否需要"}}} -{"type":"assistant/chunk","seq":1714,"time":1783421533661,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"一并"}}} -{"type":"assistant/chunk","seq":1715,"time":1783421533689,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"补"}}} -{"type":"assistant/chunk","seq":1716,"time":1783421533718,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"上"}}} -{"type":"assistant/chunk","seq":1717,"time":1783421533718,"data":{"turn":7,"step":3,"chunk":{"type":"text-delta","index":1,"text":"?"}}} -{"type":"assistant/chunk","seq":1718,"time":1783421533720,"data":{"turn":7,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"成功创建了 f.md 在 home 目录下。"}}}} -{"type":"assistant/chunk","seq":1719,"time":1783421533720,"data":{"turn":7,"step":3,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"`f.md` 已成功创建在 home 目录 (`/Users/wwl/f.md`)!\n\n顺便提一下,之前未成功的 `e.md` 是否需要一并补上?"}}}} -{"type":"assistant/chunk","seq":1720,"time":1783421533720,"data":{"turn":7,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":99,"outputTokens":52,"cacheReadTokens":3328,"reasoningTokens":12}}}} -{"type":"assistant/chunk","seq":1721,"time":1783421533720,"data":{"turn":7,"step":3,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":1722,"time":1783421533720,"data":{"turn":7,"step":3,"content":[{"type":"reasoning","text":"成功创建了 f.md 在 home 目录下。"},{"type":"text","text":"`f.md` 已成功创建在 home 目录 (`/Users/wwl/f.md`)!\n\n顺便提一下,之前未成功的 `e.md` 是否需要一并补上?"}],"usage":{"inputTokens":99,"outputTokens":52,"cacheReadTokens":3328,"reasoningTokens":12}},"sourceEventSeqs":[1665,1666,1667,1668,1669,1670,1671,1672,1673,1674,1675,1676,1677,1678,1679,1680,1681,1682,1683,1684,1685,1686,1687,1688,1689,1690,1691,1692,1693,1694,1695,1696,1697,1698,1699,1700,1701,1702,1703,1704,1705,1706,1707,1708,1709,1710,1711,1712,1713,1714,1715,1716,1717,1718,1719,1720,1721],"surfaceOp":"append"} -{"type":"step/end","seq":1723,"time":1783421533720,"data":{"turn":7,"step":3}} -{"type":"turn/end","seq":1724,"time":1783421533720,"data":{"turn":7,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":1725,"time":1783421537087,"data":{"turn":8,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":1726,"time":1783421537087,"data":{"content":[{"type":"text","text":"帮我在 ~ 创建一个 g.md"}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"step/start","seq":1727,"time":1783421537087,"data":{"turn":8,"step":1}} -{"type":"assistant/chunk","seq":1728,"time":1783421537603,"data":{"turn":8,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":1729,"time":1783421537603,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":1730,"time":1783421537727,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"想在"}}} -{"type":"assistant/chunk","seq":1731,"time":1783421537756,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" home"}}} -{"type":"assistant/chunk","seq":1732,"time":1783421537757,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1733,"time":1783421537757,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1734,"time":1783421537757,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1735,"time":1783421537785,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" g"}}} -{"type":"assistant/chunk","seq":1736,"time":1783421537786,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1737,"time":1783421537786,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1738,"time":1783421537786,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"之前"}}} -{"type":"assistant/chunk","seq":1739,"time":1783421537815,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"申请"}}} -{"type":"assistant/chunk","seq":1740,"time":1783421537844,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" danger"}}} -{"type":"assistant/chunk","seq":1741,"time":1783421537844,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-full"}}} -{"type":"assistant/chunk","seq":1742,"time":1783421537874,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-access"}}} -{"type":"assistant/chunk","seq":1743,"time":1783421537874,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1744,"time":1783421537874,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"被"}}} -{"type":"assistant/chunk","seq":1745,"time":1783421537903,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"批准"}}} -{"type":"assistant/chunk","seq":1746,"time":1783421537903,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"了"}}} -{"type":"assistant/chunk","seq":1747,"time":1783421537903,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":1748,"time":1783421537903,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"这次"}}} -{"type":"assistant/chunk","seq":1749,"time":1783421537933,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"应该"}}} -{"type":"assistant/chunk","seq":1750,"time":1783421537933,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"也可以"}}} -{"type":"assistant/chunk","seq":1751,"time":1783421537973,"data":{"turn":8,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1752,"time":1783421538049,"data":{"turn":8,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":1753,"time":1783421538049,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":1754,"time":1783421538078,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":1755,"time":1783421538078,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1756,"time":1783421538078,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":1757,"time":1783421538078,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1758,"time":1783421538078,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1759,"time":1783421538107,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1760,"time":1783421538108,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"touch"}}} -{"type":"assistant/chunk","seq":1761,"time":1783421538108,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" ~"}}} -{"type":"assistant/chunk","seq":1762,"time":1783421538108,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":1763,"time":1783421538108,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"g"}}} -{"type":"assistant/chunk","seq":1764,"time":1783421538136,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1765,"time":1783421538137,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" &&"}}} -{"type":"assistant/chunk","seq":1766,"time":1783421538165,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" ls"}}} -{"type":"assistant/chunk","seq":1767,"time":1783421538165,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" -"}}} -{"type":"assistant/chunk","seq":1768,"time":1783421538165,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"la"}}} -{"type":"assistant/chunk","seq":1769,"time":1783421538194,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" ~"}}} -{"type":"assistant/chunk","seq":1770,"time":1783421538195,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":1771,"time":1783421538195,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"g"}}} -{"type":"assistant/chunk","seq":1772,"time":1783421538195,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1773,"time":1783421538195,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1774,"time":1783421538257,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1775,"time":1783421538257,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1776,"time":1783421538257,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":1777,"time":1783421538257,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1778,"time":1783421538257,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1779,"time":1783421538285,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1780,"time":1783421538285,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"在"}}} -{"type":"assistant/chunk","seq":1781,"time":1783421538285,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" home"}}} -{"type":"assistant/chunk","seq":1782,"time":1783421538286,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1783,"time":1783421538286,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":1784,"time":1783421538286,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":1785,"time":1783421538315,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" g"}}} -{"type":"assistant/chunk","seq":1786,"time":1783421538315,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1787,"time":1783421538315,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1788,"time":1783421538344,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1789,"time":1783421538344,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1790,"time":1783421538344,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"sand"}}} -{"type":"assistant/chunk","seq":1791,"time":1783421538373,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"box"}}} -{"type":"assistant/chunk","seq":1792,"time":1783421538373,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"_per"}}} -{"type":"assistant/chunk","seq":1793,"time":1783421538373,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"missions"}}} -{"type":"assistant/chunk","seq":1794,"time":1783421538373,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1795,"time":1783421538373,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1796,"time":1783421538403,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1797,"time":1783421538403,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"danger"}}} -{"type":"assistant/chunk","seq":1798,"time":1783421538403,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"-full"}}} -{"type":"assistant/chunk","seq":1799,"time":1783421538403,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"-access"}}} -{"type":"assistant/chunk","seq":1800,"time":1783421538432,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1801,"time":1783421538461,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":1802,"time":1783421538461,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1803,"time":1783421538461,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"just"}}} -{"type":"assistant/chunk","seq":1804,"time":1783421538461,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"ification"}}} -{"type":"assistant/chunk","seq":1805,"time":1783421538461,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1806,"time":1783421538461,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1807,"time":1783421538490,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1808,"time":1783421538490,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"用户"}}} -{"type":"assistant/chunk","seq":1809,"time":1783421538519,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"要求在"}}} -{"type":"assistant/chunk","seq":1810,"time":1783421538520,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" home"}}} -{"type":"assistant/chunk","seq":1811,"time":1783421538520,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1812,"time":1783421538520,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":1813,"time":1783421538520,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"下"}}} -{"type":"assistant/chunk","seq":1814,"time":1783421538549,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":1815,"time":1783421538549,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" g"}}} -{"type":"assistant/chunk","seq":1816,"time":1783421538549,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":1817,"time":1783421538549,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":1818,"time":1783421538549,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"文件"}}} -{"type":"assistant/chunk","seq":1819,"time":1783421538549,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":","}}} -{"type":"assistant/chunk","seq":1820,"time":1783421538579,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"需要"}}} -{"type":"assistant/chunk","seq":1821,"time":1783421538579,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"完全"}}} -{"type":"assistant/chunk","seq":1822,"time":1783421538580,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"访问"}}} -{"type":"assistant/chunk","seq":1823,"time":1783421538580,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"权限"}}} -{"type":"assistant/chunk","seq":1824,"time":1783421538608,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"。"}}} -{"type":"assistant/chunk","seq":1825,"time":1783421538608,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1826,"time":1783421538608,"data":{"turn":8,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":1827,"time":1783421538670,"data":{"turn":8,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"用户想在 home 目录创建 g.md。之前申请 danger-full-access 被批准了,这次应该也可以。"}}}} -{"type":"assistant/chunk","seq":1828,"time":1783421538671,"data":{"turn":8,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","arguments":"{\"command\": \"touch ~/g.md && ls -la ~/g.md\", \"description\": \"在 home 目录创建 g.md\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"用户要求在 home 目录下创建 g.md 文件,需要完全访问权限。\"}"}}}} -{"type":"assistant/chunk","seq":1829,"time":1783421538671,"data":{"turn":8,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":150,"outputTokens":153,"cacheReadTokens":3328,"reasoningTokens":23}}}} -{"type":"assistant/chunk","seq":1830,"time":1783421538671,"data":{"turn":8,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":1831,"time":1783421538671,"data":{"turn":8,"step":1,"content":[{"type":"reasoning","text":"用户想在 home 目录创建 g.md。之前申请 danger-full-access 被批准了,这次应该也可以。"},{"type":"tool-call","id":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","arguments":"{\"command\": \"touch ~/g.md && ls -la ~/g.md\", \"description\": \"在 home 目录创建 g.md\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"用户要求在 home 目录下创建 g.md 文件,需要完全访问权限。\"}"}],"usage":{"inputTokens":150,"outputTokens":153,"cacheReadTokens":3328,"reasoningTokens":23}},"sourceEventSeqs":[1728,1729,1730,1731,1732,1733,1734,1735,1736,1737,1738,1739,1740,1741,1742,1743,1744,1745,1746,1747,1748,1749,1750,1751,1752,1753,1754,1755,1756,1757,1758,1759,1760,1761,1762,1763,1764,1765,1766,1767,1768,1769,1770,1771,1772,1773,1774,1775,1776,1777,1778,1779,1780,1781,1782,1783,1784,1785,1786,1787,1788,1789,1790,1791,1792,1793,1794,1795,1796,1797,1798,1799,1800,1801,1802,1803,1804,1805,1806,1807,1808,1809,1810,1811,1812,1813,1814,1815,1816,1817,1818,1819,1820,1821,1822,1823,1824,1825,1826,1827,1828,1829,1830],"surfaceOp":"append"} -{"type":"tool/call","seq":1832,"time":1783421538671,"data":{"turn":8,"step":1,"callId":"call_00_sv6ejgH8uXxp9Iy508TO6253","name":"bash","arguments":"{\"command\": \"touch ~/g.md && ls -la ~/g.md\", \"description\": \"在 home 目录创建 g.md\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"用户要求在 home 目录下创建 g.md 文件,需要完全访问权限。\"}"}} -{"type":"approval/asked","seq":1833,"time":1783421538671,"data":{"id":"c972f0f7-5b2b-4d52-9d33-b3318ff0d81a","toolName":"bash","callId":"call_00_sv6ejgH8uXxp9Iy508TO6253","reason":"escalate sandbox to danger-full-access: 用户要求在 home 目录下创建 g.md 文件,需要完全访问权限。"}} -{"type":"approval/decided","seq":1834,"time":1783421539711,"data":{"id":"c972f0f7-5b2b-4d52-9d33-b3318ff0d81a","outcome":"rejected"}} -{"type":"tool/result","seq":1835,"time":1783421539711,"data":{"turn":8,"step":1,"callId":"call_00_sv6ejgH8uXxp9Iy508TO6253","content":[{"type":"text","text":"Error: the user rejected escalating this command to \"danger-full-access\""}],"isError":true},"sourceEventSeqs":[1832],"surfaceOp":"append"} -{"type":"step/end","seq":1836,"time":1783421539711,"data":{"turn":8,"step":1}} -{"type":"step/start","seq":1837,"time":1783421539711,"data":{"turn":8,"step":2}} -{"type":"assistant/chunk","seq":1838,"time":1783421540359,"data":{"turn":8,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":1839,"time":1783421540359,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":1840,"time":1783421540460,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"拒绝了"}}} -{"type":"assistant/chunk","seq":1841,"time":1783421540485,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1842,"time":1783421540521,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"那"}}} -{"type":"assistant/chunk","seq":1843,"time":1783421540546,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"我在"}}} -{"type":"assistant/chunk","seq":1844,"time":1783421540602,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" workspace"}}} -{"type":"assistant/chunk","seq":1845,"time":1783421540604,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-w"}}} -{"type":"assistant/chunk","seq":1846,"time":1783421540604,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"rite"}}} -{"type":"assistant/chunk","seq":1847,"time":1783421540605,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1848,"time":1783421540605,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"范围内"}}} -{"type":"assistant/chunk","seq":1849,"time":1783421540633,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"能"}}} -{"type":"assistant/chunk","seq":1850,"time":1783421540662,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"做什么"}}} -{"type":"assistant/chunk","seq":1851,"time":1783421540691,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"呢"}}} -{"type":"assistant/chunk","seq":1852,"time":1783421540691,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"?"}}} -{"type":"assistant/chunk","seq":1853,"time":1783421540691,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"works"}}} -{"type":"assistant/chunk","seq":1854,"time":1783421540720,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"pace"}}} -{"type":"assistant/chunk","seq":1855,"time":1783421540720,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-w"}}} -{"type":"assistant/chunk","seq":1856,"time":1783421540720,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"rite"}}} -{"type":"assistant/chunk","seq":1857,"time":1783421540720,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1858,"time":1783421540720,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"只"}}} -{"type":"assistant/chunk","seq":1859,"time":1783421540748,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"允许"}}} -{"type":"assistant/chunk","seq":1860,"time":1783421540748,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"在工作"}}} -{"type":"assistant/chunk","seq":1861,"time":1783421540785,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1862,"time":1783421540785,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":1863,"time":1783421540785,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"写入"}}} -{"type":"assistant/chunk","seq":1864,"time":1783421540806,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1865,"time":1783421540806,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"所以"}}} -{"type":"assistant/chunk","seq":1866,"time":1783421540835,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"我可以"}}} -{"type":"assistant/chunk","seq":1867,"time":1783421540835,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"问"}}} -{"type":"assistant/chunk","seq":1868,"time":1783421540864,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":1869,"time":1783421540864,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"是否"}}} -{"type":"assistant/chunk","seq":1870,"time":1783421540908,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"要在"}}} -{"type":"assistant/chunk","seq":1871,"time":1783421540922,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"工作"}}} -{"type":"assistant/chunk","seq":1872,"time":1783421540922,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1873,"time":1783421540922,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":1874,"time":1783421540922,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1875,"time":1783421540922,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" g"}}} -{"type":"assistant/chunk","seq":1876,"time":1783421540951,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1877,"time":1783421540951,"data":{"turn":8,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1878,"time":1783421540951,"data":{"turn":8,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":1879,"time":1783421540951,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"权限"}}} -{"type":"assistant/chunk","seq":1880,"time":1783421540980,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"申请"}}} -{"type":"assistant/chunk","seq":1881,"time":1783421541009,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"被"}}} -{"type":"assistant/chunk","seq":1882,"time":1783421541009,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"拒绝了"}}} -{"type":"assistant/chunk","seq":1883,"time":1783421541009,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":1884,"time":1783421541009,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"我"}}} -{"type":"assistant/chunk","seq":1885,"time":1783421541037,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"无法"}}} -{"type":"assistant/chunk","seq":1886,"time":1783421541037,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"在"}}} -{"type":"assistant/chunk","seq":1887,"time":1783421541037,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":" home"}}} -{"type":"assistant/chunk","seq":1888,"time":1783421541067,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1889,"time":1783421541068,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":1890,"time":1783421541068,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"下"}}} -{"type":"assistant/chunk","seq":1891,"time":1783421541068,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":1892,"time":1783421541068,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":1893,"time":1783421541068,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"g"}}} -{"type":"assistant/chunk","seq":1894,"time":1783421541098,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":1895,"time":1783421541098,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1896,"time":1783421541098,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"。\n\n"}}} -{"type":"assistant/chunk","seq":1897,"time":1783421541098,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"如果你"}}} -{"type":"assistant/chunk","seq":1898,"time":1783421541127,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"愿意"}}} -{"type":"assistant/chunk","seq":1899,"time":1783421541165,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":1900,"time":1783421541165,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"我可以"}}} -{"type":"assistant/chunk","seq":1901,"time":1783421541165,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"把"}}} -{"type":"assistant/chunk","seq":1902,"time":1783421541185,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":1903,"time":1783421541185,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"g"}}} -{"type":"assistant/chunk","seq":1904,"time":1783421541185,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":1905,"time":1783421541185,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":1906,"time":1783421541185,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1907,"time":1783421541185,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":1908,"time":1783421541214,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"到"}}} -{"type":"assistant/chunk","seq":1909,"time":1783421541214,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"当前"}}} -{"type":"assistant/chunk","seq":1910,"time":1783421541214,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":1911,"time":1783421541242,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"工作"}}} -{"type":"assistant/chunk","seq":1912,"time":1783421541242,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":1913,"time":1783421541242,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":1914,"time":1783421541242,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":" (`"}}} -{"type":"assistant/chunk","seq":1915,"time":1783421541272,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1916,"time":1783421541272,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"Users"}}} -{"type":"assistant/chunk","seq":1917,"time":1783421541272,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1918,"time":1783421541272,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ww"}}} -{"type":"assistant/chunk","seq":1919,"time":1783421541311,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"l"}}} -{"type":"assistant/chunk","seq":1920,"time":1783421541311,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1921,"time":1783421541311,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"works"}}} -{"type":"assistant/chunk","seq":1922,"time":1783421541311,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"pace"}}} -{"type":"assistant/chunk","seq":1923,"time":1783421541311,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"/de"}}} -{"type":"assistant/chunk","seq":1924,"time":1783421541311,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ep"}}} -{"type":"assistant/chunk","seq":1925,"time":1783421541329,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"seek"}}} -{"type":"assistant/chunk","seq":1926,"time":1783421541329,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"-h"}}} -{"type":"assistant/chunk","seq":1927,"time":1783421541329,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ar"}}} -{"type":"assistant/chunk","seq":1928,"time":1783421541329,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ness"}}} -{"type":"assistant/chunk","seq":1929,"time":1783421541329,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"/"}}} -{"type":"assistant/chunk","seq":1930,"time":1783421541329,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`)"}}} -{"type":"assistant/chunk","seq":1931,"time":1783421541358,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":1932,"time":1783421541358,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"下"}}} -{"type":"assistant/chunk","seq":1933,"time":1783421541358,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":1934,"time":1783421541358,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"需要"}}} -{"type":"assistant/chunk","seq":1935,"time":1783421541387,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"吗"}}} -{"type":"assistant/chunk","seq":1936,"time":1783421541387,"data":{"turn":8,"step":2,"chunk":{"type":"text-delta","index":1,"text":"?"}}} -{"type":"assistant/chunk","seq":1937,"time":1783421541387,"data":{"turn":8,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"用户拒绝了。那我在 workspace-write 范围内能做什么呢?workspace-write 只允许在工作目录下写入。所以我可以问用户是否要在工作目录下创建 g.md。"}}}} -{"type":"assistant/chunk","seq":1938,"time":1783421541388,"data":{"turn":8,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"权限申请被拒绝了,我无法在 home 目录下创建 `g.md`。\n\n如果你愿意,我可以把 `g.md` 创建到当前**工作目录** (`/Users/wwl/workspace/deepseek-harness/`) 下,需要吗?"}}}} -{"type":"assistant/chunk","seq":1939,"time":1783421541388,"data":{"turn":8,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":73,"outputTokens":98,"cacheReadTokens":3584,"reasoningTokens":39}}}} -{"type":"assistant/chunk","seq":1940,"time":1783421541388,"data":{"turn":8,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":1941,"time":1783421541388,"data":{"turn":8,"step":2,"content":[{"type":"reasoning","text":"用户拒绝了。那我在 workspace-write 范围内能做什么呢?workspace-write 只允许在工作目录下写入。所以我可以问用户是否要在工作目录下创建 g.md。"},{"type":"text","text":"权限申请被拒绝了,我无法在 home 目录下创建 `g.md`。\n\n如果你愿意,我可以把 `g.md` 创建到当前**工作目录** (`/Users/wwl/workspace/deepseek-harness/`) 下,需要吗?"}],"usage":{"inputTokens":73,"outputTokens":98,"cacheReadTokens":3584,"reasoningTokens":39}},"sourceEventSeqs":[1838,1839,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1867,1868,1869,1870,1871,1872,1873,1874,1875,1876,1877,1878,1879,1880,1881,1882,1883,1884,1885,1886,1887,1888,1889,1890,1891,1892,1893,1894,1895,1896,1897,1898,1899,1900,1901,1902,1903,1904,1905,1906,1907,1908,1909,1910,1911,1912,1913,1914,1915,1916,1917,1918,1919,1920,1921,1922,1923,1924,1925,1926,1927,1928,1929,1930,1931,1932,1933,1934,1935,1936,1937,1938,1939,1940],"surfaceOp":"append"} -{"type":"step/end","seq":1942,"time":1783421541388,"data":{"turn":8,"step":2}} -{"type":"turn/end","seq":1943,"time":1783421541388,"data":{"turn":8,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":1944,"time":1783421552564,"data":{"turn":9,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"bash/sandbox-mode","seq":1945,"time":1783421552564,"data":{"mode":"danger-full-access"}} -{"type":"user/message","seq":1946,"time":1783421552564,"data":{"content":[{"type":"text","text":"创建一个 h.md"}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"user/message","seq":1947,"time":1783421552564,"data":{"content":[{"type":"text","text":"The bash sandbox mode changed from \"workspace-write\" to \"danger-full-access\" (changed by the user)."}],"source":{"kind":"plugin","plugin":"tool-bash"}},"surfaceOp":"append"} -{"type":"step/start","seq":1948,"time":1783421552564,"data":{"turn":9,"step":1}} -{"type":"request/header-delta","seq":1949,"time":1783421552564,"data":{"system":{"keepStart":12,"keepEnd":0,"insert":["Bash commands run under the \"danger-full-access\" file sandbox."]}}} -{"type":"assistant/chunk","seq":1950,"time":1783421553289,"data":{"turn":9,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":1951,"time":1783421553290,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"现在"}}} -{"type":"assistant/chunk","seq":1952,"time":1783421553399,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"沙"}}} -{"type":"assistant/chunk","seq":1953,"time":1783421553429,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"盒"}}} -{"type":"assistant/chunk","seq":1954,"time":1783421553429,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"模式"}}} -{"type":"assistant/chunk","seq":1955,"time":1783421553429,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"已经是"}}} -{"type":"assistant/chunk","seq":1956,"time":1783421553429,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" danger"}}} -{"type":"assistant/chunk","seq":1957,"time":1783421553429,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-full"}}} -{"type":"assistant/chunk","seq":1958,"time":1783421553458,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-access"}}} -{"type":"assistant/chunk","seq":1959,"time":1783421553458,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":1960,"time":1783421553458,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"了"}}} -{"type":"assistant/chunk","seq":1961,"time":1783421553458,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":1962,"time":1783421553458,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"可以直接"}}} -{"type":"assistant/chunk","seq":1963,"time":1783421553490,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"在工作"}}} -{"type":"assistant/chunk","seq":1964,"time":1783421553491,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"目录"}}} -{"type":"assistant/chunk","seq":1965,"time":1783421553520,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"下"}}} -{"type":"assistant/chunk","seq":1966,"time":1783421553521,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":1967,"time":1783421553542,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" h"}}} -{"type":"assistant/chunk","seq":1968,"time":1783421553571,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":1969,"time":1783421553571,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":1970,"time":1783421553571,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"无需"}}} -{"type":"assistant/chunk","seq":1971,"time":1783421553571,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"再次"}}} -{"type":"assistant/chunk","seq":1972,"time":1783421553600,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"申请"}}} -{"type":"assistant/chunk","seq":1973,"time":1783421553600,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"权限"}}} -{"type":"assistant/chunk","seq":1974,"time":1783421553600,"data":{"turn":9,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":1975,"time":1783421553685,"data":{"turn":9,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":1976,"time":1783421553685,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":1977,"time":1783421553713,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":1978,"time":1783421553714,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1979,"time":1783421553714,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":1980,"time":1783421553714,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1981,"time":1783421553714,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":1982,"time":1783421553742,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":1983,"time":1783421553743,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"touch"}}} -{"type":"assistant/chunk","seq":1984,"time":1783421553743,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":1985,"time":1783421553743,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"Users"}}} -{"type":"assistant/chunk","seq":1986,"time":1783421553743,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":1987,"time":1783421553775,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"ww"}}} -{"type":"assistant/chunk","seq":1988,"time":1783421553775,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"l"}}} -{"type":"assistant/chunk","seq":1989,"time":1783421553775,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":1990,"time":1783421553775,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":1991,"time":1783421553775,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":1992,"time":1783421553776,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"/de"}}} -{"type":"assistant/chunk","seq":1993,"time":1783421553803,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"ep"}}} -{"type":"assistant/chunk","seq":1994,"time":1783421553803,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"seek"}}} -{"type":"assistant/chunk","seq":1995,"time":1783421553803,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"-h"}}} -{"type":"assistant/chunk","seq":1996,"time":1783421553803,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"ar"}}} -{"type":"assistant/chunk","seq":1997,"time":1783421553803,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"ness"}}} -{"type":"assistant/chunk","seq":1998,"time":1783421553803,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"/h"}}} -{"type":"assistant/chunk","seq":1999,"time":1783421553831,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":2000,"time":1783421553831,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":" &&"}}} -{"type":"assistant/chunk","seq":2001,"time":1783421553832,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":" ls"}}} -{"type":"assistant/chunk","seq":2002,"time":1783421553832,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":" -"}}} -{"type":"assistant/chunk","seq":2003,"time":1783421553832,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"la"}}} -{"type":"assistant/chunk","seq":2004,"time":1783421553832,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":2005,"time":1783421553859,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"Users"}}} -{"type":"assistant/chunk","seq":2006,"time":1783421553859,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":2007,"time":1783421553859,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"ww"}}} -{"type":"assistant/chunk","seq":2008,"time":1783421553859,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"l"}}} -{"type":"assistant/chunk","seq":2009,"time":1783421553859,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"/"}}} -{"type":"assistant/chunk","seq":2010,"time":1783421553859,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"works"}}} -{"type":"assistant/chunk","seq":2011,"time":1783421553887,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"pace"}}} -{"type":"assistant/chunk","seq":2012,"time":1783421553887,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"/de"}}} -{"type":"assistant/chunk","seq":2013,"time":1783421553887,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"ep"}}} -{"type":"assistant/chunk","seq":2014,"time":1783421553887,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"seek"}}} -{"type":"assistant/chunk","seq":2015,"time":1783421553887,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"-h"}}} -{"type":"assistant/chunk","seq":2016,"time":1783421553888,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"ar"}}} -{"type":"assistant/chunk","seq":2017,"time":1783421553916,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"ness"}}} -{"type":"assistant/chunk","seq":2018,"time":1783421553916,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"/h"}}} -{"type":"assistant/chunk","seq":2019,"time":1783421553916,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":2020,"time":1783421553916,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":2021,"time":1783421553946,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":2022,"time":1783421553946,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":2023,"time":1783421553972,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":2024,"time":1783421553972,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":2025,"time":1783421553972,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":2026,"time":1783421553973,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":2027,"time":1783421554001,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"在工作"}}} -{"type":"assistant/chunk","seq":2028,"time":1783421554001,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"目录"}}} -{"type":"assistant/chunk","seq":2029,"time":1783421554001,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"创建"}}} -{"type":"assistant/chunk","seq":2030,"time":1783421554030,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":" h"}}} -{"type":"assistant/chunk","seq":2031,"time":1783421554030,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":2032,"time":1783421554030,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":2033,"time":1783421554058,"data":{"turn":9,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":2034,"time":1783421554089,"data":{"turn":9,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"现在沙盒模式已经是 danger-full-access 了,可以直接在工作目录下创建 h.md,无需再次申请权限。"}}}} -{"type":"assistant/chunk","seq":2035,"time":1783421554089,"data":{"turn":9,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/h.md && ls -la /Users/wwl/workspace/deepseek-harness/h.md\", \"description\": \"在工作目录创建 h.md\"}"}}}} -{"type":"assistant/chunk","seq":2036,"time":1783421554089,"data":{"turn":9,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3757,"outputTokens":123,"cacheReadTokens":0,"reasoningTokens":24}}}} -{"type":"assistant/chunk","seq":2037,"time":1783421554089,"data":{"turn":9,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":2038,"time":1783421554090,"data":{"turn":9,"step":1,"content":[{"type":"reasoning","text":"现在沙盒模式已经是 danger-full-access 了,可以直接在工作目录下创建 h.md,无需再次申请权限。"},{"type":"tool-call","id":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/h.md && ls -la /Users/wwl/workspace/deepseek-harness/h.md\", \"description\": \"在工作目录创建 h.md\"}"}],"usage":{"inputTokens":3757,"outputTokens":123,"cacheReadTokens":0,"reasoningTokens":24}},"sourceEventSeqs":[1950,1951,1952,1953,1954,1955,1956,1957,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030,2031,2032,2033,2034,2035,2036,2037],"surfaceOp":"append"} -{"type":"tool/call","seq":2039,"time":1783421554090,"data":{"turn":9,"step":1,"callId":"call_00_GhMY0hUKjd1feclqlu6E0395","name":"bash","arguments":"{\"command\": \"touch /Users/wwl/workspace/deepseek-harness/h.md && ls -la /Users/wwl/workspace/deepseek-harness/h.md\", \"description\": \"在工作目录创建 h.md\"}"}} -{"type":"tool/result","seq":2040,"time":1783421554171,"data":{"turn":9,"step":1,"callId":"call_00_GhMY0hUKjd1feclqlu6E0395","content":[{"type":"text","text":"-rw-r--r--@ 1 wwl staff 0 Jul 7 18:52 /Users/wwl/workspace/deepseek-harness/h.md\n"}],"isError":false},"sourceEventSeqs":[2039],"surfaceOp":"append"} -{"type":"step/end","seq":2041,"time":1783421554171,"data":{"turn":9,"step":1}} -{"type":"step/start","seq":2042,"time":1783421554172,"data":{"turn":9,"step":2}} -{"type":"assistant/chunk","seq":2043,"time":1783421554559,"data":{"turn":9,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":2044,"time":1783421554560,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"创建"}}} -{"type":"assistant/chunk","seq":2045,"time":1783421554661,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"成功"}}} -{"type":"assistant/chunk","seq":2046,"time":1783421554694,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":2047,"time":1783421554694,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"既然"}}} -{"type":"assistant/chunk","seq":2048,"time":1783421554718,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"现在是"}}} -{"type":"assistant/chunk","seq":2049,"time":1783421554746,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" danger"}}} -{"type":"assistant/chunk","seq":2050,"time":1783421554746,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-full"}}} -{"type":"assistant/chunk","seq":2051,"time":1783421554746,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-access"}}} -{"type":"assistant/chunk","seq":2052,"time":1783421554746,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":2053,"time":1783421554746,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"模式"}}} -{"type":"assistant/chunk","seq":2054,"time":1783421554746,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":2055,"time":1783421554774,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"我可以"}}} -{"type":"assistant/chunk","seq":2056,"time":1783421554774,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"顺便"}}} -{"type":"assistant/chunk","seq":2057,"time":1783421554802,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"问"}}} -{"type":"assistant/chunk","seq":2058,"time":1783421554831,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"一下"}}} -{"type":"assistant/chunk","seq":2059,"time":1783421554831,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"用户"}}} -{"type":"assistant/chunk","seq":2060,"time":1783421554831,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"是否"}}} -{"type":"assistant/chunk","seq":2061,"time":1783421554860,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"要"}}} -{"type":"assistant/chunk","seq":2062,"time":1783421554888,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"补"}}} -{"type":"assistant/chunk","seq":2063,"time":1783421554888,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"上"}}} -{"type":"assistant/chunk","seq":2064,"time":1783421554888,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"之前"}}} -{"type":"assistant/chunk","seq":2065,"time":1783421554921,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"没"}}} -{"type":"assistant/chunk","seq":2066,"time":1783421554921,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"成功的"}}} -{"type":"assistant/chunk","seq":2067,"time":1783421554948,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" b"}}} -{"type":"assistant/chunk","seq":2068,"time":1783421554948,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":2069,"time":1783421554948,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"、"}}} -{"type":"assistant/chunk","seq":2070,"time":1783421554977,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"c"}}} -{"type":"assistant/chunk","seq":2071,"time":1783421554977,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":2072,"time":1783421554977,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"、"}}} -{"type":"assistant/chunk","seq":2073,"time":1783421555005,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"e"}}} -{"type":"assistant/chunk","seq":2074,"time":1783421555005,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":2075,"time":1783421555005,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":2076,"time":1783421555005,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"和"}}} -{"type":"assistant/chunk","seq":2077,"time":1783421555034,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" g"}}} -{"type":"assistant/chunk","seq":2078,"time":1783421555034,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":".md"}}} -{"type":"assistant/chunk","seq":2079,"time":1783421555034,"data":{"turn":9,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"。"}}} -{"type":"assistant/chunk","seq":2080,"time":1783421555034,"data":{"turn":9,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":2081,"time":1783421555034,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":2082,"time":1783421555034,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"h"}}} -{"type":"assistant/chunk","seq":2083,"time":1783421555063,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":2084,"time":1783421555063,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":2085,"time":1783421555063,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2086,"time":1783421555063,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"已"}}} -{"type":"assistant/chunk","seq":2087,"time":1783421555063,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"成功"}}} -{"type":"assistant/chunk","seq":2088,"time":1783421555063,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":2089,"time":1783421555091,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"!"}}} -{"type":"assistant/chunk","seq":2090,"time":1783421555120,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"现在"}}} -{"type":"assistant/chunk","seq":2091,"time":1783421555120,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"权限"}}} -{"type":"assistant/chunk","seq":2092,"time":1783421555148,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"已"}}} -{"type":"assistant/chunk","seq":2093,"time":1783421555176,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"提升"}}} -{"type":"assistant/chunk","seq":2094,"time":1783421555204,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"为"}}} -{"type":"assistant/chunk","seq":2095,"time":1783421555204,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":2096,"time":1783421555205,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"danger"}}} -{"type":"assistant/chunk","seq":2097,"time":1783421555205,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"-full"}}} -{"type":"assistant/chunk","seq":2098,"time":1783421555205,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"-access"}}} -{"type":"assistant/chunk","seq":2099,"time":1783421555233,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":2100,"time":1783421555233,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":2101,"time":1783421555233,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"我可以"}}} -{"type":"assistant/chunk","seq":2102,"time":1783421555262,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"自由"}}} -{"type":"assistant/chunk","seq":2103,"time":1783421555290,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"读写"}}} -{"type":"assistant/chunk","seq":2104,"time":1783421555319,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"任何"}}} -{"type":"assistant/chunk","seq":2105,"time":1783421555347,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"位置"}}} -{"type":"assistant/chunk","seq":2106,"time":1783421555347,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"了"}}} -{"type":"assistant/chunk","seq":2107,"time":1783421555377,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"。\n\n"}}} -{"type":"assistant/chunk","seq":2108,"time":1783421555377,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"需要"}}} -{"type":"assistant/chunk","seq":2109,"time":1783421555377,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"我"}}} -{"type":"assistant/chunk","seq":2110,"time":1783421555406,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"帮你"}}} -{"type":"assistant/chunk","seq":2111,"time":1783421555406,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"把"}}} -{"type":"assistant/chunk","seq":2112,"time":1783421555432,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"之前"}}} -{"type":"assistant/chunk","seq":2113,"time":1783421555432,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"遗漏"}}} -{"type":"assistant/chunk","seq":2114,"time":1783421555461,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"的"}}} -{"type":"assistant/chunk","seq":2115,"time":1783421555461,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"也"}}} -{"type":"assistant/chunk","seq":2116,"time":1783421555492,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"一并"}}} -{"type":"assistant/chunk","seq":2117,"time":1783421555493,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"补"}}} -{"type":"assistant/chunk","seq":2118,"time":1783421555493,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"上"}}} -{"type":"assistant/chunk","seq":2119,"time":1783421555493,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"吗"}}} -{"type":"assistant/chunk","seq":2120,"time":1783421555524,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"?\n\n"}}} -{"type":"assistant/chunk","seq":2121,"time":1783421555524,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"|"}}} -{"type":"assistant/chunk","seq":2122,"time":1783421555550,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2123,"time":1783421555550,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"文件"}}} -{"type":"assistant/chunk","seq":2124,"time":1783421555550,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2125,"time":1783421555550,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2126,"time":1783421555550,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"位置"}}} -{"type":"assistant/chunk","seq":2127,"time":1783421555579,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2128,"time":1783421555579,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2129,"time":1783421555579,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"状态"}}} -{"type":"assistant/chunk","seq":2130,"time":1783421555579,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |\n"}}} -{"type":"assistant/chunk","seq":2131,"time":1783421555579,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"|"}}} -{"type":"assistant/chunk","seq":2132,"time":1783421555579,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"------"}}} -{"type":"assistant/chunk","seq":2133,"time":1783421555607,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"|"}}} -{"type":"assistant/chunk","seq":2134,"time":1783421555608,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"------"}}} -{"type":"assistant/chunk","seq":2135,"time":1783421555608,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"|"}}} -{"type":"assistant/chunk","seq":2136,"time":1783421555608,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"------"}}} -{"type":"assistant/chunk","seq":2137,"time":1783421555608,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"|\n"}}} -{"type":"assistant/chunk","seq":2138,"time":1783421555608,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"|"}}} -{"type":"assistant/chunk","seq":2139,"time":1783421555636,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":2140,"time":1783421555636,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"b"}}} -{"type":"assistant/chunk","seq":2141,"time":1783421555636,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":2142,"time":1783421555636,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":2143,"time":1783421555636,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2144,"time":1783421555636,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2145,"time":1783421555664,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"工作"}}} -{"type":"assistant/chunk","seq":2146,"time":1783421555664,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":2147,"time":1783421555664,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2148,"time":1783421555664,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" ❌"}}} -{"type":"assistant/chunk","seq":2149,"time":1783421555664,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2150,"time":1783421555700,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"未"}}} -{"type":"assistant/chunk","seq":2151,"time":1783421555700,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":2152,"time":1783421555700,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |\n"}}} -{"type":"assistant/chunk","seq":2153,"time":1783421555700,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"|"}}} -{"type":"assistant/chunk","seq":2154,"time":1783421555700,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":2155,"time":1783421555700,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"c"}}} -{"type":"assistant/chunk","seq":2156,"time":1783421555729,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":2157,"time":1783421555729,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":2158,"time":1783421555729,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2159,"time":1783421555729,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2160,"time":1783421555729,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"工作"}}} -{"type":"assistant/chunk","seq":2161,"time":1783421555729,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":2162,"time":1783421555752,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2163,"time":1783421555752,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" ❌"}}} -{"type":"assistant/chunk","seq":2164,"time":1783421555752,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2165,"time":1783421555752,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"未"}}} -{"type":"assistant/chunk","seq":2166,"time":1783421555752,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":2167,"time":1783421555787,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |\n"}}} -{"type":"assistant/chunk","seq":2168,"time":1783421555787,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"|"}}} -{"type":"assistant/chunk","seq":2169,"time":1783421555787,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":2170,"time":1783421555787,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"e"}}} -{"type":"assistant/chunk","seq":2171,"time":1783421555787,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":2172,"time":1783421555787,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":2173,"time":1783421555808,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2174,"time":1783421555808,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" home"}}} -{"type":"assistant/chunk","seq":2175,"time":1783421555808,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2176,"time":1783421555808,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":2177,"time":1783421555808,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2178,"time":1783421555836,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" ❌"}}} -{"type":"assistant/chunk","seq":2179,"time":1783421555836,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2180,"time":1783421555836,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"未"}}} -{"type":"assistant/chunk","seq":2181,"time":1783421555836,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":2182,"time":1783421555837,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |\n"}}} -{"type":"assistant/chunk","seq":2183,"time":1783421555837,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"|"}}} -{"type":"assistant/chunk","seq":2184,"time":1783421555869,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":2185,"time":1783421555869,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"g"}}} -{"type":"assistant/chunk","seq":2186,"time":1783421555869,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":".md"}}} -{"type":"assistant/chunk","seq":2187,"time":1783421555869,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":2188,"time":1783421555869,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2189,"time":1783421555869,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" home"}}} -{"type":"assistant/chunk","seq":2190,"time":1783421555905,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2191,"time":1783421555905,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"目录"}}} -{"type":"assistant/chunk","seq":2192,"time":1783421555905,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |"}}} -{"type":"assistant/chunk","seq":2193,"time":1783421555905,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" ❌"}}} -{"type":"assistant/chunk","seq":2194,"time":1783421555905,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":2195,"time":1783421555930,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"未"}}} -{"type":"assistant/chunk","seq":2196,"time":1783421555930,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"创建"}}} -{"type":"assistant/chunk","seq":2197,"time":1783421555930,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":" |\n\n"}}} -{"type":"assistant/chunk","seq":2198,"time":1783421555930,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"要"}}} -{"type":"assistant/chunk","seq":2199,"time":1783421555965,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"一口气"}}} -{"type":"assistant/chunk","seq":2200,"time":1783421555977,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"全"}}} -{"type":"assistant/chunk","seq":2201,"time":1783421556008,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"搞定"}}} -{"type":"assistant/chunk","seq":2202,"time":1783421556008,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"吗"}}} -{"type":"assistant/chunk","seq":2203,"time":1783421556008,"data":{"turn":9,"step":2,"chunk":{"type":"text-delta","index":1,"text":"?"}}} -{"type":"assistant/chunk","seq":2204,"time":1783421556009,"data":{"turn":9,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"创建成功。既然现在是 danger-full-access 模式,我可以顺便问一下用户是否要补上之前没成功的 b.md、c.md、e.md 和 g.md。"}}}} -{"type":"assistant/chunk","seq":2205,"time":1783421556009,"data":{"turn":9,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"`h.md` 已成功创建!现在权限已提升为 `danger-full-access`,我可以自由读写任何位置了。\n\n需要我帮你把之前遗漏的也一并补上吗?\n\n| 文件 | 位置 | 状态 |\n|------|------|------|\n| `b.md` | 工作目录 | ❌ 未创建 |\n| `c.md` | 工作目录 | ❌ 未创建 |\n| `e.md` | home 目录 | ❌ 未创建 |\n| `g.md` | home 目录 | ❌ 未创建 |\n\n要一口气全搞定吗?"}}}} -{"type":"assistant/chunk","seq":2206,"time":1783421556009,"data":{"turn":9,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":90,"outputTokens":164,"cacheReadTokens":3840,"reasoningTokens":36}}}} -{"type":"assistant/chunk","seq":2207,"time":1783421556009,"data":{"turn":9,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":2208,"time":1783421556009,"data":{"turn":9,"step":2,"content":[{"type":"reasoning","text":"创建成功。既然现在是 danger-full-access 模式,我可以顺便问一下用户是否要补上之前没成功的 b.md、c.md、e.md 和 g.md。"},{"type":"text","text":"`h.md` 已成功创建!现在权限已提升为 `danger-full-access`,我可以自由读写任何位置了。\n\n需要我帮你把之前遗漏的也一并补上吗?\n\n| 文件 | 位置 | 状态 |\n|------|------|------|\n| `b.md` | 工作目录 | ❌ 未创建 |\n| `c.md` | 工作目录 | ❌ 未创建 |\n| `e.md` | home 目录 | ❌ 未创建 |\n| `g.md` | home 目录 | ❌ 未创建 |\n\n要一口气全搞定吗?"}],"usage":{"inputTokens":90,"outputTokens":164,"cacheReadTokens":3840,"reasoningTokens":36}},"sourceEventSeqs":[2043,2044,2045,2046,2047,2048,2049,2050,2051,2052,2053,2054,2055,2056,2057,2058,2059,2060,2061,2062,2063,2064,2065,2066,2067,2068,2069,2070,2071,2072,2073,2074,2075,2076,2077,2078,2079,2080,2081,2082,2083,2084,2085,2086,2087,2088,2089,2090,2091,2092,2093,2094,2095,2096,2097,2098,2099,2100,2101,2102,2103,2104,2105,2106,2107,2108,2109,2110,2111,2112,2113,2114,2115,2116,2117,2118,2119,2120,2121,2122,2123,2124,2125,2126,2127,2128,2129,2130,2131,2132,2133,2134,2135,2136,2137,2138,2139,2140,2141,2142,2143,2144,2145,2146,2147,2148,2149,2150,2151,2152,2153,2154,2155,2156,2157,2158,2159,2160,2161,2162,2163,2164,2165,2166,2167,2168,2169,2170,2171,2172,2173,2174,2175,2176,2177,2178,2179,2180,2181,2182,2183,2184,2185,2186,2187,2188,2189,2190,2191,2192,2193,2194,2195,2196,2197,2198,2199,2200,2201,2202,2203,2204,2205,2206,2207],"surfaceOp":"append"} -{"type":"step/end","seq":2209,"time":1783421556009,"data":{"turn":9,"step":2}} -{"type":"turn/end","seq":2210,"time":1783421556009,"data":{"turn":9,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/goal-snapshots/goal-session/input.json b/examples/acp-agent/tests/goal-snapshots/goal-session/input.json index 93392c9e0f..563e3bd1c6 100644 --- a/examples/acp-agent/tests/goal-snapshots/goal-session/input.json +++ b/examples/acp-agent/tests/goal-snapshots/goal-session/input.json @@ -5,8 +5,9 @@ { "op": "promptAndWaitForAgentMessage", "text": "Create a durable two-round goal for the ACP snapshot, inspect it, then report readiness.", - "waitForText": "partial" + "waitForText": "GOAL ROUND ONE" }, - { "op": "cancel" } + { "op": "waitForTurnStart", "minimumTurn": 3 }, + { "op": "cancel", "waitForFile": { "path": ".dsh-snapshot-goal-cancel-ready" } } ] } diff --git a/examples/acp-agent/tests/goal-snapshots/goal-session/replay.override.json b/examples/acp-agent/tests/goal-snapshots/goal-session/replay.override.json index b0c5c0f28f..4f5c06fee6 100644 --- a/examples/acp-agent/tests/goal-snapshots/goal-session/replay.override.json +++ b/examples/acp-agent/tests/goal-snapshots/goal-session/replay.override.json @@ -39,5 +39,5 @@ { "type": "finish", "reason": { "kind": "stop" } } ] }, - { "kind": "hang" } + { "kind": "hang", "readyFile": ".dsh-snapshot-goal-cancel-ready" } ] diff --git a/examples/acp-agent/tests/goal-snapshots/goal-session/stdout.expected.jsonl b/examples/acp-agent/tests/goal-snapshots/goal-session/stdout.expected.jsonl index 48965f6b4f..9a54cb88c8 100644 --- a/examples/acp-agent/tests/goal-snapshots/goal-session/stdout.expected.jsonl +++ b/examples/acp-agent/tests/goal-snapshots/goal-session/stdout.expected.jsonl @@ -1,12 +1,5 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Create a durable two-round goal","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_goal_create","title":"Create goal","kind":"other","status":"in_progress","rawInput":"Finish the ACP goal-session snapshot proof"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_goal_create","status":"completed","content":[{"type":"content","content":{"type":"text","text":"{\"goal\":{\"id\":\"goal-{{sessionId}}\",\"revision\":1,\"objective\":\"Finish the ACP goal-session snapshot proof\",\"phase\":\"active\",\"roundsStarted\":0,\"maxGoalRounds\":2},\"activation\":\"armed\"}"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_goal_get","title":"Read current goal","kind":"read","status":"in_progress"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_goal_get","status":"completed","content":[{"type":"content","content":{"type":"text","text":"{\"goal\":{\"id\":\"goal-{{sessionId}}\",\"revision\":1,\"objective\":\"Finish the ACP goal-session snapshot proof\",\"phase\":\"active\",\"roundsStarted\":0,\"maxGoalRounds\":2},\"activation\":\"armed\"}"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"GOAL READY"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"GOAL ROUND ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"partial"}}}} diff --git a/examples/acp-agent/tests/goal.snapshot.ts b/examples/acp-agent/tests/goal.snapshot.ts index 23359f9982..b6a44cb66c 100644 --- a/examples/acp-agent/tests/goal.snapshot.ts +++ b/examples/acp-agent/tests/goal.snapshot.ts @@ -15,7 +15,7 @@ import type { SessionEvent } from '@deepseek-ai/dsh-session' import { describe, expect, it } from 'vitest' // This lifecycle proof has goal-specific timestamp normalization and semantic -// assertions, so it owns a separate snapshot root from the generic ACP suite. +// assertions, so it owns a separate snapshot root from the generic suite. const scenarioDir = join(dirname(fileURLToPath(import.meta.url)), 'goal-snapshots/goal-session') const fixtureFile = join(scenarioDir, 'session.jsonl') const overrideFile = join(scenarioDir, 'replay.override.json') @@ -63,7 +63,7 @@ function normalizeGoalLog(content: string, context: NormalizeContext): string { .join('\n') + '\n' } -describe('ACP same-session goal snapshot', () => { +describe('same-session goal snapshot through the ACP automation driver', () => { it('runs exact automatic rounds in the shipped application and persists cancellation', async () => { const input = JSON.parse(await readFile(join(scenarioDir, 'input.json'), 'utf8')) as InputScript const result = await runScenario(input, { @@ -77,7 +77,7 @@ describe('ACP same-session goal snapshot', () => { expect(result.stderr).toBe('') expect(result.sessionLogs).toHaveLength(1) const log = result.sessionLogs[0] - if (log === undefined) throw new Error('goal snapshot did not persist its ACP session') + if (log === undefined) throw new Error('goal snapshot did not persist its session') const records = parseJsonl(log.content) const events = records.slice(1) as unknown as SessionEvent[] const calls = events.filter(event => event.type === 'tool/call').map(event => event.data.name) diff --git a/examples/acp-agent/tests/hooks.e2e.ts b/examples/acp-agent/tests/hooks.e2e.ts index 528823f3c5..49669e6b9b 100644 --- a/examples/acp-agent/tests/hooks.e2e.ts +++ b/examples/acp-agent/tests/hooks.e2e.ts @@ -65,8 +65,8 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('acp-agent e2e: a PreToolUse hook // Verify that the denied hook left no filesystem effect. await expect(access(join(workdir, 'proof.txt'))).rejects.toThrow() - // A blocked call is still streamed with the hook's reason as an error. - const toolCalls = updates.filter(u => u.sessionUpdate === 'tool_call' || u.sessionUpdate === 'tool_call_update') - expect(toolCalls.length).toBeGreaterThan(0) + // ACP publishes only the committed answer; hook/tool trace stays in the session log. + expect(updates.length).toBeGreaterThan(0) + expect(updates.every(update => update.sessionUpdate === 'agent_message_chunk')).toBe(true) }, 180_000) }) diff --git a/examples/acp-agent/tests/plan-mode.e2e.ts b/examples/acp-agent/tests/plan-mode.e2e.ts deleted file mode 100644 index 31cfc804f5..0000000000 --- a/examples/acp-agent/tests/plan-mode.e2e.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { afterEach, describe, expect, it } from 'vitest' -import { - PROTOCOL_VERSION, - type CreateElicitationRequest, - type CreateElicitationResponse, -} from '@agentclientprotocol/sdk' -import { - launchAcpTestAgent, - type AgentUnderTest, - type LaunchedAcpTestAgent, -} from '@deepseek-ai/dsh-acp-snapshot' - -/** The shipped ACP leaf's plan mode exercised through its real subprocess entry. */ -const AGENT: AgentUnderTest = { - binScript: fileURLToPath(new URL('../../../packages/examples/acp-demo/src/bin.ts', import.meta.url)), - configPath: fileURLToPath(new URL('../cordis.yml', import.meta.url)), - tsconfigPath: fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)), -} - -let spawned: LaunchedAcpTestAgent | undefined -let workdir: string | undefined - -afterEach(async () => { - const ownedSpawned = spawned - const ownedWorkdir = workdir - spawned = undefined - workdir = undefined - try { - if (ownedSpawned !== undefined) { - await ownedSpawned.close('SIGKILL').catch((error: unknown) => { - throw new Error(`plan ACP cleanup failed; child stderr:\n${ownedSpawned.stderr()}`, { cause: error }) - }) - } - } finally { - if (ownedWorkdir !== undefined) await rm(ownedWorkdir, { recursive: true, force: true }) - } -}) - -describe.skipIf(!process.env.DEEPSEEK_API_KEY)('acp-agent plan mode e2e: approval gates implementation (real model)', () => { - it('keeps the file unchanged through review, then applies the approved plan', async () => { - workdir = await mkdtemp(join(tmpdir(), 'acp-plan-e2e-')) - const proofPath = join(workdir, 'proof.txt') - await writeFile(proofPath, 'BEFORE\n') - - const reviews: CreateElicitationRequest[] = [] - let contentAtReview: string | undefined - const createElicitation = async (request: CreateElicitationRequest): Promise<CreateElicitationResponse> => { - if (request.mode !== 'form' || request.requestedSchema.title !== 'Plan review') return { action: 'cancel' } - reviews.push(request) - contentAtReview = await readFile(proofPath, 'utf8') - return { action: 'accept', content: { choice: 'Approve' } } - } - - spawned = launchAcpTestAgent({ agent: AGENT, cwd: workdir, createElicitation }) - const { client, updates } = spawned - const rpc = async <T>(stage: string, operation: Promise<T>): Promise<T> => operation.catch((error: unknown) => { - throw new Error(`plan ACP ${stage} failed; child stderr:\n${spawned?.stderr() ?? '<unavailable>'}`, { cause: error }) - }) - await rpc('initialize', client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })) - const created = await rpc('session/new', client.newSession({ cwd: workdir, mcpServers: [] })) - expect(created.modes?.availableModes.map(mode => mode.id)).toEqual(['default', 'plan']) - await rpc('session/set_mode', client.setSessionMode({ sessionId: created.sessionId, modeId: 'plan' })) - - const result = await rpc('prompt', client.prompt({ - sessionId: created.sessionId, - prompt: [{ - type: 'text', - text: 'Inspect proof.txt and plan the smallest change that replaces its contents with exactly AFTER followed by one newline. Present the complete plan through exit_plan_mode. After I approve it, implement the change with the filesystem tools, verify the exact file contents, and stop. Do not ask questions.', - }], - })) - - expect(['end_turn', 'max_tokens']).toContain(result.stopReason) - expect(reviews).toHaveLength(1) - expect(contentAtReview).toBe('BEFORE\n') - expect(await readFile(proofPath, 'utf8')).toBe('AFTER\n') - expect(updates - .filter(update => update.sessionUpdate === 'current_mode_update') - .map(update => update.currentModeId)).toEqual(['plan', 'default']) - }, 240_000) -}) diff --git a/examples/acp-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/stdout.expected.jsonl b/examples/acp-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/stdout.expected.jsonl deleted file mode 100644 index 96896d268a..0000000000 --- a/examples/acp-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/stdout.expected.jsonl +++ /dev/null @@ -1,9 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"Perform one side-effecting remote mutation."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"unknown-outcome-call","title":"write_remote","kind":"other","status":"in_progress","rawInput":{"value":1}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"unknown-outcome-call","status":"failed","content":[{"type":"content","content":{"type":"text","text":"The tool call was interrupted after it was recorded, but no result was durably recorded. Its outcome is unknown. Decide whether to retry from the tool semantics: retry only if the operation is read-only or idempotent; if it may have side effects, first verify external state or ask the user. Do not retry blindly."}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","id":2,"result":{"modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Perform one side-effecting remote mutati","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I will verify the external state before deciding whether to retry the side-effecting operation."}}}} -{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/semantic-checkpoint.snapshot.ts b/examples/acp-agent/tests/semantic-checkpoint.snapshot.ts deleted file mode 100644 index e43d2ca4d0..0000000000 --- a/examples/acp-agent/tests/semantic-checkpoint.snapshot.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { Context } from 'cordis' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { - launchAcpTestAgent, - normalizeSessionLog, - normalizeStdout, - scrubRequestHeaders, - type AgentUnderTest, - type NormalizeContext, -} from '@deepseek-ai/dsh-acp-snapshot' -import { CallId } from '@deepseek-ai/dsh-llm' -import SessionStore, { SESSION_FORMAT_VERSION, SessionId, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session' -import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' -import { describe, expect, it } from 'vitest' - -const fixtureDir = join(dirname(fileURLToPath(import.meta.url)), 'semantic-checkpoint-snapshots/tool-outcome-unknown') -const replayFixture = join(fixtureDir, 'replay.jsonl') -const replayOverride = join(fixtureDir, 'replay.override.json') -const stdoutExpected = join(fixtureDir, 'stdout.expected.jsonl') -const sessionExpected = join(fixtureDir, 'session.expected.jsonl') -const sessionId = SessionId('semantic-checkpoint-unknown-outcome') -const refreshing = process.env.DSH_SNAPSHOT === 'refresh' - -const agent: AgentUnderTest = { - binScript: fileURLToPath(new URL('../../../packages/examples/acp-demo/src/bin.ts', import.meta.url)), - configPath: fileURLToPath(new URL('../cordis.yml', import.meta.url)), - tsconfigPath: fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)), -} - -async function seedInterruptedSession(root: string, cwd: string): Promise<string> { - const ctx = new Context() - await ctx.plugin(SessionStore) - await ctx.plugin(SessionPersistenceJsonl, { root, compression: 'none' }) - const meta: SessionHeader = { - version: SESSION_FORMAT_VERSION, - id: sessionId, - createdAt: 1, - cwd, - delegationDepth: 0, - } - const events: SessionEvent[] = [ - { type: 'turn/start', seq: 0, time: 10, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }, - { type: 'user/message', seq: 1, time: 11, data: { content: [{ type: 'text', text: 'Perform one side-effecting remote mutation.' }], source: { kind: 'user' } }, surfaceOp: 'append' }, - { type: 'step/start', seq: 2, time: 12, data: { turn: 1, step: 1 } }, - { - type: 'assistant/message', - seq: 3, - time: 13, - data: { - turn: 1, - step: 1, - content: [{ type: 'tool-call', id: CallId('unknown-outcome-call'), name: 'write_remote', arguments: '{"value":1}' }], - provenance: { provider: 'deepseek', model: 'deepseek-v4-flash' }, - }, - surfaceOp: 'append', - }, - { - type: 'tool/call', - seq: 4, - time: 14, - data: { - turn: 1, - step: 1, - callId: CallId('unknown-outcome-call'), - name: 'write_remote', - arguments: '{"value":1}', - }, - }, - ] - try { - await ctx.sessionPersistence.create(meta) - await ctx.sessionPersistence.append(sessionId, events) - const location = ctx.sessionPersistence.locate(meta) - if (location === undefined) throw new Error('JSONL backend did not locate the seeded session') - return location.path - } finally { - await ctx.fiber.dispose() - } -} - -describe('semantic checkpoint recovery snapshot', () => { - it('loads an unknown tool outcome and carries retry-risk guidance into the next model turn', async () => { - const cwd = await mkdtemp(join(tmpdir(), 'dsh-semantic-snapshot-cwd-')) - const sessionsRoot = await mkdtemp(join(tmpdir(), 'dsh-semantic-snapshot-sessions-')) - let launched: ReturnType<typeof launchAcpTestAgent> | undefined - try { - const sessionPath = await seedInterruptedSession(sessionsRoot, cwd) - launched = launchAcpTestAgent({ - agent, - cwd, - env: { - DSH_SNAPSHOT: 'replay', - DSH_SNAPSHOT_FILE: replayFixture, - DSH_SNAPSHOT_OVERRIDE: replayOverride, - DSH_SNAPSHOT_SESSIONS_ROOT: sessionsRoot, - }, - }) - await launched.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await launched.client.loadSession({ sessionId, cwd, mcpServers: [] }) - await launched.client.prompt({ - sessionId, - prompt: [{ type: 'text', text: 'Continue safely from the interrupted operation.' }], - }) - await launched.close() - - const normalization: NormalizeContext = { sessionIds: [sessionId], cwd } - const stdout = normalizeStdout(launched.rawStdout(), normalization) - const session = scrubRequestHeaders(normalizeSessionLog(await readFile(sessionPath, 'utf8'), normalization)) - if (refreshing) { - await writeFile(stdoutExpected, stdout) - await writeFile(sessionExpected, session) - } - expect(stdout).toBe(await readFile(stdoutExpected, 'utf8')) - expect(session).toBe(await readFile(sessionExpected, 'utf8')) - expect(session).toContain('TOOL_OUTCOME_UNKNOWN') - expect(session).toContain('Do not retry blindly.') - } finally { - await launched?.close('SIGKILL').catch(() => undefined) - await Promise.all([ - rm(cwd, { recursive: true, force: true }), - rm(sessionsRoot, { recursive: true, force: true }), - ]) - } - }) -}) diff --git a/examples/acp-agent/tests/snapshots/advanced-toolchain/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/advanced-toolchain/stdout.expected.jsonl index 7c0fe5cd9c..9ba3346933 100644 --- a/examples/acp-agent/tests/snapshots/advanced-toolchain/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/advanced-toolchain/stdout.expected.jsonl @@ -1,16 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Run this advanced flow exactly","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"advanced-mount","title":"Mount plugin into live cordis runtime","kind":"execute","status":"in_progress","rawInput":{"code":"return { name: 'snapshot-marker', apply() {} }"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"advanced-mount","status":"completed","content":[{"type":"content","content":{"type":"text","text":"mounted dyn-1 (plugin \"snapshot-marker\", state: active)"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"advanced-code","title":"return await tools.cordis_inspect({ what: 'dynamic' })","kind":"execute","status":"in_progress","rawInput":"return await tools.cordis_inspect({ what: 'dynamic' })"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"advanced-code","status":"completed","content":[{"type":"content","content":{"type":"text","text":"## dynamic\n- dyn-1: snapshot-marker [active]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"advanced-direct-child","title":"subagent","kind":"other","status":"in_progress","rawInput":{"description":"Check direct child","prompt":"Reply with exactly DIRECT_CHILD_OK and nothing else."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"advanced-direct-child","status":"completed","content":[{"type":"content","content":{"type":"text","text":"DIRECT_CHILD_OK"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"advanced-workflow","title":"workflow: advanced-acp-snapshot","kind":"other","status":"in_progress","rawInput":"phase('Delegate')\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\nreturn { reply }"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"advanced-workflow","status":"completed","content":[{"type":"content","content":{"type":"text","text":"workflow \"advanced-acp-snapshot\" completed (1 agent).\nReturn value:\n{\n \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"advanced-unmount","title":"Unmount dyn-1","kind":"delete","status":"in_progress"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"advanced-unmount","status":"completed","content":[{"type":"content","content":{"type":"text","text":"unmounted dyn-1 (plugin \"snapshot-marker\")"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ADVANCED_ACP_OK"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md index 8fae73812d..d45a386c99 100644 --- a/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md @@ -41,27 +41,6 @@ The available tools: type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue } interface ToolArgsMap { - /** Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer. */ - ask_user_question: { - /** Questions to ask the user before continuing. */ - questions: ({ - /** Stable id for this question; echoed in the answer. */ - id: string; - /** The specific question to ask the user. */ - question: string; - /** Optional short heading for the question, such as "Confirm" or "Choose Mode". */ - header?: string; - /** Optional choices to show the user. If you recommend one, put it first and append "(Recommended)" to that label. */ - options?: ({ - /** Short user-facing option label. */ - label: string; - /** One sentence explaining the tradeoff or impact. */ - description?: string; - } & Record<string, JsonValue>)[]; - /** Whether the user may select more than one option. Defaults to false. */ - multi_select?: boolean; - } & Record<string, JsonValue>)[]; - } & Record<string, JsonValue>; /** Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later. */ bash: { /** The bash command to execute. */ @@ -118,11 +97,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. */ justification?: string; } & Record<string, JsonValue>; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record<string, JsonValue>; /** Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal. */ get_goal: Record<string, JsonValue>; /** Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools. */ @@ -319,13 +293,6 @@ interface ToolArgsMap { } interface ToolOutputMap { - ask_user_question: { - answers: { - id: string; - selected: string[]; - custom?: string; - }[]; - }; bash: { kind: "background"; taskId: string; @@ -387,9 +354,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json index a0ab8af765..bb239d8c2d 100644 --- a/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json @@ -1,68 +1,5 @@ { "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, { "name": "bash", "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", @@ -227,22 +164,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, { "name": "get_goal", "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", diff --git a/examples/acp-agent/tests/snapshots/bash-spill/session.jsonl b/examples/acp-agent/tests/snapshots/bash-spill/session.jsonl index eb4488858e..833ed36355 100644 --- a/examples/acp-agent/tests/snapshots/bash-spill/session.jsonl +++ b/examples/acp-agent/tests/snapshots/bash-spill/session.jsonl @@ -11,7 +11,7 @@ {"type":"assistant/chunk","seq":9,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":10,"time":0,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"call_spill","name":"bash","arguments":"{\"command\":\"node -e \\\"process.stdout.write('SPILL_START-' + 'x'.repeat(2000) + '-SPILL_END')\\\"\",\"description\":\"Print large deterministic output\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} {"type":"tool/call","seq":11,"time":0,"data":{"turn":1,"step":1,"callId":"call_spill","name":"bash","arguments":"{\"command\":\"node -e \\\"process.stdout.write('SPILL_START-' + 'x'.repeat(2000) + '-SPILL_END')\\\"\",\"description\":\"Print large deterministic output\"}"}} -{"type":"tool/result","seq":12,"time":0,"data":{"turn":1,"step":1,"callId":"call_spill","content":[{"type":"text","text":"SPILL_START-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-SPILL_END\n\n(Omitted 1417 bytes. Full formatted result stored at: /tmp/dsh-acp-snap-ee77dff02/session-fbfcf2f560a0/1bddd2b64176-bash.txt. Use read with offset/limit, or grep this path to search within it.)"}],"isError":false},"sourceEventSeqs":[11],"surfaceOp":"append"} +{"type":"tool/result","seq":12,"time":0,"data":{"turn":1,"step":1,"callId":"call_spill","content":[{"type":"text","text":"SPILL_START-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-SPILL_END\n\n(Omitted 1417 bytes. Full formatted result stored at: /tmp/dsh-acp-snap-ee77dff02/session-5747fa727e10/57c2f8c3fbf2-bash.txt. Use read with offset/limit, or grep this path to search within it.)"}],"isError":false},"sourceEventSeqs":[11],"surfaceOp":"append"} {"type":"step/end","seq":13,"time":0,"data":{"turn":1,"step":1}} {"type":"step/start","seq":14,"time":0,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":15,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} diff --git a/examples/acp-agent/tests/snapshots/bash-spill/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/bash-spill/stdout.expected.jsonl index 01a96948ba..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/bash-spill/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/bash-spill/stdout.expected.jsonl @@ -1,8 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_spill","title":"node -e \"process.stdout.write('SPILL_START-' + 'x'.repeat(2000) + '-SPILL_END')\"","kind":"execute","status":"in_progress","rawInput":"node -e \"process.stdout.write('SPILL_START-' + 'x'.repeat(2000) + '-SPILL_END')\"","content":[{"type":"content","content":{"type":"text","text":"Print large deterministic output"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nSPILL_START-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-SPILL_END\n\n(Omitted 1417 bytes. Full formatted result stored at: {{spillLocator:bash.txt}}. Use read with offset/limit, or grep this path to search within it.)\n```"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/fs-terminal-card/input.json b/examples/acp-agent/tests/snapshots/bash-tool-turn/input.json similarity index 77% rename from examples/acp-agent/tests/snapshots/fs-terminal-card/input.json rename to examples/acp-agent/tests/snapshots/bash-tool-turn/input.json index de9237ea82..086e8fa77c 100644 --- a/examples/acp-agent/tests/snapshots/fs-terminal-card/input.json +++ b/examples/acp-agent/tests/snapshots/bash-tool-turn/input.json @@ -1,6 +1,6 @@ { "steps": [ - { "op": "initialize", "terminalOutput": true }, + { "op": "initialize" }, { "op": "newSession" }, { "op": "prompt", "text": "Use the bash tool to run exactly: echo TERMINAL_OK. Then reply with the single word DONE and stop." } ] diff --git a/examples/acp-agent/tests/snapshots/fs-terminal-card/session.jsonl b/examples/acp-agent/tests/snapshots/bash-tool-turn/session.jsonl similarity index 100% rename from examples/acp-agent/tests/snapshots/fs-terminal-card/session.jsonl rename to examples/acp-agent/tests/snapshots/bash-tool-turn/session.jsonl diff --git a/examples/acp-agent/tests/snapshots/bash-tool-turn/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/bash-tool-turn/stdout.expected.jsonl new file mode 100644 index 0000000000..82ae8907ca --- /dev/null +++ b/examples/acp-agent/tests/snapshots/bash-tool-turn/stdout.expected.jsonl @@ -0,0 +1,4 @@ +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/both-mode-turn/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/both-mode-turn/stdout.expected.jsonl index 2fb72d7f0b..7b2bc6dff8 100644 --- a/examples/acp-agent/tests/snapshots/both-mode-turn/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/both-mode-turn/stdout.expected.jsonl @@ -1,64 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Call the run_code tool (NOT","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" execute"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" program"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" calls"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".b"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" B"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"OTH"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returns"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" its"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_AZFzvUwuC4vAUoICrfke5147","title":"const result = await tools.bash({ command: \"echo BOTH_OK\", description: \"Echo BOTH_OK\" });\nreturn result.stdout.text;","kind":"execute","status":"in_progress","rawInput":"const result = await tools.bash({ command: \"echo BOTH_OK\", description: \"Echo BOTH_OK\" });\nreturn result.stdout.text;"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_AZFzvUwuC4vAUoICrfke5147","status":"completed","content":[{"type":"content","content":{"type":"text","text":"BOTH_OK\n"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"B"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"OTH"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" only"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"B"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"OTH"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_OK"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"BOTH_OK"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md index 014455b3fd..b66bb0de0c 100644 --- a/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md @@ -41,27 +41,6 @@ The available tools: type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue } interface ToolArgsMap { - /** Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer. */ - ask_user_question: { - /** Questions to ask the user before continuing. */ - questions: ({ - /** Stable id for this question; echoed in the answer. */ - id: string; - /** The specific question to ask the user. */ - question: string; - /** Optional short heading for the question, such as "Confirm" or "Choose Mode". */ - header?: string; - /** Optional choices to show the user. If you recommend one, put it first and append "(Recommended)" to that label. */ - options?: ({ - /** Short user-facing option label. */ - label: string; - /** One sentence explaining the tradeoff or impact. */ - description?: string; - } & Record<string, JsonValue>)[]; - /** Whether the user may select more than one option. Defaults to false. */ - multi_select?: boolean; - } & Record<string, JsonValue>)[]; - } & Record<string, JsonValue>; /** Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later. */ bash: { /** The bash command to execute. */ @@ -101,11 +80,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. */ justification?: string; } & Record<string, JsonValue>; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record<string, JsonValue>; /** Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal. */ get_goal: Record<string, JsonValue>; /** Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools. */ @@ -302,13 +276,6 @@ interface ToolArgsMap { } interface ToolOutputMap { - ask_user_question: { - answers: { - id: string; - selected: string[]; - custom?: string; - }[]; - }; bash: { kind: "background"; taskId: string; @@ -358,9 +325,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json index 8626f46680..ac3323d626 100644 --- a/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json @@ -1,68 +1,5 @@ { "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, { "name": "bash", "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", @@ -170,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, { "name": "get_goal", "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", diff --git a/examples/acp-agent/tests/snapshots/cancel-tool-calls/input.json b/examples/acp-agent/tests/snapshots/cancel-tool-calls/input.json index 7024820966..3b54337fa4 100644 --- a/examples/acp-agent/tests/snapshots/cancel-tool-calls/input.json +++ b/examples/acp-agent/tests/snapshots/cancel-tool-calls/input.json @@ -5,9 +5,7 @@ { "op": "promptAndCancel", "text": "Run two shell commands: wait for cancellation, then write skipped.txt.", - "afterUpdate": "tool_call", - "waitForFile": { "path": "started.txt" }, - "waitForToolCallUpdate": "call_skipped" + "waitForFile": { "path": "started.txt" } }, { "op": "waitForTurnEnd" } ] diff --git a/examples/acp-agent/tests/snapshots/cancel-tool-calls/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/cancel-tool-calls/stdout.expected.jsonl index 6258693575..cb25d1c6bb 100644 --- a/examples/acp-agent/tests/snapshots/cancel-tool-calls/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/cancel-tool-calls/stdout.expected.jsonl @@ -1,9 +1,3 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Run two shell commands: wait","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_wait","title":"node -e \"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\"","kind":"execute","status":"in_progress","rawInput":"node -e \"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\"","content":[{"type":"content","content":{"type":"text","text":"Wait until cancellation"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"cancelled"}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_wait","status":"failed","content":[{"type":"content","content":{"type":"text","text":"```console\nError: command aborted\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_skipped","title":"printf skipped > skipped.txt","kind":"execute","status":"in_progress","rawInput":"printf skipped > skipped.txt","content":[{"type":"content","content":{"type":"text","text":"Write skipped marker"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_skipped","status":"failed","content":[{"type":"content","content":{"type":"text","text":"```console\nError: tool call aborted before dispatch\n```"}}]}}} diff --git a/examples/acp-agent/tests/snapshots/cancel/input.json b/examples/acp-agent/tests/snapshots/cancel/input.json index a2e2fdc5f0..a96b0418c3 100644 --- a/examples/acp-agent/tests/snapshots/cancel/input.json +++ b/examples/acp-agent/tests/snapshots/cancel/input.json @@ -2,7 +2,11 @@ "steps": [ { "op": "initialize" }, { "op": "newSession" }, - { "op": "promptAndCancel", "text": "Start a long task; this turn will be cancelled mid-stream." }, + { + "op": "promptAndCancel", + "text": "Start a long task; this turn will be cancelled mid-stream.", + "waitForFile": { "path": ".dsh-snapshot-stream-ready" } + }, { "op": "waitForTurnEnd" } ] } diff --git a/examples/acp-agent/tests/snapshots/cancel/replay.override.json b/examples/acp-agent/tests/snapshots/cancel/replay.override.json index 8436b9ca06..3114a72f41 100644 --- a/examples/acp-agent/tests/snapshots/cancel/replay.override.json +++ b/examples/acp-agent/tests/snapshots/cancel/replay.override.json @@ -1,3 +1,3 @@ [ - { "kind": "hang" } + { "kind": "hang", "readyFile": ".dsh-snapshot-stream-ready" } ] diff --git a/examples/acp-agent/tests/snapshots/cancel/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/cancel/stdout.expected.jsonl index c528122503..cb25d1c6bb 100644 --- a/examples/acp-agent/tests/snapshots/cancel/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/cancel/stdout.expected.jsonl @@ -1,6 +1,3 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Start a long task; this","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"partial"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"cancelled"}} diff --git a/examples/acp-agent/tests/snapshots/code-mode-turn/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/code-mode-turn/stdout.expected.jsonl index 85866dd6dc..9ca552c9fd 100644 --- a/examples/acp-agent/tests/snapshots/code-mode-turn/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/code-mode-turn/stdout.expected.jsonl @@ -1,572 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Using ONE run_code program: call","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" carefully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instructions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" write"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" program"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Calls"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" -"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Calls"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WO"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" -"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WO"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"3"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Inside"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" same"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" program"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" console"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".log"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"capt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ured"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"4"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Return"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" two"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" outputs"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" joined"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plus"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sign"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" look"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" at"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" signature"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" carefully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" parameter"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" execute"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" So"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'d"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" pass"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"But"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wait"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" -"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" be"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" careful"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" about"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" what"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" looks"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" like"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returns"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stdout"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"/st"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"derr"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" objects"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" check"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" type"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"```"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ts"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" {\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" kind"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"fore"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ground"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" |"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"background"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\";\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" //"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" if"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" foreground"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" number"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" |"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" null"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":";\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stdout"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" {"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" text"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" string"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":";"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" truncated"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" boolean"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":";"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" spill"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Path"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"?:"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" string"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":";"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" };\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" st"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"derr"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" {"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" text"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" string"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":";"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ..."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" };\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ...\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"}\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"```\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"So"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" extract"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"std"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"out"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".text"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" from"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" each"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" call"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" also"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" make"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sure"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" about"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"description"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" parameter"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" -"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" required"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" be"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"5"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"10"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" words"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" describing"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" write"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"```"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ts"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"const"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" r"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ="}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" await"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".b"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"({"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" description"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"E"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"cho"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stdout"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" });\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"const"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" r"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ="}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" await"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".b"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"({"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WO"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" description"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"E"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"cho"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WO"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stdout"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" });\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"console"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".log"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"(\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"capt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ured"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\");\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"return"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" r"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".stdout"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".text"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".trim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"()"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" +"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \"+"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" +"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" r"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".stdout"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".text"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".trim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"();\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"```\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" think"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" about"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" format"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" will"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" So"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"r"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".stdout"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".text"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" would"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" be"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" after"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" trim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`.\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"So"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" joined"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" string"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" would"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" be"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"+"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WO"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`.\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"And"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" console"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".log"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"(\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"capt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ured"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\")"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" prints"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"capt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ured"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" console"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" response"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" comes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" which"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" includes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stdout"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" return"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" value"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Since"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" return"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" value"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" what"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" we"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" want"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" joined"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" string"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" only"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" -"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" think"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" return"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" value"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" of"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" function"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" what"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" matters"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" But"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" console"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".log"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" also"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" comes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" write"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" see"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_9r18203KAw8KCXThwJ7k3704","title":"\nconst r1 = await tools.bash({ command: \"echo CODE_ONE\", description: \"Echo CODE_ONE to stdout\" });\nconst r2 = await tools.bash({ command: \"echo CODE_TWO\", description: \"Echo CODE_TWO to stdout\" });\nconsole.log(\"captured output\");\nreturn r1.stdout.text.trim() + \"+\" + r2.stdout.text.trim();\n","kind":"execute","status":"in_progress","rawInput":"\nconst r1 = await tools.bash({ command: \"echo CODE_ONE\", description: \"Echo CODE_ONE to stdout\" });\nconst r2 = await tools.bash({ command: \"echo CODE_TWO\", description: \"Echo CODE_TWO to stdout\" });\nconsole.log(\"captured output\");\nreturn r1.stdout.text.trim() + \"+\" + r2.stdout.text.trim();\n"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_9r18203KAw8KCXThwJ7k3704","status":"completed","content":[{"type":"content","content":{"type":"text","text":"captured output\nCODE_ONE+CODE_TWO"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" shows"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"capt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ured"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"from"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" console"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".log"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":")\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"+"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WO"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" return"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" value"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":")\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instructions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" say"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" joined"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" string"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" only"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" So"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"+"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WO"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"+"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"WO"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"CODE_ONE+CODE_TWO"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md index 014455b3fd..b66bb0de0c 100644 --- a/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md @@ -41,27 +41,6 @@ The available tools: type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue } interface ToolArgsMap { - /** Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer. */ - ask_user_question: { - /** Questions to ask the user before continuing. */ - questions: ({ - /** Stable id for this question; echoed in the answer. */ - id: string; - /** The specific question to ask the user. */ - question: string; - /** Optional short heading for the question, such as "Confirm" or "Choose Mode". */ - header?: string; - /** Optional choices to show the user. If you recommend one, put it first and append "(Recommended)" to that label. */ - options?: ({ - /** Short user-facing option label. */ - label: string; - /** One sentence explaining the tradeoff or impact. */ - description?: string; - } & Record<string, JsonValue>)[]; - /** Whether the user may select more than one option. Defaults to false. */ - multi_select?: boolean; - } & Record<string, JsonValue>)[]; - } & Record<string, JsonValue>; /** Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later. */ bash: { /** The bash command to execute. */ @@ -101,11 +80,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. */ justification?: string; } & Record<string, JsonValue>; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record<string, JsonValue>; /** Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal. */ get_goal: Record<string, JsonValue>; /** Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools. */ @@ -302,13 +276,6 @@ interface ToolArgsMap { } interface ToolOutputMap { - ask_user_question: { - answers: { - id: string; - selected: string[]; - custom?: string; - }[]; - }; bash: { kind: "background"; taskId: string; @@ -358,9 +325,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/stdout.expected.jsonl index c881517f8b..f9a0416af5 100644 --- a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/stdout.expected.jsonl @@ -1,139 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Using ONE run_code program, call","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" write"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" program"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reads"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" called"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" nested"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"/t"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ask"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" answer"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" hand"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"shake"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" question"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" based"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" on"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" what"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" start"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_6APApmaKLRDlXKMdIcWL5139","title":"const content = await tools.read({ file_path: \"nested/task.txt\" });\nreturn content.lines.map(line => line.text).join(String.fromCharCode(10));","kind":"execute","status":"in_progress","rawInput":"const content = await tools.read({ file_path: \"nested/task.txt\" });\nreturn content.lines.map(line => line.text).join(String.fromCharCode(10));"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_6APApmaKLRDlXKMdIcWL5139","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Touch this file to discover the nested workspace instruction."}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" nested"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"/t"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ask"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" told"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Touch"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" discover"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" nested"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" workspace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instruction"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" nested"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"/"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AG"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ENTS"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".md"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instructions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" say"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"When"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" asked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" for"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Mode"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" workspace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" hand"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"shake"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" answer"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_M"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_CONT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"EXT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" nothing"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" else"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"So"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" answer"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" hand"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"shake"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" question"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_M"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_CONT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"EXT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" **"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" Mode"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" workspace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" hand"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"shake"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"**"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"CODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_M"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ODE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_CONT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"EXT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"`"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The **Code Mode workspace handshake** is: `CODE_MODE_CONTEXT_OK`"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md index 014455b3fd..b66bb0de0c 100644 --- a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md @@ -41,27 +41,6 @@ The available tools: type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue } interface ToolArgsMap { - /** Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer. */ - ask_user_question: { - /** Questions to ask the user before continuing. */ - questions: ({ - /** Stable id for this question; echoed in the answer. */ - id: string; - /** The specific question to ask the user. */ - question: string; - /** Optional short heading for the question, such as "Confirm" or "Choose Mode". */ - header?: string; - /** Optional choices to show the user. If you recommend one, put it first and append "(Recommended)" to that label. */ - options?: ({ - /** Short user-facing option label. */ - label: string; - /** One sentence explaining the tradeoff or impact. */ - description?: string; - } & Record<string, JsonValue>)[]; - /** Whether the user may select more than one option. Defaults to false. */ - multi_select?: boolean; - } & Record<string, JsonValue>)[]; - } & Record<string, JsonValue>; /** Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later. */ bash: { /** The bash command to execute. */ @@ -101,11 +80,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. */ justification?: string; } & Record<string, JsonValue>; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record<string, JsonValue>; /** Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal. */ get_goal: Record<string, JsonValue>; /** Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools. */ @@ -302,13 +276,6 @@ interface ToolArgsMap { } interface ToolOutputMap { - ask_user_question: { - answers: { - id: string; - selected: string[]; - custom?: string; - }[]; - }; bash: { kind: "background"; taskId: string; @@ -358,9 +325,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/examples/acp-agent/tests/snapshots/config-options/input.json b/examples/acp-agent/tests/snapshots/config-options/input.json deleted file mode 100644 index 900367cea8..0000000000 --- a/examples/acp-agent/tests/snapshots/config-options/input.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "steps": [ - { - "op": "initialize" - }, - { - "op": "newSession" - }, - { - "op": "setConfigOption", - "configId": "permission", - "value": "workspace-write" - }, - { - "op": "setConfigOption", - "configId": "permission", - "value": "danger-full-access" - }, - { - "op": "setConfigOptionExpectError", - "configId": "permission", - "value": "plan" - }, - { - "op": "setConfigOptionExpectError", - "configId": "reasoning-effort", - "value": "max" - } - ] -} diff --git a/examples/acp-agent/tests/snapshots/config-options/session.jsonl b/examples/acp-agent/tests/snapshots/config-options/session.jsonl deleted file mode 100644 index 63f2775383..0000000000 --- a/examples/acp-agent/tests/snapshots/config-options/session.jsonl +++ /dev/null @@ -1 +0,0 @@ -{"type":"session","version":0,"id":"00000000-0000-0000-0000-000000000000","createdAt":0,"delegationDepth":0} diff --git a/examples/acp-agent/tests/snapshots/config-options/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/config-options/stdout.expected.jsonl deleted file mode 100644 index 53ad812adb..0000000000 --- a/examples/acp-agent/tests/snapshots/config-options/stdout.expected.jsonl +++ /dev/null @@ -1,7 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"workspace-write","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","id":4,"result":{"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","id":5,"error":{"code":-32602,"message":"Invalid params: unknown permission value \"plan\""}} -{"jsonrpc":"2.0","id":6,"error":{"code":-32602,"message":"Invalid params: unknown config option \"reasoning-effort\""}} diff --git a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/stdout.expected.jsonl index 56cc640977..eff1b66bf3 100644 --- a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/stdout.expected.jsonl @@ -1,10 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Inspect the exact tools service","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"inspect-tools-api","title":"Inspect cordis runtime: api: tools","kind":"read","status":"in_progress"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"inspect-tools-api","status":"completed","content":[{"type":"content","content":{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - tool schema, execution, and optional finalization/presentation callbacks.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy,\n * definition-owned content finalization, and final notification. Tool and\n * listener failures resolve as materialized error results; an invisible tool\n * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen\n * snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise<ToolExecutionResult>\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly ctx: Context;\n followup(content: ContentBlock[], options?: SendOptions): AgentMessageId;\n queue(content: ContentBlock[], options?: SendOptions): AgentMessageId;\n steer(content: ContentBlock[], options?: SendOptions): AgentMessageId;\n inject(content: ContentBlock[], options?: InjectOptions): AgentMessageId;\n send(input: ResolvedAgentInput): AgentMessageId;\n cancel(cause?: AgentCancelCause, options?: CancelOptions): void;\n whenIdle(): Promise<void>;\n }\n export type AgentCancelCause = {\n readonly kind: 'user';\n } | {\n readonly kind: 'parent';\n };\n export type AgentMessageId = Branded<'AgentMessageId'>;\n export interface AgentOptions {\n provider?: string;\n model?: string;\n }\n export type AgentStatus = 'idle' | 'running' | 'disposed';\n export interface AssistantProvenance {\n provider: string;\n model: string;\n replayState?: unknown;\n }\n export type Branded<B extends string> = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface CancelOptions {\n keepInbox?: boolean;\n }\n export interface ContentBlockMap {\n 'text': TextBlock;\n 'reasoning': ReasoningBlock;\n 'tool-call': ToolCallBlock;\n 'tool-result': ToolResultBlock;\n }\n export type ContentBlockType = keyof ContentBlockMap;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface EpochHeader {\n config: LlmCallConfig;\n system?: string;\n tools?: ToolSchema[];\n messagePrefix?: Message[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export type FinishReason = FinishReasonMap[keyof FinishReasonMap];\n export interface FinishReasonMap {\n 'stop': {\n kind: 'stop';\n };\n 'tool-calls': {\n kind: 'tool-calls';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n 'aborted': {\n kind: 'aborted';\n failure: LlmFailure;\n };\n 'error': {\n kind: 'error';\n failure: LlmFailure;\n };\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export interface HookContext {\n content: ContentBlock[];\n source: MessageSource;\n placement?: 'separate' | 'prompt-prefix';\n meta?: JsonValue;\n }\n export interface InjectOptions {\n source?: MessageSource;\n meta?: JsonValue;\n }\n export interface JsonSchemaNode {\n type?: JsonSchemaType;\n oneOf?: JsonSchemaNode[];\n properties?: Record<string, JsonSchemaNode>;\n required?: string[];\n additionalProperties?: boolean;\n items?: JsonSchemaNode;\n enum?: JsonSchemaScalar[];\n const?: JsonSchemaScalar;\n description?: string;\n title?: string;\n default?: JsonValue;\n examples?: JsonValue;\n }\n export type JsonSchemaScalar = string | number | boolean | null;\n export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export interface LlmCallConfig {\n provider: string;\n model: string;\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n }\n export interface LlmFailure {\n readonly message: string;\n readonly code: string;\n readonly status?: number;\n readonly providerRetryAfterMs?: number;\n readonly requestId?: ProviderRequestId;\n }\n export interface Message {\n role: 'system' | 'user' | 'assistant';\n content: ContentBlock[];\n provenance?: AssistantProvenance;\n }\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n }\n export interface PromptMessageData {\n content: ContentBlock[];\n source: MessageSource;\n envelope?: PromptMessageEnvelope;\n meta?: JsonValue;\n }\n export interface PromptMessageEnvelope {\n displayContent: ContentBlock[];\n prefixContexts: PromptPrefixContext[];\n }\n export interface PromptPrefixContext {\n source: MessageSource;\n meta?: JsonValue;\n }\n export type ProviderRequestId = Branded<'ProviderRequestId'>;\n export interface ReasoningBlock {\n type: 'reasoning';\n text: string;\n }\n export type RequestHeaderReason = 'initial' | 'resume' | 'change';\n export type ResolvedAgentInput = {\n content: ContentBlock[];\n source: MessageSource;\n meta: JsonValue | undefined;\n } & ({\n target: 'next-turn';\n wakeup: boolean;\n contexts: HookContext[];\n } | {\n target: 'next-step';\n wakeup: true;\n contexts: HookContext[];\n } | {\n target: 'next-step';\n wakeup: false;\n contexts: [\n ];\n });\n export type ScopeKey = object;\n export interface SendOptions {\n source?: MessageSource;\n contexts?: HookContext[];\n meta?: JsonValue;\n }\n export class Session {\n get surface(): SessionSurface;\n readonly header: SessionHeader;\n get id(): SessionId;\n constructor(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader);\n get events(): readonly SessionEvent[];\n get seq(): number;\n append<T extends SessionEventType>(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]): SessionEvent<T>;\n requestHeader(): EpochHeader | undefined;\n deriveMessages(): Message[];\n deriveEventMessage(event: SessionEvent): Message | null;\n }\n export type SessionEvent<T extends SessionEventType = SessionEventType> = {\n [K in SessionEventType]: {\n type: K;\n seq: number;\n time: number;\n data: SessionEventMap[K];\n } & (K extends SurfaceEventType ? {\n sourceEventSeqs?: number[];\n surfaceOp?: SurfaceOp;\n } : object);\n }[T];\n export interface SessionEventMap {\n 'turn/start': {\n turn: number;\n trigger: TurnTrigger;\n };\n 'turn/end': {\n turn: number;\n reason: TurnEndReason;\n };\n 'step/start': {\n turn: number;\n step: number;\n };\n 'step/end': {\n turn: number;\n step: number;\n };\n 'user/message': PromptMessageData;\n 'prompt/blocked': {\n content: ContentBlock[];\n source: MessageSource;\n reason: string;\n };\n 'assistant/chunk': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n 'assistant/message': {\n turn: number;\n step: number;\n content: ContentBlock[];\n provenance: AssistantProvenance;\n usage?: TokenUsage;\n };\n 'tool/call': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n 'tool/result': {\n turn: number;\n step: number;\n callId: CallId;\n content: ContentBlock[];\n isError: boolean;\n error?: {\n name: string;\n code: string;\n };\n meta?: JsonValue;\n };\n 'steering/message': PromptMessageData & {\n turn: number;\n };\n 'todo/write': {\n todos: TodoItem[];\n };\n 'request/header': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n };\n }\n export type SessionEventType = keyof SessionEventMap;\n export interface SessionHeader {\n readonly version: number;\n readonly id: SessionId;\n readonly createdAt: number;\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly delegationDepth?: number;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface SessionSurface {\n readonly nodes: readonly number[];\n readonly replaceGeneration: number;\n }\n export type StreamChunk = {\n type: 'block-start';\n index: number;\n blockType: ContentBlockType;\n } | {\n type: 'text-delta';\n index: number;\n text: string;\n } | {\n type: 'reasoning-delta';\n index: number;\n text: string;\n } | {\n type: 'tool-call-delta';\n index: number;\n id: CallId;\n name?: string;\n argumentsDelta: string;\n } | {\n type: 'block-end';\n index: number;\n block: ContentBlock;\n } | {\n type: 'usage';\n usage: TokenUsage;\n } | {\n type: 'finish';\n reason: FinishReason;\n replayState?: unknown;\n };\n export type SurfaceEventType = 'user/message' | 'assistant/message' | 'tool/result' | 'steering/message';\n export interface SurfaceIntent {\n surfaceOp: SurfaceOp;\n sourceEventSeqs?: number[];\n }\n export type SurfaceOp = 'append' | {\n op: 'replace';\n start: number;\n end: number;\n };\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export interface TodoItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n }\n export interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n }\n export interface ToolCallBlock {\n type: 'tool-call';\n id: CallId;\n name: string;\n arguments: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n readonly output: ToolOutputDefinition;\n execute(args: unknown, exec: ToolRunContext): Promise<unknown>;\n finalizeContent?(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>): ContentBlock[] | undefined;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionFailure {\n readonly isError: true;\n readonly error: ToolFailure;\n readonly value?: never;\n readonly content: ContentBlock[];\n readonly meta?: JsonValue;\n readonly additionalContexts?: HookContext[];\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\n export interface ToolExecutionSuccess {\n readonly isError: false;\n readonly value: JsonValue;\n readonly content: ContentBlock[];\n readonly error?: never;\n readonly meta?: JsonValue;\n readonly additionalContexts?: HookContext[];\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export interface ToolFailure {\n message: string;\n info?: ToolErrorInfo;\n }\n export type ToolGuard = (execution: Readonly<ToolExecution>) => string | undefined;\n export interface ToolOutputDefinition {\n readonly schema: JsonSchemaNode;\n render(args: unknown, value: JsonValue): ContentBlock[];\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\n }\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: JsonValue;\n }\n export interface ToolResultBlock {\n type: 'tool-result';\n toolCallId: CallId;\n content: ContentBlock[];\n isError?: boolean;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: HookContext): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n }\n export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];\n export interface TurnEndReasonMap {\n completed: {\n kind: 'completed';\n };\n aborted: {\n kind: 'aborted';\n };\n error: {\n kind: 'error';\n step: number;\n } & ({\n failure: LlmFailure;\n message?: never;\n code?: never;\n } | {\n message: string;\n code?: string;\n failure?: never;\n });\n disposed: {\n kind: 'disposed';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n rejected: {\n kind: 'rejected';\n reason: string;\n };\n interrupted: {\n kind: 'interrupted';\n };\n }\n export type TurnTrigger = TurnTriggerMap[keyof TurnTriggerMap];\n export interface TurnTriggerMap {\n message: {\n kind: 'message';\n source: MessageSource;\n };\n injection: {\n kind: 'injection';\n source: MessageSource;\n };\n }"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"inspect-tools-event","title":"Inspect cordis runtime: events: tools/pre-execute","kind":"read","status":"in_progress"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"inspect-tools-event","status":"completed","content":[{"type":"content","content":{"type":"text","text":"## events\n- tools/pre-execute [waterfall] — Allow, deny, or ask before dispatch.\n /**\n * Allow, deny, or ask before dispatch. `next()` delegates to allow; missing\n * approval support turns `ask` into denial. Async gates must observe\n * `exec.signal`; the registry rechecks cancellation after they settle but\n * never abandons their promise.\n * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent's calls.\n * @param exec - the pending call (name, parsed arguments, caller agent).\n * @mode waterfall\n */\n 'tools/pre-execute'(this: Scoped<ToolRegistry>, exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision>\nwaterfall listeners receive a trailing next() and MUST call it to delegate — returning without next() vetoes the chain."}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"CORDIS_INSPECT_JSDOC_OK"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/error-finish/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/error-finish/stdout.expected.jsonl index ecef64b941..4ad17f44e8 100644 --- a/examples/acp-agent/tests/snapshots/error-finish/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/error-finish/stdout.expected.jsonl @@ -1,6 +1,3 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"This prompt triggers a recorded","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\n\n[Model attempt failed; any partial output above is discarded: simulated provider error (HTTP 401)]\n\n"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","id":3,"error":{"code":-32603,"message":"Internal error: turn failed: simulated provider error (HTTP 401)"}} diff --git a/examples/acp-agent/tests/snapshots/escalation-approved/input.json b/examples/acp-agent/tests/snapshots/escalation-approved/input.json index 99f9f8821b..226171ecfc 100644 --- a/examples/acp-agent/tests/snapshots/escalation-approved/input.json +++ b/examples/acp-agent/tests/snapshots/escalation-approved/input.json @@ -6,11 +6,6 @@ { "op": "newSession" }, - { - "op": "setConfigOption", - "configId": "permission", - "value": "workspace-write" - }, { "op": "prompt", "text": "The sandbox already denied writing /tmp/dsh-escalated.txt earlier (it is outside this workspace). Retry it now exactly once: one single bash call with the command printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt, with sandbox_permissions set to danger-full-access and the justification 'the user asked to write a file outside the workspace'. Do not run it without sandbox_permissions first. I will approve the permission prompt. After the result, reply with the single word DONE and stop." diff --git a/examples/acp-agent/tests/snapshots/escalation-approved/session.jsonl b/examples/acp-agent/tests/snapshots/escalation-approved/session.jsonl index 4438550b97..bf8440bf80 100644 --- a/examples/acp-agent/tests/snapshots/escalation-approved/session.jsonl +++ b/examples/acp-agent/tests/snapshots/escalation-approved/session.jsonl @@ -1,189 +1,186 @@ {"type":"session","version":0,"id":"f3cbd087-fb45-4b32-b0f2-3082d65bfcb4","createdAt":1783860675270,"cwd":"/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-cbBLh2","delegationDepth":0} {"type":"turn/start","seq":0,"time":1783860675271,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"permission/preset","seq":1,"time":1783962245380,"data":{"preset":"workspace-write"}} -{"type":"sandbox/mode","seq":2,"time":1784518116517,"data":{"mode":"workspace-write"}} -{"type":"approval/policy","seq":3,"time":1783962245380,"data":{"policy":"ask"}} -{"type":"user/message","seq":4,"time":1783962245380,"data":{"content":[{"type":"text","text":"The sandbox already denied writing /tmp/dsh-escalated.txt earlier (it is outside this workspace). Retry it now exactly once: one single bash call with the command printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt, with sandbox_permissions set to danger-full-access and the justification 'the user asked to write a file outside the workspace'. Do not run it without sandbox_permissions first. I will approve the permission prompt. After the result, reply with the single word DONE and stop."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"session/title","seq":5,"time":1783962245380,"data":{"title":"The sandbox already denied writing","messageSeqs":[4],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":6,"time":1783962245382,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":7,"time":1783962245382,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"assistant/chunk","seq":8,"time":1783860676464,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":9,"time":1783860676465,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":10,"time":1783860676465,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":11,"time":1783860676465,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":12,"time":1783860676465,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":13,"time":1783860676499,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":14,"time":1783860676499,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} -{"type":"assistant/chunk","seq":15,"time":1783860676499,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":16,"time":1783860676522,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} -{"type":"assistant/chunk","seq":17,"time":1783860676525,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":18,"time":1783860676525,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" sand"}}} -{"type":"assistant/chunk","seq":19,"time":1783860676525,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} -{"type":"assistant/chunk","seq":20,"time":1783860676553,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_per"}}} -{"type":"assistant/chunk","seq":21,"time":1783860676553,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"missions"}}} -{"type":"assistant/chunk","seq":22,"time":1783860676554,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" set"}}} -{"type":"assistant/chunk","seq":23,"time":1783860676554,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":24,"time":1783860676554,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" danger"}}} -{"type":"assistant/chunk","seq":25,"time":1783860676583,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-full"}}} -{"type":"assistant/chunk","seq":26,"time":1783860676583,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-access"}}} -{"type":"assistant/chunk","seq":27,"time":1783860676611,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":28,"time":1783860676639,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" no"}}} -{"type":"assistant/chunk","seq":29,"time":1783860676640,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" prior"}}} -{"type":"assistant/chunk","seq":30,"time":1783860676672,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} -{"type":"assistant/chunk","seq":31,"time":1783860676673,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" needed"}}} -{"type":"assistant/chunk","seq":32,"time":1783860676705,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":33,"time":1783860676728,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" justified"}}} -{"type":"assistant/chunk","seq":34,"time":1783860676787,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" as"}}} -{"type":"assistant/chunk","seq":35,"time":1783860676788,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" instructed"}}} -{"type":"assistant/chunk","seq":36,"time":1783860676816,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":37,"time":1783860676816,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":38,"time":1783860676816,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":39,"time":1783860676816,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":40,"time":1783860676845,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":41,"time":1783860676845,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":42,"time":1783860676846,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":43,"time":1783860676846,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":44,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":45,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"printf"}}} -{"type":"assistant/chunk","seq":46,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" '"}}} -{"type":"assistant/chunk","seq":47,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"es"}}} -{"type":"assistant/chunk","seq":48,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":49,"time":1783860676879,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":50,"time":1783860676909,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\\\\n"}}} -{"type":"assistant/chunk","seq":51,"time":1783860676911,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"'"}}} -{"type":"assistant/chunk","seq":52,"time":1783860676912,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" >"}}} -{"type":"assistant/chunk","seq":53,"time":1783860676912,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":54,"time":1783860676912,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"tmp"}}} -{"type":"assistant/chunk","seq":55,"time":1783860676939,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"/d"}}} -{"type":"assistant/chunk","seq":56,"time":1783860676941,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"sh"}}} -{"type":"assistant/chunk","seq":57,"time":1783860676941,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-es"}}} -{"type":"assistant/chunk","seq":58,"time":1783860676941,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":59,"time":1783860676941,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":60,"time":1783860676967,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":61,"time":1783860676969,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" &&"}}} -{"type":"assistant/chunk","seq":62,"time":1783860676969,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" cat"}}} -{"type":"assistant/chunk","seq":63,"time":1783860676970,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":64,"time":1783860676970,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"tmp"}}} -{"type":"assistant/chunk","seq":65,"time":1783860676970,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"/d"}}} -{"type":"assistant/chunk","seq":66,"time":1783860677003,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"sh"}}} -{"type":"assistant/chunk","seq":67,"time":1783860677003,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-es"}}} -{"type":"assistant/chunk","seq":68,"time":1783860677003,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":69,"time":1783860677003,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":70,"time":1783860677004,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":71,"time":1783860677004,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" &&"}}} -{"type":"assistant/chunk","seq":72,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" rm"}}} -{"type":"assistant/chunk","seq":73,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":74,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"tmp"}}} -{"type":"assistant/chunk","seq":75,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"/d"}}} -{"type":"assistant/chunk","seq":76,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"sh"}}} -{"type":"assistant/chunk","seq":77,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-es"}}} -{"type":"assistant/chunk","seq":78,"time":1783860677055,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":79,"time":1783860677085,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":80,"time":1783860677087,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":81,"time":1783860677087,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":82,"time":1783860677087,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":83,"time":1783860677087,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":84,"time":1783860677115,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":85,"time":1783860677115,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":86,"time":1783860677116,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":87,"time":1783860677116,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":88,"time":1783860677146,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"Write"}}} -{"type":"assistant/chunk","seq":89,"time":1783860677147,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" file"}}} -{"type":"assistant/chunk","seq":90,"time":1783860677148,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" outside"}}} -{"type":"assistant/chunk","seq":91,"time":1783860677174,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" workspace"}}} -{"type":"assistant/chunk","seq":92,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" and"}}} -{"type":"assistant/chunk","seq":93,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" verify"}}} -{"type":"assistant/chunk","seq":94,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":95,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":96,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":97,"time":1783860677238,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"sand"}}} -{"type":"assistant/chunk","seq":98,"time":1783860677238,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"box"}}} -{"type":"assistant/chunk","seq":99,"time":1783860677238,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"_per"}}} -{"type":"assistant/chunk","seq":100,"time":1783860677238,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"missions"}}} -{"type":"assistant/chunk","seq":101,"time":1783860677275,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":102,"time":1783860677275,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":103,"time":1783860677276,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":104,"time":1783860677276,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"danger"}}} -{"type":"assistant/chunk","seq":105,"time":1783860677292,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-full"}}} -{"type":"assistant/chunk","seq":106,"time":1783860677293,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-access"}}} -{"type":"assistant/chunk","seq":107,"time":1783860677320,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":108,"time":1783860677321,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":", "}}} +{"type":"user/message","seq":1,"time":1784821261714,"data":{"content":[{"type":"text","text":"The sandbox already denied writing /tmp/dsh-escalated.txt earlier (it is outside this workspace). Retry it now exactly once: one single bash call with the command printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt, with sandbox_permissions set to danger-full-access and the justification 'the user asked to write a file outside the workspace'. Do not run it without sandbox_permissions first. I will approve the permission prompt. After the result, reply with the single word DONE and stop."}],"source":{"kind":"user"}},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":1784821261714,"data":{"title":"The sandbox already denied writing","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":1784821261726,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":1784821261726,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"assistant/chunk","seq":5,"time":1784821261748,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":6,"time":1784821261748,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":7,"time":1784821261748,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} +{"type":"assistant/chunk","seq":8,"time":1784821261748,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} +{"type":"assistant/chunk","seq":9,"time":1783860676464,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":10,"time":1783860676465,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":11,"time":1783860676465,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} +{"type":"assistant/chunk","seq":12,"time":1783860676465,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} +{"type":"assistant/chunk","seq":13,"time":1783860676465,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} +{"type":"assistant/chunk","seq":14,"time":1783860676499,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":15,"time":1783860676499,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" sand"}}} +{"type":"assistant/chunk","seq":16,"time":1783860676499,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} +{"type":"assistant/chunk","seq":17,"time":1783860676522,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_per"}}} +{"type":"assistant/chunk","seq":18,"time":1783860676525,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"missions"}}} +{"type":"assistant/chunk","seq":19,"time":1783860676525,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" set"}}} +{"type":"assistant/chunk","seq":20,"time":1783860676525,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":21,"time":1783860676553,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" danger"}}} +{"type":"assistant/chunk","seq":22,"time":1783860676553,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-full"}}} +{"type":"assistant/chunk","seq":23,"time":1783860676554,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-access"}}} +{"type":"assistant/chunk","seq":24,"time":1783860676554,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} +{"type":"assistant/chunk","seq":25,"time":1783860676554,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" no"}}} +{"type":"assistant/chunk","seq":26,"time":1783860676583,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" prior"}}} +{"type":"assistant/chunk","seq":27,"time":1783860676583,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} +{"type":"assistant/chunk","seq":28,"time":1783860676611,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" needed"}}} +{"type":"assistant/chunk","seq":29,"time":1783860676639,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} +{"type":"assistant/chunk","seq":30,"time":1783860676640,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" justified"}}} +{"type":"assistant/chunk","seq":31,"time":1783860676672,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" as"}}} +{"type":"assistant/chunk","seq":32,"time":1783860676673,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" instructed"}}} +{"type":"assistant/chunk","seq":33,"time":1783860676705,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":34,"time":1783860676728,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":35,"time":1783860676787,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":""}}} +{"type":"assistant/chunk","seq":36,"time":1783860676788,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"{"}}} +{"type":"assistant/chunk","seq":37,"time":1783860676816,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":38,"time":1783860676816,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"command"}}} +{"type":"assistant/chunk","seq":39,"time":1783860676816,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":40,"time":1783860676816,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":41,"time":1783860676845,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":42,"time":1783860676845,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"printf"}}} +{"type":"assistant/chunk","seq":43,"time":1783860676846,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" '"}}} +{"type":"assistant/chunk","seq":44,"time":1783860676846,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"es"}}} +{"type":"assistant/chunk","seq":45,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":46,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":47,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\\\\n"}}} +{"type":"assistant/chunk","seq":48,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"'"}}} +{"type":"assistant/chunk","seq":49,"time":1783860676878,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" >"}}} +{"type":"assistant/chunk","seq":50,"time":1783860676879,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" /"}}} +{"type":"assistant/chunk","seq":51,"time":1783860676909,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"tmp"}}} +{"type":"assistant/chunk","seq":52,"time":1783860676911,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"/d"}}} +{"type":"assistant/chunk","seq":53,"time":1783860676912,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"sh"}}} +{"type":"assistant/chunk","seq":54,"time":1783860676912,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-es"}}} +{"type":"assistant/chunk","seq":55,"time":1783860676912,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":56,"time":1783860676939,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":57,"time":1783860676941,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":".txt"}}} +{"type":"assistant/chunk","seq":58,"time":1783860676941,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" &&"}}} +{"type":"assistant/chunk","seq":59,"time":1783860676941,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" cat"}}} +{"type":"assistant/chunk","seq":60,"time":1783860676941,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" /"}}} +{"type":"assistant/chunk","seq":61,"time":1783860676967,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"tmp"}}} +{"type":"assistant/chunk","seq":62,"time":1783860676969,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"/d"}}} +{"type":"assistant/chunk","seq":63,"time":1783860676969,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"sh"}}} +{"type":"assistant/chunk","seq":64,"time":1783860676970,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-es"}}} +{"type":"assistant/chunk","seq":65,"time":1783860676970,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":66,"time":1783860676970,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":67,"time":1783860677003,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":".txt"}}} +{"type":"assistant/chunk","seq":68,"time":1783860677003,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" &&"}}} +{"type":"assistant/chunk","seq":69,"time":1783860677003,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" rm"}}} +{"type":"assistant/chunk","seq":70,"time":1783860677003,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" /"}}} +{"type":"assistant/chunk","seq":71,"time":1783860677004,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"tmp"}}} +{"type":"assistant/chunk","seq":72,"time":1783860677004,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"/d"}}} +{"type":"assistant/chunk","seq":73,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"sh"}}} +{"type":"assistant/chunk","seq":74,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-es"}}} +{"type":"assistant/chunk","seq":75,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":76,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":77,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":".txt"}}} +{"type":"assistant/chunk","seq":78,"time":1783860677026,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":79,"time":1783860677055,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":80,"time":1783860677085,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":81,"time":1783860677087,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"description"}}} +{"type":"assistant/chunk","seq":82,"time":1783860677087,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":83,"time":1783860677087,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":84,"time":1783860677087,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":85,"time":1783860677115,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"Write"}}} +{"type":"assistant/chunk","seq":86,"time":1783860677115,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" file"}}} +{"type":"assistant/chunk","seq":87,"time":1783860677116,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" outside"}}} +{"type":"assistant/chunk","seq":88,"time":1783860677116,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" workspace"}}} +{"type":"assistant/chunk","seq":89,"time":1783860677146,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" and"}}} +{"type":"assistant/chunk","seq":90,"time":1783860677147,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" verify"}}} +{"type":"assistant/chunk","seq":91,"time":1783860677148,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":92,"time":1783860677174,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":93,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":94,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"sand"}}} +{"type":"assistant/chunk","seq":95,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"box"}}} +{"type":"assistant/chunk","seq":96,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"_per"}}} +{"type":"assistant/chunk","seq":97,"time":1783860677202,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"missions"}}} +{"type":"assistant/chunk","seq":98,"time":1783860677238,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":99,"time":1783860677238,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":100,"time":1783860677238,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":101,"time":1783860677238,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"danger"}}} +{"type":"assistant/chunk","seq":102,"time":1783860677275,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-full"}}} +{"type":"assistant/chunk","seq":103,"time":1783860677275,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"-access"}}} +{"type":"assistant/chunk","seq":104,"time":1783860677276,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":105,"time":1783860677276,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":106,"time":1783860677292,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":107,"time":1783860677293,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"just"}}} +{"type":"assistant/chunk","seq":108,"time":1783860677320,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ification"}}} {"type":"assistant/chunk","seq":109,"time":1783860677321,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":110,"time":1783860677321,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"just"}}} -{"type":"assistant/chunk","seq":111,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"ification"}}} -{"type":"assistant/chunk","seq":112,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":113,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":114,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":115,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"the"}}} -{"type":"assistant/chunk","seq":116,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" user"}}} -{"type":"assistant/chunk","seq":117,"time":1783860677388,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" asked"}}} -{"type":"assistant/chunk","seq":118,"time":1783860677388,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" to"}}} -{"type":"assistant/chunk","seq":119,"time":1783860677388,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" write"}}} -{"type":"assistant/chunk","seq":120,"time":1783860677388,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" a"}}} -{"type":"assistant/chunk","seq":121,"time":1783860677492,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" file"}}} -{"type":"assistant/chunk","seq":122,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" outside"}}} -{"type":"assistant/chunk","seq":123,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":124,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" workspace"}}} -{"type":"assistant/chunk","seq":125,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":126,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":127,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run a command with sandbox_permissions set to danger-full-access, no prior run needed, justified as instructed."}}}} -{"type":"assistant/chunk","seq":128,"time":1783962245385,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write file outside workspace and verify\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}}}} -{"type":"assistant/chunk","seq":129,"time":1783962245385,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1501,"outputTokens":174,"cacheReadTokens":0,"reasoningTokens":28}}}} -{"type":"assistant/chunk","seq":130,"time":1783962245385,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":131,"time":1783962245385,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to run a command with sandbox_permissions set to danger-full-access, no prior run needed, justified as instructed."},{"type":"tool-call","id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write file outside workspace and verify\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":1501,"outputTokens":174,"cacheReadTokens":0,"reasoningTokens":28}},"sourceEventSeqs":[8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130],"surfaceOp":"append"} -{"type":"tool/call","seq":132,"time":1783962245385,"data":{"turn":1,"step":1,"callId":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write file outside workspace and verify\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}} -{"type":"approval/asked","seq":133,"time":1783962245386,"data":{"id":"efa76e4a-8e3e-4be0-9608-a68def7354b9","toolName":"bash","callId":"call_00_d0sAHpJ9mYOJi0z7KNy30441","reason":"escalate sandbox to danger-full-access: the user asked to write a file outside the workspace"}} -{"type":"approval/decided","seq":134,"time":1783962245387,"data":{"id":"efa76e4a-8e3e-4be0-9608-a68def7354b9","outcome":"allowed-once"}} -{"type":"tool/result","seq":135,"time":1783962245399,"data":{"turn":1,"step":1,"callId":"call_00_d0sAHpJ9mYOJi0z7KNy30441","content":[{"type":"text","text":"escalated\n"}],"isError":false},"sourceEventSeqs":[132],"surfaceOp":"append"} -{"type":"step/end","seq":136,"time":1783962245400,"data":{"turn":1,"step":1}} -{"type":"step/start","seq":137,"time":1783962245400,"data":{"turn":1,"step":2}} -{"type":"assistant/chunk","seq":138,"time":1783860678811,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":139,"time":1783860678811,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":140,"time":1783860678833,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} -{"type":"assistant/chunk","seq":141,"time":1783860678834,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" succeeded"}}} -{"type":"assistant/chunk","seq":142,"time":1783860678834,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" —"}}} -{"type":"assistant/chunk","seq":143,"time":1783860678868,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} -{"type":"assistant/chunk","seq":144,"time":1783860678868,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" wrote"}}} -{"type":"assistant/chunk","seq":145,"time":1783860678868,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":146,"time":1783860678904,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":147,"time":1783860678905,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":148,"time":1783860678926,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" read"}}} -{"type":"assistant/chunk","seq":149,"time":1783860678926,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} -{"type":"assistant/chunk","seq":150,"time":1783860678926,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" back"}}} -{"type":"assistant/chunk","seq":151,"time":1783860678975,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" ("}}} -{"type":"assistant/chunk","seq":152,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"output"}}} -{"type":"assistant/chunk","seq":153,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":154,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"es"}}} -{"type":"assistant/chunk","seq":155,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"cal"}}} -{"type":"assistant/chunk","seq":156,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ated"}}} -{"type":"assistant/chunk","seq":157,"time":1783860678999,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\"),"}}} -{"type":"assistant/chunk","seq":158,"time":1783860679001,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":159,"time":1783860679002,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" removed"}}} -{"type":"assistant/chunk","seq":160,"time":1783860679002,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} -{"type":"assistant/chunk","seq":161,"time":1783860679002,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":162,"time":1783860679016,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" The"}}} -{"type":"assistant/chunk","seq":163,"time":1783860679017,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":164,"time":1783860679017,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" asked"}}} -{"type":"assistant/chunk","seq":165,"time":1783860679017,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":166,"time":1783860679046,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":167,"time":1783860679047,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":168,"time":1783860679048,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":169,"time":1783860679048,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":170,"time":1783860679079,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" single"}}} -{"type":"assistant/chunk","seq":171,"time":1783860679079,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" word"}}} -{"type":"assistant/chunk","seq":172,"time":1783860679103,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" D"}}} -{"type":"assistant/chunk","seq":173,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} -{"type":"assistant/chunk","seq":174,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" after"}}} -{"type":"assistant/chunk","seq":175,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":176,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" result"}}} -{"type":"assistant/chunk","seq":177,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":178,"time":1783860679137,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":179,"time":1783860679137,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} -{"type":"assistant/chunk","seq":180,"time":1783860679137,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} -{"type":"assistant/chunk","seq":181,"time":1783860679137,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The command succeeded — it wrote the file, read it back (output \"escalated\"), and removed it. The user asked me to reply with the single word DONE after the result."}}}} -{"type":"assistant/chunk","seq":182,"time":1783962245402,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} -{"type":"assistant/chunk","seq":183,"time":1783962245402,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":27,"outputTokens":42,"cacheReadTokens":1664,"reasoningTokens":39}}}} -{"type":"assistant/chunk","seq":184,"time":1783962245402,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":185,"time":1783962245402,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The command succeeded — it wrote the file, read it back (output \"escalated\"), and removed it. The user asked me to reply with the single word DONE after the result."},{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":27,"outputTokens":42,"cacheReadTokens":1664,"reasoningTokens":39}},"sourceEventSeqs":[138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184],"surfaceOp":"append"} -{"type":"step/end","seq":186,"time":1783962245402,"data":{"turn":1,"step":2}} -{"type":"turn/end","seq":187,"time":1783962245402,"data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"assistant/chunk","seq":110,"time":1783860677321,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":111,"time":1783860677321,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":112,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"the"}}} +{"type":"assistant/chunk","seq":113,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" user"}}} +{"type":"assistant/chunk","seq":114,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" asked"}}} +{"type":"assistant/chunk","seq":115,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" to"}}} +{"type":"assistant/chunk","seq":116,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" write"}}} +{"type":"assistant/chunk","seq":117,"time":1783860677349,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" a"}}} +{"type":"assistant/chunk","seq":118,"time":1783860677388,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" file"}}} +{"type":"assistant/chunk","seq":119,"time":1783860677388,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" outside"}}} +{"type":"assistant/chunk","seq":120,"time":1783860677388,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" the"}}} +{"type":"assistant/chunk","seq":121,"time":1783860677388,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":" workspace"}}} +{"type":"assistant/chunk","seq":122,"time":1783860677492,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":123,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","argumentsDelta":"}"}}} +{"type":"assistant/chunk","seq":124,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run a command with sandbox_permissions set to danger-full-access, no prior run needed, justified as instructed."}}}} +{"type":"assistant/chunk","seq":125,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write file outside workspace and verify\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}}}} +{"type":"assistant/chunk","seq":126,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1501,"outputTokens":174,"cacheReadTokens":0,"reasoningTokens":28}}}} +{"type":"assistant/chunk","seq":127,"time":1783860677493,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":128,"time":1784821261753,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to run a command with sandbox_permissions set to danger-full-access, no prior run needed, justified as instructed."},{"type":"tool-call","id":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write file outside workspace and verify\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":1501,"outputTokens":174,"cacheReadTokens":0,"reasoningTokens":28}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127],"surfaceOp":"append"} +{"type":"tool/call","seq":129,"time":1784821261754,"data":{"turn":1,"step":1,"callId":"call_00_d0sAHpJ9mYOJi0z7KNy30441","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write file outside workspace and verify\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}} +{"type":"approval/asked","seq":130,"time":1784821261758,"data":{"id":"bc159170-7ce0-4162-a6c4-ed41d4ca582f","toolName":"bash","callId":"call_00_d0sAHpJ9mYOJi0z7KNy30441","reason":"escalate sandbox to danger-full-access: the user asked to write a file outside the workspace"}} +{"type":"approval/decided","seq":131,"time":1784821261759,"data":{"id":"bc159170-7ce0-4162-a6c4-ed41d4ca582f","outcome":"allowed-once"}} +{"type":"tool/result","seq":132,"time":1784821261775,"data":{"turn":1,"step":1,"callId":"call_00_d0sAHpJ9mYOJi0z7KNy30441","content":[{"type":"text","text":"escalated\n"}],"isError":false},"sourceEventSeqs":[129],"surfaceOp":"append"} +{"type":"step/end","seq":133,"time":1784821261781,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":134,"time":1784821261782,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":135,"time":1784821261788,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":136,"time":1784821261788,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":137,"time":1784821261788,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} +{"type":"assistant/chunk","seq":138,"time":1784821261788,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" succeeded"}}} +{"type":"assistant/chunk","seq":139,"time":1783860678811,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" —"}}} +{"type":"assistant/chunk","seq":140,"time":1783860678811,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} +{"type":"assistant/chunk","seq":141,"time":1783860678833,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" wrote"}}} +{"type":"assistant/chunk","seq":142,"time":1783860678834,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} +{"type":"assistant/chunk","seq":143,"time":1783860678834,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} +{"type":"assistant/chunk","seq":144,"time":1783860678868,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} +{"type":"assistant/chunk","seq":145,"time":1783860678868,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" read"}}} +{"type":"assistant/chunk","seq":146,"time":1783860678868,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} +{"type":"assistant/chunk","seq":147,"time":1783860678904,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" back"}}} +{"type":"assistant/chunk","seq":148,"time":1783860678905,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" ("}}} +{"type":"assistant/chunk","seq":149,"time":1783860678926,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"output"}}} +{"type":"assistant/chunk","seq":150,"time":1783860678926,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} +{"type":"assistant/chunk","seq":151,"time":1783860678926,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"es"}}} +{"type":"assistant/chunk","seq":152,"time":1783860678975,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"cal"}}} +{"type":"assistant/chunk","seq":153,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ated"}}} +{"type":"assistant/chunk","seq":154,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\"),"}}} +{"type":"assistant/chunk","seq":155,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} +{"type":"assistant/chunk","seq":156,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" removed"}}} +{"type":"assistant/chunk","seq":157,"time":1783860678976,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} +{"type":"assistant/chunk","seq":158,"time":1783860678999,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":159,"time":1783860679001,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" The"}}} +{"type":"assistant/chunk","seq":160,"time":1783860679002,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} +{"type":"assistant/chunk","seq":161,"time":1783860679002,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" asked"}}} +{"type":"assistant/chunk","seq":162,"time":1783860679002,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":163,"time":1783860679016,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":164,"time":1783860679017,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} +{"type":"assistant/chunk","seq":165,"time":1783860679017,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":166,"time":1783860679017,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} +{"type":"assistant/chunk","seq":167,"time":1783860679046,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" single"}}} +{"type":"assistant/chunk","seq":168,"time":1783860679047,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" word"}}} +{"type":"assistant/chunk","seq":169,"time":1783860679048,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" D"}}} +{"type":"assistant/chunk","seq":170,"time":1783860679048,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} +{"type":"assistant/chunk","seq":171,"time":1783860679079,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" after"}}} +{"type":"assistant/chunk","seq":172,"time":1783860679079,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} +{"type":"assistant/chunk","seq":173,"time":1783860679103,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" result"}}} +{"type":"assistant/chunk","seq":174,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":175,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} +{"type":"assistant/chunk","seq":176,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} +{"type":"assistant/chunk","seq":177,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} +{"type":"assistant/chunk","seq":178,"time":1783860679136,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The command succeeded — it wrote the file, read it back (output \"escalated\"), and removed it. The user asked me to reply with the single word DONE after the result."}}}} +{"type":"assistant/chunk","seq":179,"time":1783860679137,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} +{"type":"assistant/chunk","seq":180,"time":1783860679137,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":27,"outputTokens":42,"cacheReadTokens":1664,"reasoningTokens":39}}}} +{"type":"assistant/chunk","seq":181,"time":1783860679137,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":182,"time":1784821261790,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The command succeeded — it wrote the file, read it back (output \"escalated\"), and removed it. The user asked me to reply with the single word DONE after the result."},{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":27,"outputTokens":42,"cacheReadTokens":1664,"reasoningTokens":39}},"sourceEventSeqs":[135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181],"surfaceOp":"append"} +{"type":"step/end","seq":183,"time":1784821261795,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":184,"time":1784821261795,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/escalation-approved/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/escalation-approved/stdout.expected.jsonl index f928a513ba..0bf109087a 100644 --- a/examples/acp-agent/tests/snapshots/escalation-approved/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/escalation-approved/stdout.expected.jsonl @@ -1,78 +1,5 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"workspace-write","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"The sandbox already denied writing","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sand"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"box"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_per"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"missions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" set"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" danger"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-full"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-access"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" no"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" prior"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" needed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" justified"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instructed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_d0sAHpJ9mYOJi0z7KNy30441","title":"printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt","kind":"execute","status":"in_progress","rawInput":"printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt","content":[{"type":"content","content":{"type":"text","text":"Write file outside workspace and verify"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","id":1,"method":"session/request_permission","params":{"sessionId":"{{sessionId}}","toolCall":{"toolCallId":"call_00_d0sAHpJ9mYOJi0z7KNy30441"},"options":[{"optionId":"allow-once","name":"Allow once","kind":"allow_once"},{"optionId":"reject-once","name":"Reject","kind":"reject_once"}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_d0sAHpJ9mYOJi0z7KNy30441","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nescalated\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" succeeded"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" —"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wrote"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"es"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"cal"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ated"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"),"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" removed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" asked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" after"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/escalation-approved/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/escalation-approved/system-prompt.expected.md new file mode 100644 index 0000000000..362d0a6355 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/escalation-approved/system-prompt.expected.md @@ -0,0 +1,26 @@ +You are an AI agent powered by the DeepSeek Harness SDK. + +You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + +Verify your work by running the code or tests. Keep answers brief and factual. + + +Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. + +Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes. + +Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session. + +Check the [exit code: N] marker on every bash result; investigate failures before moving on. + +Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. + +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + +Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. + +<!-- dsh-user-approval-policy:ask --> + +Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. + +Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. diff --git a/examples/acp-agent/tests/snapshots/escalation-approved/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/escalation-approved/tool-schemas.expected.json new file mode 100644 index 0000000000..dde0ba0d7a --- /dev/null +++ b/examples/acp-agent/tests/snapshots/escalation-approved/tool-schemas.expected.json @@ -0,0 +1,677 @@ +{ + "initial": [ + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." + } + }, + "required": [ + "command", + "description" + ] + } + }, + { + "name": "create_goal", + "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace. Must match exactly." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "ralph", + "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The immutable completion objective for every fresh Ralph round." + }, + "maxRounds": { + "type": "number", + "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, + { + "name": "skill", + "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "task_kill", + "description": "Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.", + "parameters": { + "type": "object", + "properties": { + "task_id": { + "type": "string", + "description": "Task id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the task." + } + }, + "required": [ + "task_id" + ] + } + }, + { + "name": "task_list", + "description": "List your background tasks (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "task_output", + "description": "Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", + "parameters": { + "type": "object", + "properties": { + "task_id": { + "type": "string", + "description": "Task id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." + } + }, + "required": [ + "task_id" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit | pause | resume | complete | blocked", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Concrete blocking condition; required only with action blocked." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return <value>` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)." + }, + "meta": { + "type": "object", + "description": "The workflow identity block (plain JSON — never code).", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [] +} diff --git a/examples/acp-agent/tests/snapshots/escalation-rejected/input.json b/examples/acp-agent/tests/snapshots/escalation-rejected/input.json index 83b9d8aab5..89218b3e30 100644 --- a/examples/acp-agent/tests/snapshots/escalation-rejected/input.json +++ b/examples/acp-agent/tests/snapshots/escalation-rejected/input.json @@ -6,11 +6,6 @@ { "op": "newSession" }, - { - "op": "setConfigOption", - "configId": "permission", - "value": "workspace-write" - }, { "op": "prompt", "text": "The sandbox already denied writing /tmp/dsh-escalated.txt earlier (it is outside this workspace). Retry it now exactly once: one single bash call with the command printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt, with sandbox_permissions set to danger-full-access and the justification 'the user asked to write a file outside the workspace'. Do not run it without sandbox_permissions first. I will reject the permission prompt; after the rejection, do not retry and do not work around it \u2014 explain in one short sentence and stop." diff --git a/examples/acp-agent/tests/snapshots/escalation-rejected/session.jsonl b/examples/acp-agent/tests/snapshots/escalation-rejected/session.jsonl index eb01e7443e..9ae1899961 100644 --- a/examples/acp-agent/tests/snapshots/escalation-rejected/session.jsonl +++ b/examples/acp-agent/tests/snapshots/escalation-rejected/session.jsonl @@ -1,216 +1,213 @@ {"type":"session","version":0,"id":"d692fe7f-7079-4ee4-8b06-f44fd026d4ea","createdAt":1783860679475,"cwd":"/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-Hn29Od","delegationDepth":0} {"type":"turn/start","seq":0,"time":1783860679476,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"permission/preset","seq":1,"time":1783962246267,"data":{"preset":"workspace-write"}} -{"type":"sandbox/mode","seq":2,"time":1784518117237,"data":{"mode":"workspace-write"}} -{"type":"approval/policy","seq":3,"time":1783962246267,"data":{"policy":"ask"}} -{"type":"user/message","seq":4,"time":1783962246267,"data":{"content":[{"type":"text","text":"The sandbox already denied writing /tmp/dsh-escalated.txt earlier (it is outside this workspace). Retry it now exactly once: one single bash call with the command printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt, with sandbox_permissions set to danger-full-access and the justification 'the user asked to write a file outside the workspace'. Do not run it without sandbox_permissions first. I will reject the permission prompt; after the rejection, do not retry and do not work around it — explain in one short sentence and stop."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"session/title","seq":5,"time":1783962246267,"data":{"title":"The sandbox already denied writing","messageSeqs":[4],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":6,"time":1783962246269,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":7,"time":1783962246269,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"assistant/chunk","seq":8,"time":1783860680779,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":9,"time":1783860680782,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":10,"time":1783860680782,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":11,"time":1783860680782,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":12,"time":1783860680830,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":13,"time":1783860680831,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":14,"time":1783860680831,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} -{"type":"assistant/chunk","seq":15,"time":1783860680859,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":16,"time":1783860680859,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" specific"}}} -{"type":"assistant/chunk","seq":17,"time":1783860680868,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} -{"type":"assistant/chunk","seq":18,"time":1783860680871,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":19,"time":1783860680871,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":20,"time":1783860680872,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"sand"}}} -{"type":"assistant/chunk","seq":21,"time":1783860680872,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} -{"type":"assistant/chunk","seq":22,"time":1783860680902,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_per"}}} -{"type":"assistant/chunk","seq":23,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"missions"}}} -{"type":"assistant/chunk","seq":24,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":25,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" set"}}} -{"type":"assistant/chunk","seq":26,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":27,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":28,"time":1783860680937,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"danger"}}} -{"type":"assistant/chunk","seq":29,"time":1783860680938,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-full"}}} -{"type":"assistant/chunk","seq":30,"time":1783860680938,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-access"}}} -{"type":"assistant/chunk","seq":31,"time":1783860680956,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":32,"time":1783860680958,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":33,"time":1783860680958,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":34,"time":1783860680958,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" specific"}}} -{"type":"assistant/chunk","seq":35,"time":1783860680985,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" justification"}}} -{"type":"assistant/chunk","seq":36,"time":1783860680985,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":37,"time":1783860681022,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" They"}}} -{"type":"assistant/chunk","seq":38,"time":1783860681024,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" explicitly"}}} -{"type":"assistant/chunk","seq":39,"time":1783860681024,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" said"}}} -{"type":"assistant/chunk","seq":40,"time":1783860681024,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" NOT"}}} -{"type":"assistant/chunk","seq":41,"time":1783860681024,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":42,"time":1783860681043,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} -{"type":"assistant/chunk","seq":43,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} -{"type":"assistant/chunk","seq":44,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" without"}}} -{"type":"assistant/chunk","seq":45,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" sand"}}} -{"type":"assistant/chunk","seq":46,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} -{"type":"assistant/chunk","seq":47,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_per"}}} -{"type":"assistant/chunk","seq":48,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"missions"}}} -{"type":"assistant/chunk","seq":49,"time":1783860681107,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" first"}}} -{"type":"assistant/chunk","seq":50,"time":1783860681107,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":51,"time":1783860681108,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} -{"type":"assistant/chunk","seq":52,"time":1783860681138,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":53,"time":1783860681138,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" do"}}} -{"type":"assistant/chunk","seq":54,"time":1783860681251,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} -{"type":"assistant/chunk","seq":55,"time":1783860681251,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" that"}}} -{"type":"assistant/chunk","seq":56,"time":1783860681251,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":57,"time":1783860681251,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":58,"time":1783860681252,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":59,"time":1783860681252,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":60,"time":1783860681252,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":61,"time":1783860681252,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":62,"time":1783860681280,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":63,"time":1783860681281,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":64,"time":1783860681281,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":65,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"printf"}}} -{"type":"assistant/chunk","seq":66,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" '"}}} -{"type":"assistant/chunk","seq":67,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"es"}}} -{"type":"assistant/chunk","seq":68,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":69,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":70,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\\\\n"}}} -{"type":"assistant/chunk","seq":71,"time":1783860681342,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"'"}}} -{"type":"assistant/chunk","seq":72,"time":1783860681343,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" >"}}} -{"type":"assistant/chunk","seq":73,"time":1783860681343,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":74,"time":1783860681343,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"tmp"}}} -{"type":"assistant/chunk","seq":75,"time":1783860681368,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"/d"}}} -{"type":"assistant/chunk","seq":76,"time":1783860681371,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"sh"}}} -{"type":"assistant/chunk","seq":77,"time":1783860681371,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-es"}}} -{"type":"assistant/chunk","seq":78,"time":1783860681371,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":79,"time":1783860681371,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":80,"time":1783860681400,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":81,"time":1783860681400,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" &&"}}} -{"type":"assistant/chunk","seq":82,"time":1783860681400,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" cat"}}} -{"type":"assistant/chunk","seq":83,"time":1783860681400,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":84,"time":1783860681401,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"tmp"}}} -{"type":"assistant/chunk","seq":85,"time":1783860681402,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"/d"}}} -{"type":"assistant/chunk","seq":86,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"sh"}}} -{"type":"assistant/chunk","seq":87,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-es"}}} -{"type":"assistant/chunk","seq":88,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":89,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":90,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":91,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" &&"}}} -{"type":"assistant/chunk","seq":92,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" rm"}}} -{"type":"assistant/chunk","seq":93,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":94,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"tmp"}}} -{"type":"assistant/chunk","seq":95,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"/d"}}} -{"type":"assistant/chunk","seq":96,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"sh"}}} -{"type":"assistant/chunk","seq":97,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-es"}}} -{"type":"assistant/chunk","seq":98,"time":1783860681485,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":99,"time":1783860681519,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":100,"time":1783860681521,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":101,"time":1783860681521,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":102,"time":1783860681521,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":103,"time":1783860681521,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":104,"time":1783860681542,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":105,"time":1783860681545,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":106,"time":1783860681545,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":107,"time":1783860681573,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":108,"time":1783860681573,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"Write"}}} -{"type":"assistant/chunk","seq":109,"time":1783860681574,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" to"}}} -{"type":"assistant/chunk","seq":110,"time":1783860681605,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" /"}}} -{"type":"assistant/chunk","seq":111,"time":1783860681608,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"tmp"}}} -{"type":"assistant/chunk","seq":112,"time":1783860681630,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" and"}}} -{"type":"assistant/chunk","seq":113,"time":1783860681632,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" verify"}}} -{"type":"assistant/chunk","seq":114,"time":1783860681661,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":","}}} -{"type":"assistant/chunk","seq":115,"time":1783860681661,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" then"}}} -{"type":"assistant/chunk","seq":116,"time":1783860681693,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" clean"}}} -{"type":"assistant/chunk","seq":117,"time":1783860681693,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" up"}}} -{"type":"assistant/chunk","seq":118,"time":1783860681693,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":119,"time":1783860681693,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":120,"time":1783860681725,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":121,"time":1783860681725,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"sand"}}} -{"type":"assistant/chunk","seq":122,"time":1783860681726,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"box"}}} -{"type":"assistant/chunk","seq":123,"time":1783860681726,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"_per"}}} -{"type":"assistant/chunk","seq":124,"time":1783860681751,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"missions"}}} -{"type":"assistant/chunk","seq":125,"time":1783860681753,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":126,"time":1783860681754,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":127,"time":1783860681754,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":128,"time":1783860681754,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"danger"}}} -{"type":"assistant/chunk","seq":129,"time":1783860681813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-full"}}} -{"type":"assistant/chunk","seq":130,"time":1783860681813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-access"}}} -{"type":"assistant/chunk","seq":131,"time":1783860681813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":132,"time":1783860681813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":", "}}} +{"type":"user/message","seq":1,"time":1784821263241,"data":{"content":[{"type":"text","text":"The sandbox already denied writing /tmp/dsh-escalated.txt earlier (it is outside this workspace). Retry it now exactly once: one single bash call with the command printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt, with sandbox_permissions set to danger-full-access and the justification 'the user asked to write a file outside the workspace'. Do not run it without sandbox_permissions first. I will reject the permission prompt; after the rejection, do not retry and do not work around it — explain in one short sentence and stop."}],"source":{"kind":"user"}},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":1784821263241,"data":{"title":"The sandbox already denied writing","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":1784821263267,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":1784821263267,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"assistant/chunk","seq":5,"time":1784821263288,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":6,"time":1784821263288,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":7,"time":1784821263288,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} +{"type":"assistant/chunk","seq":8,"time":1784821263288,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} +{"type":"assistant/chunk","seq":9,"time":1783860680779,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":10,"time":1783860680782,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":11,"time":1783860680782,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} +{"type":"assistant/chunk","seq":12,"time":1783860680782,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} +{"type":"assistant/chunk","seq":13,"time":1783860680830,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" specific"}}} +{"type":"assistant/chunk","seq":14,"time":1783860680831,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} +{"type":"assistant/chunk","seq":15,"time":1783860680831,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":16,"time":1783860680859,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" `"}}} +{"type":"assistant/chunk","seq":17,"time":1783860680859,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"sand"}}} +{"type":"assistant/chunk","seq":18,"time":1783860680868,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} +{"type":"assistant/chunk","seq":19,"time":1783860680871,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_per"}}} +{"type":"assistant/chunk","seq":20,"time":1783860680871,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"missions"}}} +{"type":"assistant/chunk","seq":21,"time":1783860680872,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"`"}}} +{"type":"assistant/chunk","seq":22,"time":1783860680872,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" set"}}} +{"type":"assistant/chunk","seq":23,"time":1783860680902,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":24,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" `"}}} +{"type":"assistant/chunk","seq":25,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"danger"}}} +{"type":"assistant/chunk","seq":26,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-full"}}} +{"type":"assistant/chunk","seq":27,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"-access"}}} +{"type":"assistant/chunk","seq":28,"time":1783860680903,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"`"}}} +{"type":"assistant/chunk","seq":29,"time":1783860680937,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} +{"type":"assistant/chunk","seq":30,"time":1783860680938,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} +{"type":"assistant/chunk","seq":31,"time":1783860680938,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" specific"}}} +{"type":"assistant/chunk","seq":32,"time":1783860680956,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" justification"}}} +{"type":"assistant/chunk","seq":33,"time":1783860680958,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":34,"time":1783860680958,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" They"}}} +{"type":"assistant/chunk","seq":35,"time":1783860680958,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" explicitly"}}} +{"type":"assistant/chunk","seq":36,"time":1783860680985,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" said"}}} +{"type":"assistant/chunk","seq":37,"time":1783860680985,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" NOT"}}} +{"type":"assistant/chunk","seq":38,"time":1783860681022,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":39,"time":1783860681024,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} +{"type":"assistant/chunk","seq":40,"time":1783860681024,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} +{"type":"assistant/chunk","seq":41,"time":1783860681024,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" without"}}} +{"type":"assistant/chunk","seq":42,"time":1783860681024,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" sand"}}} +{"type":"assistant/chunk","seq":43,"time":1783860681043,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} +{"type":"assistant/chunk","seq":44,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_per"}}} +{"type":"assistant/chunk","seq":45,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"missions"}}} +{"type":"assistant/chunk","seq":46,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" first"}}} +{"type":"assistant/chunk","seq":47,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":48,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} +{"type":"assistant/chunk","seq":49,"time":1783860681091,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":50,"time":1783860681107,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" do"}}} +{"type":"assistant/chunk","seq":51,"time":1783860681107,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} +{"type":"assistant/chunk","seq":52,"time":1783860681108,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" that"}}} +{"type":"assistant/chunk","seq":53,"time":1783860681138,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":54,"time":1783860681138,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":55,"time":1783860681251,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":""}}} +{"type":"assistant/chunk","seq":56,"time":1783860681251,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"{"}}} +{"type":"assistant/chunk","seq":57,"time":1783860681251,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":58,"time":1783860681251,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"command"}}} +{"type":"assistant/chunk","seq":59,"time":1783860681252,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":60,"time":1783860681252,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":61,"time":1783860681252,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":62,"time":1783860681252,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"printf"}}} +{"type":"assistant/chunk","seq":63,"time":1783860681280,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" '"}}} +{"type":"assistant/chunk","seq":64,"time":1783860681281,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"es"}}} +{"type":"assistant/chunk","seq":65,"time":1783860681281,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":66,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":67,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\\\\n"}}} +{"type":"assistant/chunk","seq":68,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"'"}}} +{"type":"assistant/chunk","seq":69,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" >"}}} +{"type":"assistant/chunk","seq":70,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" /"}}} +{"type":"assistant/chunk","seq":71,"time":1783860681324,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"tmp"}}} +{"type":"assistant/chunk","seq":72,"time":1783860681342,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"/d"}}} +{"type":"assistant/chunk","seq":73,"time":1783860681343,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"sh"}}} +{"type":"assistant/chunk","seq":74,"time":1783860681343,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-es"}}} +{"type":"assistant/chunk","seq":75,"time":1783860681343,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":76,"time":1783860681368,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":77,"time":1783860681371,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":".txt"}}} +{"type":"assistant/chunk","seq":78,"time":1783860681371,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" &&"}}} +{"type":"assistant/chunk","seq":79,"time":1783860681371,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" cat"}}} +{"type":"assistant/chunk","seq":80,"time":1783860681371,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" /"}}} +{"type":"assistant/chunk","seq":81,"time":1783860681400,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"tmp"}}} +{"type":"assistant/chunk","seq":82,"time":1783860681400,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"/d"}}} +{"type":"assistant/chunk","seq":83,"time":1783860681400,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"sh"}}} +{"type":"assistant/chunk","seq":84,"time":1783860681400,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-es"}}} +{"type":"assistant/chunk","seq":85,"time":1783860681401,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":86,"time":1783860681402,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":87,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":".txt"}}} +{"type":"assistant/chunk","seq":88,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" &&"}}} +{"type":"assistant/chunk","seq":89,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" rm"}}} +{"type":"assistant/chunk","seq":90,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" /"}}} +{"type":"assistant/chunk","seq":91,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"tmp"}}} +{"type":"assistant/chunk","seq":92,"time":1783860681432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"/d"}}} +{"type":"assistant/chunk","seq":93,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"sh"}}} +{"type":"assistant/chunk","seq":94,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-es"}}} +{"type":"assistant/chunk","seq":95,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":96,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":97,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":".txt"}}} +{"type":"assistant/chunk","seq":98,"time":1783860681456,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":99,"time":1783860681485,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":100,"time":1783860681519,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":101,"time":1783860681521,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"description"}}} +{"type":"assistant/chunk","seq":102,"time":1783860681521,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":103,"time":1783860681521,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":104,"time":1783860681521,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":105,"time":1783860681542,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"Write"}}} +{"type":"assistant/chunk","seq":106,"time":1783860681545,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" to"}}} +{"type":"assistant/chunk","seq":107,"time":1783860681545,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" /"}}} +{"type":"assistant/chunk","seq":108,"time":1783860681573,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"tmp"}}} +{"type":"assistant/chunk","seq":109,"time":1783860681573,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" and"}}} +{"type":"assistant/chunk","seq":110,"time":1783860681574,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" verify"}}} +{"type":"assistant/chunk","seq":111,"time":1783860681605,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":","}}} +{"type":"assistant/chunk","seq":112,"time":1783860681608,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" then"}}} +{"type":"assistant/chunk","seq":113,"time":1783860681630,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" clean"}}} +{"type":"assistant/chunk","seq":114,"time":1783860681632,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" up"}}} +{"type":"assistant/chunk","seq":115,"time":1783860681661,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":116,"time":1783860681661,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":117,"time":1783860681693,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":118,"time":1783860681693,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"sand"}}} +{"type":"assistant/chunk","seq":119,"time":1783860681693,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"box"}}} +{"type":"assistant/chunk","seq":120,"time":1783860681693,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"_per"}}} +{"type":"assistant/chunk","seq":121,"time":1783860681725,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"missions"}}} +{"type":"assistant/chunk","seq":122,"time":1783860681725,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":123,"time":1783860681726,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":124,"time":1783860681726,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":125,"time":1783860681751,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"danger"}}} +{"type":"assistant/chunk","seq":126,"time":1783860681753,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-full"}}} +{"type":"assistant/chunk","seq":127,"time":1783860681754,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"-access"}}} +{"type":"assistant/chunk","seq":128,"time":1783860681754,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":129,"time":1783860681754,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":130,"time":1783860681813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":131,"time":1783860681813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"just"}}} +{"type":"assistant/chunk","seq":132,"time":1783860681813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ification"}}} {"type":"assistant/chunk","seq":133,"time":1783860681813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":134,"time":1783860681815,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"just"}}} -{"type":"assistant/chunk","seq":135,"time":1783860681840,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"ification"}}} -{"type":"assistant/chunk","seq":136,"time":1783860681842,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":137,"time":1783860681842,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":138,"time":1783860681842,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":139,"time":1783860681842,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"the"}}} -{"type":"assistant/chunk","seq":140,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" user"}}} -{"type":"assistant/chunk","seq":141,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" asked"}}} -{"type":"assistant/chunk","seq":142,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" to"}}} -{"type":"assistant/chunk","seq":143,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" write"}}} -{"type":"assistant/chunk","seq":144,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" a"}}} -{"type":"assistant/chunk","seq":145,"time":1783860681872,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" file"}}} -{"type":"assistant/chunk","seq":146,"time":1783860681901,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" outside"}}} -{"type":"assistant/chunk","seq":147,"time":1783860681903,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":148,"time":1783860681967,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" workspace"}}} -{"type":"assistant/chunk","seq":149,"time":1783860681967,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":150,"time":1783860681967,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":151,"time":1783860681967,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run a specific command with `sandbox_permissions` set to `danger-full-access` and a specific justification. They explicitly said NOT to run it without sandbox_permissions first. Let me do exactly that."}}}} -{"type":"assistant/chunk","seq":152,"time":1783962246274,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write to /tmp and verify, then clean up\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}}}} -{"type":"assistant/chunk","seq":153,"time":1783962246274,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1509,"outputTokens":198,"cacheReadTokens":0,"reasoningTokens":48}}}} -{"type":"assistant/chunk","seq":154,"time":1783962246274,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":155,"time":1783962246274,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to run a specific command with `sandbox_permissions` set to `danger-full-access` and a specific justification. They explicitly said NOT to run it without sandbox_permissions first. Let me do exactly that."},{"type":"tool-call","id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write to /tmp and verify, then clean up\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":1509,"outputTokens":198,"cacheReadTokens":0,"reasoningTokens":48}},"sourceEventSeqs":[8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154],"surfaceOp":"append"} -{"type":"tool/call","seq":156,"time":1783962246274,"data":{"turn":1,"step":1,"callId":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write to /tmp and verify, then clean up\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}} -{"type":"approval/asked","seq":157,"time":1783962246275,"data":{"id":"e5cc84ef-8704-4cd9-8e47-897a0a51beb6","toolName":"bash","callId":"call_00_WB1vnPomi8yr6MlcFKTj7912","reason":"escalate sandbox to danger-full-access: the user asked to write a file outside the workspace"}} -{"type":"approval/decided","seq":158,"time":1783962246275,"data":{"id":"e5cc84ef-8704-4cd9-8e47-897a0a51beb6","outcome":"rejected"}} -{"type":"tool/result","seq":159,"time":1783962246275,"data":{"turn":1,"step":1,"callId":"call_00_WB1vnPomi8yr6MlcFKTj7912","content":[{"type":"text","text":"Error: the user rejected escalating this command to \"danger-full-access\""}],"isError":true},"sourceEventSeqs":[156],"surfaceOp":"append"} -{"type":"step/end","seq":160,"time":1783962246276,"data":{"turn":1,"step":1}} -{"type":"step/start","seq":161,"time":1783962246276,"data":{"turn":1,"step":2}} -{"type":"assistant/chunk","seq":162,"time":1783860683140,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":163,"time":1783860683141,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":164,"time":1783860683141,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":165,"time":1783860683170,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" rejected"}}} -{"type":"assistant/chunk","seq":166,"time":1783860683170,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":167,"time":1783860683170,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" escalation"}}} -{"type":"assistant/chunk","seq":168,"time":1783860683205,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":169,"time":1783860683208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" As"}}} -{"type":"assistant/chunk","seq":170,"time":1783860683208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" instructed"}}} -{"type":"assistant/chunk","seq":171,"time":1783860683208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":172,"time":1783860683208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":173,"time":1783860683230,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" will"}}} -{"type":"assistant/chunk","seq":174,"time":1783860683232,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" not"}}} -{"type":"assistant/chunk","seq":175,"time":1783860683233,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" ret"}}} -{"type":"assistant/chunk","seq":176,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ry"}}} -{"type":"assistant/chunk","seq":177,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":178,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" will"}}} -{"type":"assistant/chunk","seq":179,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" not"}}} -{"type":"assistant/chunk","seq":180,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" work"}}} -{"type":"assistant/chunk","seq":181,"time":1783860683294,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" around"}}} -{"type":"assistant/chunk","seq":182,"time":1783860683296,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} -{"type":"assistant/chunk","seq":183,"time":1783860683296,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" —"}}} -{"type":"assistant/chunk","seq":184,"time":1783860683317,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" just"}}} -{"type":"assistant/chunk","seq":185,"time":1783860683317,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" explain"}}} -{"type":"assistant/chunk","seq":186,"time":1783860683317,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" in"}}} -{"type":"assistant/chunk","seq":187,"time":1783860683318,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" one"}}} -{"type":"assistant/chunk","seq":188,"time":1783860683318,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" short"}}} -{"type":"assistant/chunk","seq":189,"time":1783860683318,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" sentence"}}} -{"type":"assistant/chunk","seq":190,"time":1783860683347,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":191,"time":1783860683347,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" stop"}}} -{"type":"assistant/chunk","seq":192,"time":1783860683349,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":193,"time":1783860683349,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":194,"time":1783860683375,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"The"}}} -{"type":"assistant/chunk","seq":195,"time":1783860683376,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" user"}}} -{"type":"assistant/chunk","seq":196,"time":1783860683409,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" rejected"}}} -{"type":"assistant/chunk","seq":197,"time":1783860683410,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":198,"time":1783860683410,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" permission"}}} -{"type":"assistant/chunk","seq":199,"time":1783860683435,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" escalation"}}} -{"type":"assistant/chunk","seq":200,"time":1783860683437,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":201,"time":1783860683437,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" so"}}} -{"type":"assistant/chunk","seq":202,"time":1783860683462,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" this"}}} -{"type":"assistant/chunk","seq":203,"time":1783860683464,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" command"}}} -{"type":"assistant/chunk","seq":204,"time":1783860683464,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" cannot"}}} -{"type":"assistant/chunk","seq":205,"time":1783860683506,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" be"}}} -{"type":"assistant/chunk","seq":206,"time":1783860683506,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" run"}}} -{"type":"assistant/chunk","seq":207,"time":1783860683506,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"."}}} -{"type":"assistant/chunk","seq":208,"time":1783860683506,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user rejected the escalation. As instructed, I will not retry and will not work around it — just explain in one short sentence and stop."}}}} -{"type":"assistant/chunk","seq":209,"time":1783962246279,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The user rejected the permission escalation, so this command cannot be run."}}}} -{"type":"assistant/chunk","seq":210,"time":1783962246279,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":69,"outputTokens":45,"cacheReadTokens":1664,"reasoningTokens":30}}}} -{"type":"assistant/chunk","seq":211,"time":1783962246279,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":212,"time":1783962246279,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The user rejected the escalation. As instructed, I will not retry and will not work around it — just explain in one short sentence and stop."},{"type":"text","text":"The user rejected the permission escalation, so this command cannot be run."}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":69,"outputTokens":45,"cacheReadTokens":1664,"reasoningTokens":30}},"sourceEventSeqs":[162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211],"surfaceOp":"append"} -{"type":"step/end","seq":213,"time":1783962246279,"data":{"turn":1,"step":2}} -{"type":"turn/end","seq":214,"time":1783962246279,"data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"assistant/chunk","seq":134,"time":1783860681813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":135,"time":1783860681815,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":136,"time":1783860681840,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"the"}}} +{"type":"assistant/chunk","seq":137,"time":1783860681842,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" user"}}} +{"type":"assistant/chunk","seq":138,"time":1783860681842,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" asked"}}} +{"type":"assistant/chunk","seq":139,"time":1783860681842,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" to"}}} +{"type":"assistant/chunk","seq":140,"time":1783860681842,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" write"}}} +{"type":"assistant/chunk","seq":141,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" a"}}} +{"type":"assistant/chunk","seq":142,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" file"}}} +{"type":"assistant/chunk","seq":143,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" outside"}}} +{"type":"assistant/chunk","seq":144,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" the"}}} +{"type":"assistant/chunk","seq":145,"time":1783860681870,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":" workspace"}}} +{"type":"assistant/chunk","seq":146,"time":1783860681872,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":147,"time":1783860681901,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","argumentsDelta":"}"}}} +{"type":"assistant/chunk","seq":148,"time":1783860681903,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run a specific command with `sandbox_permissions` set to `danger-full-access` and a specific justification. They explicitly said NOT to run it without sandbox_permissions first. Let me do exactly that."}}}} +{"type":"assistant/chunk","seq":149,"time":1783860681967,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write to /tmp and verify, then clean up\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}}}} +{"type":"assistant/chunk","seq":150,"time":1783860681967,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1509,"outputTokens":198,"cacheReadTokens":0,"reasoningTokens":48}}}} +{"type":"assistant/chunk","seq":151,"time":1783860681967,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":152,"time":1784821263293,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to run a specific command with `sandbox_permissions` set to `danger-full-access` and a specific justification. They explicitly said NOT to run it without sandbox_permissions first. Let me do exactly that."},{"type":"tool-call","id":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write to /tmp and verify, then clean up\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":1509,"outputTokens":198,"cacheReadTokens":0,"reasoningTokens":48}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151],"surfaceOp":"append"} +{"type":"tool/call","seq":153,"time":1784821263294,"data":{"turn":1,"step":1,"callId":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write to /tmp and verify, then clean up\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}} +{"type":"approval/asked","seq":154,"time":1784821263300,"data":{"id":"ad9d426a-bcd7-42df-8ad4-9f4ae8eb160c","toolName":"bash","callId":"call_00_WB1vnPomi8yr6MlcFKTj7912","reason":"escalate sandbox to danger-full-access: the user asked to write a file outside the workspace"}} +{"type":"approval/decided","seq":155,"time":1784821263301,"data":{"id":"ad9d426a-bcd7-42df-8ad4-9f4ae8eb160c","outcome":"rejected"}} +{"type":"tool/result","seq":156,"time":1784821263302,"data":{"turn":1,"step":1,"callId":"call_00_WB1vnPomi8yr6MlcFKTj7912","content":[{"type":"text","text":"Error: the user rejected escalating this command to \"danger-full-access\""}],"isError":true},"sourceEventSeqs":[153],"surfaceOp":"append"} +{"type":"step/end","seq":157,"time":1784821263307,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":158,"time":1784821263307,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":159,"time":1784821263313,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":160,"time":1784821263313,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":161,"time":1784821263313,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} +{"type":"assistant/chunk","seq":162,"time":1784821263313,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" rejected"}}} +{"type":"assistant/chunk","seq":163,"time":1783860683140,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} +{"type":"assistant/chunk","seq":164,"time":1783860683141,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" escalation"}}} +{"type":"assistant/chunk","seq":165,"time":1783860683141,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":166,"time":1783860683170,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" As"}}} +{"type":"assistant/chunk","seq":167,"time":1783860683170,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" instructed"}}} +{"type":"assistant/chunk","seq":168,"time":1783860683170,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} +{"type":"assistant/chunk","seq":169,"time":1783860683205,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} +{"type":"assistant/chunk","seq":170,"time":1783860683208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" will"}}} +{"type":"assistant/chunk","seq":171,"time":1783860683208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" not"}}} +{"type":"assistant/chunk","seq":172,"time":1783860683208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" ret"}}} +{"type":"assistant/chunk","seq":173,"time":1783860683208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ry"}}} +{"type":"assistant/chunk","seq":174,"time":1783860683230,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} +{"type":"assistant/chunk","seq":175,"time":1783860683232,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" will"}}} +{"type":"assistant/chunk","seq":176,"time":1783860683233,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" not"}}} +{"type":"assistant/chunk","seq":177,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" work"}}} +{"type":"assistant/chunk","seq":178,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" around"}}} +{"type":"assistant/chunk","seq":179,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} +{"type":"assistant/chunk","seq":180,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" —"}}} +{"type":"assistant/chunk","seq":181,"time":1783860683260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" just"}}} +{"type":"assistant/chunk","seq":182,"time":1783860683294,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" explain"}}} +{"type":"assistant/chunk","seq":183,"time":1783860683296,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" in"}}} +{"type":"assistant/chunk","seq":184,"time":1783860683296,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" one"}}} +{"type":"assistant/chunk","seq":185,"time":1783860683317,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" short"}}} +{"type":"assistant/chunk","seq":186,"time":1783860683317,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" sentence"}}} +{"type":"assistant/chunk","seq":187,"time":1783860683317,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} +{"type":"assistant/chunk","seq":188,"time":1783860683318,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" stop"}}} +{"type":"assistant/chunk","seq":189,"time":1783860683318,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":190,"time":1783860683318,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} +{"type":"assistant/chunk","seq":191,"time":1783860683347,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"The"}}} +{"type":"assistant/chunk","seq":192,"time":1783860683347,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" user"}}} +{"type":"assistant/chunk","seq":193,"time":1783860683349,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" rejected"}}} +{"type":"assistant/chunk","seq":194,"time":1783860683349,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" the"}}} +{"type":"assistant/chunk","seq":195,"time":1783860683375,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" permission"}}} +{"type":"assistant/chunk","seq":196,"time":1783860683376,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" escalation"}}} +{"type":"assistant/chunk","seq":197,"time":1783860683409,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":","}}} +{"type":"assistant/chunk","seq":198,"time":1783860683410,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" so"}}} +{"type":"assistant/chunk","seq":199,"time":1783860683410,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" this"}}} +{"type":"assistant/chunk","seq":200,"time":1783860683435,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" command"}}} +{"type":"assistant/chunk","seq":201,"time":1783860683437,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" cannot"}}} +{"type":"assistant/chunk","seq":202,"time":1783860683437,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" be"}}} +{"type":"assistant/chunk","seq":203,"time":1783860683462,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":" run"}}} +{"type":"assistant/chunk","seq":204,"time":1783860683464,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"."}}} +{"type":"assistant/chunk","seq":205,"time":1783860683464,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user rejected the escalation. As instructed, I will not retry and will not work around it — just explain in one short sentence and stop."}}}} +{"type":"assistant/chunk","seq":206,"time":1783860683506,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The user rejected the permission escalation, so this command cannot be run."}}}} +{"type":"assistant/chunk","seq":207,"time":1783860683506,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":69,"outputTokens":45,"cacheReadTokens":1664,"reasoningTokens":30}}}} +{"type":"assistant/chunk","seq":208,"time":1783860683506,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":209,"time":1784821263315,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The user rejected the escalation. As instructed, I will not retry and will not work around it — just explain in one short sentence and stop."},{"type":"text","text":"The user rejected the permission escalation, so this command cannot be run."}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":69,"outputTokens":45,"cacheReadTokens":1664,"reasoningTokens":30}},"sourceEventSeqs":[159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208],"surfaceOp":"append"} +{"type":"step/end","seq":210,"time":1784821263321,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":211,"time":1784821263321,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/escalation-rejected/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/escalation-rejected/stdout.expected.jsonl index 409bbb57a1..23d260507b 100644 --- a/examples/acp-agent/tests/snapshots/escalation-rejected/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/escalation-rejected/stdout.expected.jsonl @@ -1,101 +1,5 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"workspace-write","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"The sandbox already denied writing","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" specific"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"sand"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"box"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_per"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"missions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" set"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"danger"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-full"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-access"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" specific"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" justification"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" They"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" explicitly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" said"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" NOT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" without"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sand"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"box"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_per"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"missions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" do"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_WB1vnPomi8yr6MlcFKTj7912","title":"printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt","kind":"execute","status":"in_progress","rawInput":"printf 'escalated\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt","content":[{"type":"content","content":{"type":"text","text":"Write to /tmp and verify, then clean up"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","id":1,"method":"session/request_permission","params":{"sessionId":"{{sessionId}}","toolCall":{"toolCallId":"call_00_WB1vnPomi8yr6MlcFKTj7912"},"options":[{"optionId":"allow-once","name":"Allow once","kind":"allow_once"},{"optionId":"reject-once","name":"Reject","kind":"reject_once"}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_WB1vnPomi8yr6MlcFKTj7912","status":"failed","content":[{"type":"content","content":{"type":"text","text":"```console\nError: the user rejected escalating this command to \"danger-full-access\"\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" rejected"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" escalation"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" As"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instructed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" will"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ret"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ry"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" will"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" work"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" around"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" —"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" explain"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" one"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" short"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sentence"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" rejected"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" permission"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" escalation"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" so"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" cannot"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" be"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The user rejected the permission escalation, so this command cannot be run."}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl b/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl index d0bd2d5bef..bcdd4c7b99 100644 --- a/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl @@ -130,7 +130,7 @@ {"type":"assistant/chunk","seq":128,"time":1783352087469,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":129,"time":1783352087469,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"Now I need to replace \"DEBUG\" with \"RELEASE\" using the edit tool."},{"type":"tool-call","id":"call_00_vOytneZ0XpsLslEEJAxR6398","name":"edit","arguments":"{\"file_path\": \"config.txt\", \"old_string\": \"DEBUG\", \"new_string\": \"RELEASE\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":241,"outputTokens":98,"cacheReadTokens":2816,"reasoningTokens":18}},"sourceEventSeqs":[74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128],"surfaceOp":"append"} {"type":"tool/call","seq":130,"time":1783352087469,"data":{"turn":1,"step":2,"callId":"call_00_vOytneZ0XpsLslEEJAxR6398","name":"edit","arguments":"{\"file_path\": \"config.txt\", \"old_string\": \"DEBUG\", \"new_string\": \"RELEASE\"}"}} -{"type":"tool/result","seq":131,"time":1783352087476,"data":{"turn":1,"step":2,"callId":"call_00_vOytneZ0XpsLslEEJAxR6398","content":[{"type":"text","text":"The file /tmp/acp-snap-cwd-0BxHdV/config.txt has been updated successfully."}],"isError":false,"meta":{"diffs":[{"path":"config.txt","oldText":"mode=DEBUG\nlevel=info","newText":"mode=RELEASE\nlevel=info"}]}},"sourceEventSeqs":[130],"surfaceOp":"append"} +{"type":"tool/result","seq":131,"time":1783352087476,"data":{"turn":1,"step":2,"callId":"call_00_vOytneZ0XpsLslEEJAxR6398","content":[{"type":"text","text":"The file /private/tmp/acp-snap-cwd-0BxHdV/config.txt has been updated successfully."}],"isError":false,"meta":{"diffs":[{"path":"config.txt","oldText":"mode=DEBUG\nlevel=info","newText":"mode=RELEASE\nlevel=info"}]}},"sourceEventSeqs":[130],"surfaceOp":"append"} {"type":"step/end","seq":132,"time":1783352087477,"data":{"turn":1,"step":2}} {"type":"step/start","seq":133,"time":1783352087477,"data":{"turn":1,"step":3}} {"type":"assistant/chunk","seq":134,"time":1783352088286,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-edit/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/fs-edit/stdout.expected.jsonl index b589e427d0..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/fs-edit/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-edit/stdout.expected.jsonl @@ -1,89 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"First use the read tool","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" config"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" current"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" directory"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" replace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" DEBUG"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" RE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LEASE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"3"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" start"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_S6krdIDHoSCGWv7WnXX97617","title":"Read config.txt","kind":"read","status":"in_progress","locations":[{"path":"config.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_S6krdIDHoSCGWv7WnXX97617","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/config.txt</path>\n<type>file</type>\n<content>\n1: mode=DEBUG\n2: level=info\n\n(End of file - total 2 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" replace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"DEBUG"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"RE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LEASE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_vOytneZ0XpsLslEEJAxR6398","title":"Edit config.txt","kind":"edit","status":"in_progress","locations":[{"path":"config.txt"}],"content":[{"type":"diff","path":"config.txt","oldText":"DEBUG","newText":"RELEASE"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_vOytneZ0XpsLslEEJAxR6398","status":"completed","content":[{"type":"diff","path":"config.txt","oldText":"mode=DEBUG\nlevel=info","newText":"mode=RELEASE\nlevel=info"}],"title":"Edit config.txt"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Done"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/fs-escalation-approved/input.json b/examples/acp-agent/tests/snapshots/fs-escalation-approved/input.json index d6d8d2b8c6..c39c10d94d 100644 --- a/examples/acp-agent/tests/snapshots/fs-escalation-approved/input.json +++ b/examples/acp-agent/tests/snapshots/fs-escalation-approved/input.json @@ -2,7 +2,6 @@ "steps": [ { "op": "initialize" }, { "op": "newSession" }, - { "op": "setConfigOption", "configId": "permission", "value": "workspace-write" }, { "op": "prompt", "text": "Use the write tool (NOT bash) to create escalated.md in the current directory containing exactly the single line: escalated. An equivalent write was denied earlier, so make this one single write call with sandbox_permissions set to danger-full-access and the justification 'the user asked to escalate this write'. Do not call write without sandbox_permissions first. I will approve the permission prompt. After the result, reply with exactly the single word DONE." } ], "permissionAnswers": [ diff --git a/examples/acp-agent/tests/snapshots/fs-escalation-approved/session.jsonl b/examples/acp-agent/tests/snapshots/fs-escalation-approved/session.jsonl index 918b3ab4d5..180ef6c704 100644 --- a/examples/acp-agent/tests/snapshots/fs-escalation-approved/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-escalation-approved/session.jsonl @@ -1,128 +1,125 @@ {"type":"session","version":0,"id":"977a4820-f609-4b48-9039-adcdd921c5fe","createdAt":1784045702340,"cwd":"/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-vmEGzd","delegationDepth":0} {"type":"turn/start","seq":0,"time":1784045702342,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"permission/preset","seq":1,"time":1784045702343,"data":{"preset":"workspace-write"}} -{"type":"sandbox/mode","seq":2,"time":1784045702343,"data":{"mode":"workspace-write"}} -{"type":"approval/policy","seq":3,"time":1784045702343,"data":{"policy":"ask"}} -{"type":"user/message","seq":4,"time":1784045702343,"data":{"content":[{"type":"text","text":"Use the write tool (NOT bash) to create escalated.md in the current directory containing exactly the single line: escalated. An equivalent write was denied earlier, so make this one single write call with sandbox_permissions set to danger-full-access and the justification 'the user asked to escalate this write'. Do not call write without sandbox_permissions first. I will approve the permission prompt. After the result, reply with exactly the single word DONE."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"session/title","seq":5,"time":1784045702343,"data":{"title":"Use the write tool (NOT","messageSeqs":[4],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":6,"time":1784045702345,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":7,"time":1784045702345,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"assistant/chunk","seq":8,"time":1784045703046,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":9,"time":1784045703046,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":10,"time":1784045703162,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":11,"time":1784045703172,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":12,"time":1784045703172,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":13,"time":1784045703173,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":14,"time":1784045703173,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" create"}}} -{"type":"assistant/chunk","seq":15,"time":1784045703173,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":16,"time":1784045703173,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":17,"time":1784045703199,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" using"}}} -{"type":"assistant/chunk","seq":18,"time":1784045703225,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":19,"time":1784045703251,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" write"}}} -{"type":"assistant/chunk","seq":20,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" tool"}}} -{"type":"assistant/chunk","seq":21,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":22,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" sand"}}} -{"type":"assistant/chunk","seq":23,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} -{"type":"assistant/chunk","seq":24,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_per"}}} -{"type":"assistant/chunk","seq":25,"time":1784045703277,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"missions"}}} -{"type":"assistant/chunk","seq":26,"time":1784045703278,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":27,"time":1784045703278,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} -{"type":"assistant/chunk","seq":28,"time":1784045703278,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":29,"time":1784045703278,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" do"}}} -{"type":"assistant/chunk","seq":30,"time":1784045703304,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" that"}}} -{"type":"assistant/chunk","seq":31,"time":1784045703304,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":32,"time":1784045703356,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":33,"time":1784045703356,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":34,"time":1784045703381,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"{"}}} +{"type":"user/message","seq":1,"time":1784821264846,"data":{"content":[{"type":"text","text":"Use the write tool (NOT bash) to create escalated.md in the current directory containing exactly the single line: escalated. An equivalent write was denied earlier, so make this one single write call with sandbox_permissions set to danger-full-access and the justification 'the user asked to escalate this write'. Do not call write without sandbox_permissions first. I will approve the permission prompt. After the result, reply with exactly the single word DONE."}],"source":{"kind":"user"}},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":1784821264846,"data":{"title":"Use the write tool (NOT","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":1784821264855,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":1784821264855,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"assistant/chunk","seq":5,"time":1784821264889,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":6,"time":1784821264889,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":7,"time":1784821264889,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} +{"type":"assistant/chunk","seq":8,"time":1784821264889,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} +{"type":"assistant/chunk","seq":9,"time":1784045703046,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":10,"time":1784045703046,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":11,"time":1784045703162,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" create"}}} +{"type":"assistant/chunk","seq":12,"time":1784045703172,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} +{"type":"assistant/chunk","seq":13,"time":1784045703172,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} +{"type":"assistant/chunk","seq":14,"time":1784045703173,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" using"}}} +{"type":"assistant/chunk","seq":15,"time":1784045703173,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} +{"type":"assistant/chunk","seq":16,"time":1784045703173,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" write"}}} +{"type":"assistant/chunk","seq":17,"time":1784045703173,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" tool"}}} +{"type":"assistant/chunk","seq":18,"time":1784045703199,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":19,"time":1784045703225,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" sand"}}} +{"type":"assistant/chunk","seq":20,"time":1784045703251,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"box"}}} +{"type":"assistant/chunk","seq":21,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_per"}}} +{"type":"assistant/chunk","seq":22,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"missions"}}} +{"type":"assistant/chunk","seq":23,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":24,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} +{"type":"assistant/chunk","seq":25,"time":1784045703252,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":26,"time":1784045703277,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" do"}}} +{"type":"assistant/chunk","seq":27,"time":1784045703278,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" that"}}} +{"type":"assistant/chunk","seq":28,"time":1784045703278,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":29,"time":1784045703278,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":30,"time":1784045703278,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":""}}} +{"type":"assistant/chunk","seq":31,"time":1784045703304,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"{"}}} +{"type":"assistant/chunk","seq":32,"time":1784045703304,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":33,"time":1784045703356,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"file"}}} +{"type":"assistant/chunk","seq":34,"time":1784045703356,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"_path"}}} {"type":"assistant/chunk","seq":35,"time":1784045703381,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":36,"time":1784045703381,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"file"}}} -{"type":"assistant/chunk","seq":37,"time":1784045703405,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"_path"}}} -{"type":"assistant/chunk","seq":38,"time":1784045703406,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":39,"time":1784045703406,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":40,"time":1784045703406,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":41,"time":1784045703431,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"es"}}} -{"type":"assistant/chunk","seq":42,"time":1784045703432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":43,"time":1784045703432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":44,"time":1784045703432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":".md"}}} -{"type":"assistant/chunk","seq":45,"time":1784045703432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":46,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":47,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":48,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"content"}}} -{"type":"assistant/chunk","seq":49,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":50,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":51,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":52,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"es"}}} -{"type":"assistant/chunk","seq":53,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"cal"}}} -{"type":"assistant/chunk","seq":54,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"ated"}}} -{"type":"assistant/chunk","seq":55,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":56,"time":1784045703565,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":57,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":58,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"sand"}}} -{"type":"assistant/chunk","seq":59,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"box"}}} -{"type":"assistant/chunk","seq":60,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"_per"}}} -{"type":"assistant/chunk","seq":61,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"missions"}}} -{"type":"assistant/chunk","seq":62,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":63,"time":1784045703591,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":64,"time":1784045703591,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":65,"time":1784045703591,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"danger"}}} -{"type":"assistant/chunk","seq":66,"time":1784045703591,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"-full"}}} -{"type":"assistant/chunk","seq":67,"time":1784045703617,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"-access"}}} -{"type":"assistant/chunk","seq":68,"time":1784045703618,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":69,"time":1784045703644,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":70,"time":1784045703645,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":71,"time":1784045703645,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"just"}}} -{"type":"assistant/chunk","seq":72,"time":1784045703645,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"ification"}}} -{"type":"assistant/chunk","seq":73,"time":1784045703669,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":74,"time":1784045703669,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":75,"time":1784045703669,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":76,"time":1784045703669,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"the"}}} -{"type":"assistant/chunk","seq":77,"time":1784045703696,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" user"}}} -{"type":"assistant/chunk","seq":78,"time":1784045703696,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" asked"}}} -{"type":"assistant/chunk","seq":79,"time":1784045703696,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" to"}}} -{"type":"assistant/chunk","seq":80,"time":1784045703696,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" escalate"}}} -{"type":"assistant/chunk","seq":81,"time":1784045703724,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" this"}}} -{"type":"assistant/chunk","seq":82,"time":1784045703724,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" write"}}} -{"type":"assistant/chunk","seq":83,"time":1784045703724,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":84,"time":1784045703749,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":85,"time":1784045703776,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to create a file using the write tool with sandbox_permissions. Let me do that."}}}} -{"type":"assistant/chunk","seq":86,"time":1784045703776,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","arguments":"{\"file_path\": \"escalated.md\", \"content\": \"escalated\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to escalate this write\"}"}}}} -{"type":"assistant/chunk","seq":87,"time":1784045703776,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3871,"outputTokens":132,"cacheReadTokens":0,"reasoningTokens":23}}}} -{"type":"assistant/chunk","seq":88,"time":1784045703776,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":89,"time":1784045703780,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to create a file using the write tool with sandbox_permissions. Let me do that."},{"type":"tool-call","id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","arguments":"{\"file_path\": \"escalated.md\", \"content\": \"escalated\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to escalate this write\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":3871,"outputTokens":132,"cacheReadTokens":0,"reasoningTokens":23}},"sourceEventSeqs":[8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88],"surfaceOp":"append"} -{"type":"tool/call","seq":90,"time":1784045703780,"data":{"turn":1,"step":1,"callId":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","arguments":"{\"file_path\": \"escalated.md\", \"content\": \"escalated\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to escalate this write\"}"}} -{"type":"approval/asked","seq":91,"time":1784045703782,"data":{"id":"d7250dff-fc08-4163-9b51-f43f08d6f36f","toolName":"write","callId":"call_00_Fnymmavpr4klMDy4Fdej3227","reason":"escalate sandbox to danger-full-access: the user asked to escalate this write"}} -{"type":"approval/decided","seq":92,"time":1784045703786,"data":{"id":"d7250dff-fc08-4163-9b51-f43f08d6f36f","outcome":"allowed-once"}} -{"type":"tool/result","seq":93,"time":1784045703798,"data":{"turn":1,"step":1,"callId":"call_00_Fnymmavpr4klMDy4Fdej3227","content":[{"type":"text","text":"<path>/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-vmEGzd/escalated.md</path>\n<type>file</type>\n<content>\nCreated file\n</content>"}],"isError":false,"meta":{"diffs":[]}},"sourceEventSeqs":[90],"surfaceOp":"append"} -{"type":"step/end","seq":94,"time":1784045703798,"data":{"turn":1,"step":1}} -{"type":"step/start","seq":95,"time":1784045703799,"data":{"turn":1,"step":2}} -{"type":"assistant/chunk","seq":96,"time":1784045704512,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":97,"time":1784045704512,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":98,"time":1784045704620,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":99,"time":1784045704645,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" was"}}} -{"type":"assistant/chunk","seq":100,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" created"}}} -{"type":"assistant/chunk","seq":101,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" successfully"}}} -{"type":"assistant/chunk","seq":102,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":103,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" The"}}} -{"type":"assistant/chunk","seq":104,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":105,"time":1784045704672,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" asked"}}} -{"type":"assistant/chunk","seq":106,"time":1784045704673,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":107,"time":1784045704673,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":108,"time":1784045704673,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":109,"time":1784045704699,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":110,"time":1784045704699,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} -{"type":"assistant/chunk","seq":111,"time":1784045704699,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":112,"time":1784045704726,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" single"}}} -{"type":"assistant/chunk","seq":113,"time":1784045704726,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" word"}}} -{"type":"assistant/chunk","seq":114,"time":1784045704726,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" D"}}} -{"type":"assistant/chunk","seq":115,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} -{"type":"assistant/chunk","seq":116,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":117,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":118,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} -{"type":"assistant/chunk","seq":119,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} -{"type":"assistant/chunk","seq":120,"time":1784045704755,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The file was created successfully. The user asked me to reply with exactly the single word DONE."}}}} -{"type":"assistant/chunk","seq":121,"time":1784045704755,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} -{"type":"assistant/chunk","seq":122,"time":1784045704755,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":107,"outputTokens":23,"cacheReadTokens":3968,"reasoningTokens":20}}}} -{"type":"assistant/chunk","seq":123,"time":1784045704755,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":124,"time":1784045704755,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The file was created successfully. The user asked me to reply with exactly the single word DONE."},{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":107,"outputTokens":23,"cacheReadTokens":3968,"reasoningTokens":20}},"sourceEventSeqs":[96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123],"surfaceOp":"append"} -{"type":"step/end","seq":125,"time":1784045704755,"data":{"turn":1,"step":2}} -{"type":"turn/end","seq":126,"time":1784045704756,"data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"assistant/chunk","seq":36,"time":1784045703381,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":37,"time":1784045703381,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":38,"time":1784045703405,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"es"}}} +{"type":"assistant/chunk","seq":39,"time":1784045703406,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":40,"time":1784045703406,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":41,"time":1784045703406,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":".md"}}} +{"type":"assistant/chunk","seq":42,"time":1784045703431,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":43,"time":1784045703432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":44,"time":1784045703432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":45,"time":1784045703432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"content"}}} +{"type":"assistant/chunk","seq":46,"time":1784045703432,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":47,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":48,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":49,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"es"}}} +{"type":"assistant/chunk","seq":50,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"cal"}}} +{"type":"assistant/chunk","seq":51,"time":1784045703483,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"ated"}}} +{"type":"assistant/chunk","seq":52,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":53,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":54,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":55,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"sand"}}} +{"type":"assistant/chunk","seq":56,"time":1784045703509,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"box"}}} +{"type":"assistant/chunk","seq":57,"time":1784045703565,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"_per"}}} +{"type":"assistant/chunk","seq":58,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"missions"}}} +{"type":"assistant/chunk","seq":59,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":60,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":61,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":62,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"danger"}}} +{"type":"assistant/chunk","seq":63,"time":1784045703566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"-full"}}} +{"type":"assistant/chunk","seq":64,"time":1784045703591,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"-access"}}} +{"type":"assistant/chunk","seq":65,"time":1784045703591,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":66,"time":1784045703591,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":67,"time":1784045703591,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":68,"time":1784045703617,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"just"}}} +{"type":"assistant/chunk","seq":69,"time":1784045703618,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"ification"}}} +{"type":"assistant/chunk","seq":70,"time":1784045703644,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":71,"time":1784045703645,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":72,"time":1784045703645,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":73,"time":1784045703645,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"the"}}} +{"type":"assistant/chunk","seq":74,"time":1784045703669,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" user"}}} +{"type":"assistant/chunk","seq":75,"time":1784045703669,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" asked"}}} +{"type":"assistant/chunk","seq":76,"time":1784045703669,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" to"}}} +{"type":"assistant/chunk","seq":77,"time":1784045703669,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" escalate"}}} +{"type":"assistant/chunk","seq":78,"time":1784045703696,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" this"}}} +{"type":"assistant/chunk","seq":79,"time":1784045703696,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":" write"}}} +{"type":"assistant/chunk","seq":80,"time":1784045703696,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":81,"time":1784045703696,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","argumentsDelta":"}"}}} +{"type":"assistant/chunk","seq":82,"time":1784045703724,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to create a file using the write tool with sandbox_permissions. Let me do that."}}}} +{"type":"assistant/chunk","seq":83,"time":1784045703724,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","arguments":"{\"file_path\": \"escalated.md\", \"content\": \"escalated\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to escalate this write\"}"}}}} +{"type":"assistant/chunk","seq":84,"time":1784045703724,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3871,"outputTokens":132,"cacheReadTokens":0,"reasoningTokens":23}}}} +{"type":"assistant/chunk","seq":85,"time":1784045703749,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":86,"time":1784821264893,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to create a file using the write tool with sandbox_permissions. Let me do that."},{"type":"tool-call","id":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","arguments":"{\"file_path\": \"escalated.md\", \"content\": \"escalated\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to escalate this write\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":3871,"outputTokens":132,"cacheReadTokens":0,"reasoningTokens":23}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85],"surfaceOp":"append"} +{"type":"tool/call","seq":87,"time":1784821264893,"data":{"turn":1,"step":1,"callId":"call_00_Fnymmavpr4klMDy4Fdej3227","name":"write","arguments":"{\"file_path\": \"escalated.md\", \"content\": \"escalated\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to escalate this write\"}"}} +{"type":"approval/asked","seq":88,"time":1784821264898,"data":{"id":"9e3fc97b-19e4-44a1-8ff1-795683948bcd","toolName":"write","callId":"call_00_Fnymmavpr4klMDy4Fdej3227","reason":"escalate sandbox to danger-full-access: the user asked to escalate this write"}} +{"type":"approval/decided","seq":89,"time":1784821264898,"data":{"id":"9e3fc97b-19e4-44a1-8ff1-795683948bcd","outcome":"allowed-once"}} +{"type":"tool/result","seq":90,"time":1784821264906,"data":{"turn":1,"step":1,"callId":"call_00_Fnymmavpr4klMDy4Fdej3227","content":[{"type":"text","text":"<path>/private/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-vmEGzd/escalated.md</path>\n<type>file</type>\n<content>\nCreated file\n</content>"}],"isError":false,"meta":{"diffs":[]}},"sourceEventSeqs":[87],"surfaceOp":"append"} +{"type":"step/end","seq":91,"time":1784821264911,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":92,"time":1784821264912,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":93,"time":1784821264916,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":94,"time":1784821264916,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":95,"time":1784821264916,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} +{"type":"assistant/chunk","seq":96,"time":1784821264916,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" was"}}} +{"type":"assistant/chunk","seq":97,"time":1784045704512,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" created"}}} +{"type":"assistant/chunk","seq":98,"time":1784045704512,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" successfully"}}} +{"type":"assistant/chunk","seq":99,"time":1784045704620,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":100,"time":1784045704645,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" The"}}} +{"type":"assistant/chunk","seq":101,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} +{"type":"assistant/chunk","seq":102,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" asked"}}} +{"type":"assistant/chunk","seq":103,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":104,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":105,"time":1784045704646,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} +{"type":"assistant/chunk","seq":106,"time":1784045704672,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":107,"time":1784045704673,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} +{"type":"assistant/chunk","seq":108,"time":1784045704673,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} +{"type":"assistant/chunk","seq":109,"time":1784045704673,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" single"}}} +{"type":"assistant/chunk","seq":110,"time":1784045704699,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" word"}}} +{"type":"assistant/chunk","seq":111,"time":1784045704699,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" D"}}} +{"type":"assistant/chunk","seq":112,"time":1784045704699,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} +{"type":"assistant/chunk","seq":113,"time":1784045704726,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":114,"time":1784045704726,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} +{"type":"assistant/chunk","seq":115,"time":1784045704726,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} +{"type":"assistant/chunk","seq":116,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} +{"type":"assistant/chunk","seq":117,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The file was created successfully. The user asked me to reply with exactly the single word DONE."}}}} +{"type":"assistant/chunk","seq":118,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} +{"type":"assistant/chunk","seq":119,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":107,"outputTokens":23,"cacheReadTokens":3968,"reasoningTokens":20}}}} +{"type":"assistant/chunk","seq":120,"time":1784045704754,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":121,"time":1784821264917,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The file was created successfully. The user asked me to reply with exactly the single word DONE."},{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":107,"outputTokens":23,"cacheReadTokens":3968,"reasoningTokens":20}},"sourceEventSeqs":[93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120],"surfaceOp":"append"} +{"type":"step/end","seq":122,"time":1784821264922,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":123,"time":1784821264922,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-escalation-approved/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/fs-escalation-approved/stdout.expected.jsonl index 6f5783b6ad..c8a50f539b 100644 --- a/examples/acp-agent/tests/snapshots/fs-escalation-approved/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-escalation-approved/stdout.expected.jsonl @@ -1,54 +1,5 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"workspace-write","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the write tool (NOT","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" create"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" write"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sand"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"box"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_per"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"missions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" do"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_Fnymmavpr4klMDy4Fdej3227","title":"Write escalated.md","kind":"edit","status":"in_progress","locations":[{"path":"escalated.md"}],"content":[{"type":"diff","path":"escalated.md","oldText":null,"newText":"escalated"}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","id":1,"method":"session/request_permission","params":{"sessionId":"{{sessionId}}","toolCall":{"toolCallId":"call_00_Fnymmavpr4klMDy4Fdej3227"},"options":[{"optionId":"allow-once","name":"Allow once","kind":"allow_once"},{"optionId":"reject-once","name":"Reject","kind":"reject_once"}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_Fnymmavpr4klMDy4Fdej3227","status":"completed","content":[{"type":"diff","path":"escalated.md","oldText":null,"newText":"escalated"}],"title":"Write escalated.md"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" was"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" created"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" successfully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" asked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl b/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl index 8f97feff04..25c57ee964 100644 --- a/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl @@ -78,7 +78,7 @@ {"type":"assistant/chunk","seq":76,"time":1783611703969,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":77,"time":1783611703972,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to use the edit tool to replace \"blue\" with \"green\" in settings.txt without reading the file first, and then reply with just \"DONE\"."},{"type":"tool-call","id":"call_00_x0zlnXl5JOxLrAYL9y7P0119","name":"edit","arguments":"{\"file_path\": \"settings.txt\", \"old_string\": \"blue\", \"new_string\": \"green\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":3132,"outputTokens":115,"cacheReadTokens":0,"reasoningTokens":36}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76],"surfaceOp":"append"} {"type":"tool/call","seq":78,"time":1783611703972,"data":{"turn":1,"step":1,"callId":"call_00_x0zlnXl5JOxLrAYL9y7P0119","name":"edit","arguments":"{\"file_path\": \"settings.txt\", \"old_string\": \"blue\", \"new_string\": \"green\"}"}} -{"type":"tool/result","seq":79,"time":1783611703978,"data":{"turn":1,"step":1,"callId":"call_00_x0zlnXl5JOxLrAYL9y7P0119","content":[{"type":"text","text":"Error: edit requires reading \"/var/folders/2c/psb0_fmx7hbgz558xjt_f0l00000gn/T/acp-snap-cwd-QzoqnB/settings.txt\" first"}],"isError":true,"error":{"name":"FsError","code":"FS_NOT_OBSERVED"}},"sourceEventSeqs":[78],"surfaceOp":"append"} +{"type":"tool/result","seq":79,"time":1783611703978,"data":{"turn":1,"step":1,"callId":"call_00_x0zlnXl5JOxLrAYL9y7P0119","content":[{"type":"text","text":"Error: edit requires reading \"/private/var/folders/2c/psb0_fmx7hbgz558xjt_f0l00000gn/T/acp-snap-cwd-QzoqnB/settings.txt\" first"}],"isError":true,"error":{"name":"FsError","code":"FS_NOT_OBSERVED"}},"sourceEventSeqs":[78],"surfaceOp":"append"} {"type":"step/end","seq":80,"time":1783611703978,"data":{"turn":1,"step":1}} {"type":"step/start","seq":81,"time":1783611703978,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":82,"time":1783611704825,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} @@ -226,7 +226,7 @@ {"type":"assistant/chunk","seq":224,"time":1783611707096,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":225,"time":1783611707097,"data":{"turn":1,"step":3,"content":[{"type":"reasoning","text":"The file contains \"color: blue\". I need to replace \"blue\" with \"green\". The edit tool said it requires reading first — now I've read it, so the edit should work."},{"type":"tool-call","id":"call_00_GVknJu2tksKkP4lALCwh0926","name":"edit","arguments":"{\"file_path\": \"settings.txt\", \"old_string\": \"blue\", \"new_string\": \"green\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":281,"outputTokens":119,"cacheReadTokens":3200,"reasoningTokens":40}},"sourceEventSeqs":[149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224],"surfaceOp":"append"} {"type":"tool/call","seq":226,"time":1783611707097,"data":{"turn":1,"step":3,"callId":"call_00_GVknJu2tksKkP4lALCwh0926","name":"edit","arguments":"{\"file_path\": \"settings.txt\", \"old_string\": \"blue\", \"new_string\": \"green\"}"}} -{"type":"tool/result","seq":227,"time":1783611707114,"data":{"turn":1,"step":3,"callId":"call_00_GVknJu2tksKkP4lALCwh0926","content":[{"type":"text","text":"The file /var/folders/2c/psb0_fmx7hbgz558xjt_f0l00000gn/T/acp-snap-cwd-QzoqnB/settings.txt has been updated successfully."}],"isError":false,"meta":{"diffs":[{"path":"settings.txt","oldText":"color: blue","newText":"color: green"}]}},"sourceEventSeqs":[226],"surfaceOp":"append"} +{"type":"tool/result","seq":227,"time":1783611707114,"data":{"turn":1,"step":3,"callId":"call_00_GVknJu2tksKkP4lALCwh0926","content":[{"type":"text","text":"The file /private/var/folders/2c/psb0_fmx7hbgz558xjt_f0l00000gn/T/acp-snap-cwd-QzoqnB/settings.txt has been updated successfully."}],"isError":false,"meta":{"diffs":[{"path":"settings.txt","oldText":"color: blue","newText":"color: green"}]}},"sourceEventSeqs":[226],"surfaceOp":"append"} {"type":"step/end","seq":228,"time":1783611707114,"data":{"turn":1,"step":3}} {"type":"step/start","seq":229,"time":1783611707114,"data":{"turn":1,"step":4}} {"type":"assistant/chunk","seq":230,"time":1783611707747,"data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-policy-reject/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/fs-policy-reject/stdout.expected.jsonl index 49a6f6db55..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/fs-policy-reject/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-policy-reject/stdout.expected.jsonl @@ -1,150 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Do NOT use the read","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" replace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"blue"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"green"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" settings"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" without"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_x0zlnXl5JOxLrAYL9y7P0119","title":"Edit settings.txt","kind":"edit","status":"in_progress","locations":[{"path":"settings.txt"}],"content":[{"type":"diff","path":"settings.txt","oldText":"blue","newText":"green"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_x0zlnXl5JOxLrAYL9y7P0119","status":"failed","content":[{"type":"content","content":{"type":"text","text":"Error: edit requires reading \"{{cwd}}/settings.txt\" first"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" requires"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" said"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Do"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" but"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" own"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" constraints"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" require"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" follow"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" requirements"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_tfr0gdIclW92oIEgi7NF0891","title":"Read settings.txt","kind":"read","status":"in_progress","locations":[{"path":"settings.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_tfr0gdIclW92oIEgi7NF0891","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/settings.txt</path>\n<type>file</type>\n<content>\n1: color: blue\n\n(End of file - total 1 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" contains"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"color"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" blue"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" replace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"blue"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"green"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" said"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" requires"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" —"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'ve"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" so"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" work"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_GVknJu2tksKkP4lALCwh0926","title":"Edit settings.txt","kind":"edit","status":"in_progress","locations":[{"path":"settings.txt"}],"content":[{"type":"diff","path":"settings.txt","oldText":"blue","newText":"green"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_GVknJu2tksKkP4lALCwh0926","status":"completed","content":[{"type":"diff","path":"settings.txt","oldText":"color: blue","newText":"color: green"}],"title":"Edit settings.txt"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" replacement"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" was"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" successful"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'ll"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instructed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/fs-read-window/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/fs-read-window/stdout.expected.jsonl index 0a32a44362..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/fs-read-window/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-read-window/stdout.expected.jsonl @@ -1,92 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the read tool (NOT","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" offset"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"5"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" limit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"4"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" lines"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"5"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" through"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"8"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" of"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" big"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" current"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" directory"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" check"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" current"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" directory"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_GIZwZS9a7vhWTFCIc7Z35497","title":"Read big.txt (5 - 8)","kind":"read","status":"in_progress","locations":[{"path":"big.txt","line":5}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_GIZwZS9a7vhWTFCIc7Z35497","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/big.txt</path>\n<type>file</type>\n<content>\n5: line five\n6: line six\n7: line seven\n8: line eight\n\n(Showing lines 5-8 of 10. Use offset=9 to continue.)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" lines"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"5"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" through"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"8"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" expected"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/fs-read/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/fs-read/stdout.expected.jsonl index aabd8fe4dc..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/fs-read/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-read/stdout.expected.jsonl @@ -1,75 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the read tool (NOT","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" greeting"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"),"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_hHPZCcivsIkXAGS9jTGy8417","title":"Read greeting.txt","kind":"read","status":"in_progress","locations":[{"path":"greeting.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_hHPZCcivsIkXAGS9jTGy8417","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/greeting.txt</path>\n<type>file</type>\n<content>\n1: hello\n\n(End of file - total 1 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" asked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'ve"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/fs-terminal-card/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/fs-terminal-card/stdout.expected.jsonl deleted file mode 100644 index 0b2343793b..0000000000 --- a/examples/acp-agent/tests/snapshots/fs-terminal-card/stdout.expected.jsonl +++ /dev/null @@ -1,49 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" simple"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","title":"echo TERMINAL_OK","kind":"execute","status":"in_progress","rawInput":"echo TERMINAL_OK","content":[{"type":"content","content":{"type":"text","text":"Echo TERMINAL_OK to verify terminal access"}},{"type":"terminal","terminalId":"call_00_fkbBRJsUrGKd1pWVc4Gn8233"}],"_meta":{"terminal_info":{"terminal_id":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","cwd":"{{cwd}}"}}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","status":"completed","_meta":{"terminal_output":{"terminal_id":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","data":"TERMINAL_OK\n"},"terminal_exit":{"terminal_id":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","exit_code":0}}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ran"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" successfully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"TER"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"MIN"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl b/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl index 5a3fc5696b..f3db3493b5 100644 --- a/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl @@ -115,7 +115,7 @@ {"type":"assistant/chunk","seq":113,"time":1783352094988,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":114,"time":1783352094988,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The file contains \"original contents\". Now I'll replace it with \"replaced\"."},{"type":"tool-call","id":"call_00_N23EvXjDo4c8enyWpIUq4043","name":"write","arguments":"{\"file_path\": \"data.txt\", \"content\": \"replaced\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":228,"outputTokens":79,"cacheReadTokens":2816,"reasoningTokens":17}},"sourceEventSeqs":[70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113],"surfaceOp":"append"} {"type":"tool/call","seq":115,"time":1783352094988,"data":{"turn":1,"step":2,"callId":"call_00_N23EvXjDo4c8enyWpIUq4043","name":"write","arguments":"{\"file_path\": \"data.txt\", \"content\": \"replaced\"}"}} -{"type":"tool/result","seq":116,"time":1783352094995,"data":{"turn":1,"step":2,"callId":"call_00_N23EvXjDo4c8enyWpIUq4043","content":[{"type":"text","text":"<path>/tmp/acp-snap-cwd-hH2sGY/data.txt</path>\n<type>file</type>\n<content>\nUpdated file\n</content>"}],"isError":false,"meta":{"diffs":[{"path":"data.txt","oldText":"original contents","newText":"replaced"}]}},"sourceEventSeqs":[115],"surfaceOp":"append"} +{"type":"tool/result","seq":116,"time":1783352094995,"data":{"turn":1,"step":2,"callId":"call_00_N23EvXjDo4c8enyWpIUq4043","content":[{"type":"text","text":"<path>/private/tmp/acp-snap-cwd-hH2sGY/data.txt</path>\n<type>file</type>\n<content>\nUpdated file\n</content>"}],"isError":false,"meta":{"diffs":[{"path":"data.txt","oldText":"original contents","newText":"replaced"}]}},"sourceEventSeqs":[115],"surfaceOp":"append"} {"type":"step/end","seq":117,"time":1783352094995,"data":{"turn":1,"step":2}} {"type":"step/start","seq":118,"time":1783352094995,"data":{"turn":1,"step":3}} {"type":"assistant/chunk","seq":119,"time":1783352096090,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-write-overwrite/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/fs-write-overwrite/stdout.expected.jsonl index c1e57a0315..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/fs-write-overwrite/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-write-overwrite/stdout.expected.jsonl @@ -1,86 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"First use the read tool","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" data"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Replace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" its"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" entire"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" contents"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"re"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"placed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" write"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"3"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_n4eRJuGoxNR07svgNtk82243","title":"Read data.txt","kind":"read","status":"in_progress","locations":[{"path":"data.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_n4eRJuGoxNR07svgNtk82243","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/data.txt</path>\n<type>file</type>\n<content>\n1: original contents\n\n(End of file - total 1 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" contains"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"original"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" contents"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'ll"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" replace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"re"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"placed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_N23EvXjDo4c8enyWpIUq4043","title":"Write data.txt","kind":"edit","status":"in_progress","locations":[{"path":"data.txt"}],"content":[{"type":"diff","path":"data.txt","oldText":null,"newText":"replaced"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_N23EvXjDo4c8enyWpIUq4043","status":"completed","content":[{"type":"diff","path":"data.txt","oldText":"original contents","newText":"replaced"}],"title":"Write data.txt"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" has"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" been"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" replaced"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" successfully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/fs-write/session.jsonl b/examples/acp-agent/tests/snapshots/fs-write/session.jsonl index dbaaf8a8b6..46de5fa221 100644 --- a/examples/acp-agent/tests/snapshots/fs-write/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-write/session.jsonl @@ -63,7 +63,7 @@ {"type":"assistant/chunk","seq":61,"time":1783352079886,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":62,"time":1783352079888,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to create a file named notes.txt with the content \"hello world\" using the write tool, then reply with \"DONE\"."},{"type":"tool-call","id":"call_00_APMUCJJm9lrTSlVbg6dB0185","name":"write","arguments":"{\"file_path\": \"notes.txt\", \"content\": \"hello world\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":2891,"outputTokens":92,"cacheReadTokens":0,"reasoningTokens":30}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61],"surfaceOp":"append"} {"type":"tool/call","seq":63,"time":1783352079888,"data":{"turn":1,"step":1,"callId":"call_00_APMUCJJm9lrTSlVbg6dB0185","name":"write","arguments":"{\"file_path\": \"notes.txt\", \"content\": \"hello world\"}"}} -{"type":"tool/result","seq":64,"time":1783352079897,"data":{"turn":1,"step":1,"callId":"call_00_APMUCJJm9lrTSlVbg6dB0185","content":[{"type":"text","text":"<path>/tmp/acp-snap-cwd-sNvn5N/notes.txt</path>\n<type>file</type>\n<content>\nCreated file\n</content>"}],"isError":false,"meta":{"diffs":[]}},"sourceEventSeqs":[63],"surfaceOp":"append"} +{"type":"tool/result","seq":64,"time":1783352079897,"data":{"turn":1,"step":1,"callId":"call_00_APMUCJJm9lrTSlVbg6dB0185","content":[{"type":"text","text":"<path>/private/tmp/acp-snap-cwd-sNvn5N/notes.txt</path>\n<type>file</type>\n<content>\nCreated file\n</content>"}],"isError":false,"meta":{"diffs":[]}},"sourceEventSeqs":[63],"surfaceOp":"append"} {"type":"step/end","seq":65,"time":1783352079898,"data":{"turn":1,"step":1}} {"type":"step/start","seq":66,"time":1783352079899,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":67,"time":1783352080825,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-write/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/fs-write/stdout.expected.jsonl index 16f2d39a8d..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/fs-write/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-write/stdout.expected.jsonl @@ -1,56 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the write tool (NOT","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" create"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" named"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" notes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" content"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" world"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" write"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_APMUCJJm9lrTSlVbg6dB0185","title":"Write notes.txt","kind":"edit","status":"in_progress","locations":[{"path":"notes.txt"}],"content":[{"type":"diff","path":"notes.txt","oldText":null,"newText":"hello world"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_APMUCJJm9lrTSlVbg6dB0185","status":"completed","content":[{"type":"diff","path":"notes.txt","oldText":null,"newText":"hello world"}],"title":"Write notes.txt"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" has"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" been"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" created"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/goal-command-status/input.json b/examples/acp-agent/tests/snapshots/goal-command-status/input.json deleted file mode 100644 index 0bc0192c93..0000000000 --- a/examples/acp-agent/tests/snapshots/goal-command-status/input.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "steps": [ - { "op": "initialize" }, - { "op": "newSession" }, - { "op": "prompt", "text": "/goal" } - ] -} diff --git a/examples/acp-agent/tests/snapshots/goal-command-status/session.jsonl b/examples/acp-agent/tests/snapshots/goal-command-status/session.jsonl deleted file mode 100644 index a6f73319bc..0000000000 --- a/examples/acp-agent/tests/snapshots/goal-command-status/session.jsonl +++ /dev/null @@ -1 +0,0 @@ -{"type":"session","version":0,"id":"00000000-0000-0000-0000-000000000000","createdAt":0} diff --git a/examples/acp-agent/tests/snapshots/goal-command-status/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/goal-command-status/stdout.expected.jsonl deleted file mode 100644 index 64ef74a717..0000000000 --- a/examples/acp-agent/tests/snapshots/goal-command-status/stdout.expected.jsonl +++ /dev/null @@ -1,5 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"No goal is currently set.\nUsage: /goal [<objective>|clear|edit <objective>|pause|resume]"}}}} -{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/handshake/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/handshake/stdout.expected.jsonl index 42747846b2..a20b86580e 100644 --- a/examples/acp-agent/tests/snapshots/handshake/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/handshake/stdout.expected.jsonl @@ -1,3 +1,2 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} diff --git a/examples/acp-agent/tests/snapshots/hook-cc-posttool-block/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-cc-posttool-block/stdout.expected.jsonl index 3295477ce5..e42141f739 100644 --- a/examples/acp-agent/tests/snapshots/hook-cc-posttool-block/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-cc-posttool-block/stdout.expected.jsonl @@ -1,92 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Call the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" If"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" rejected"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ret"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ry"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" once"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" quote"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" final"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_VAByyMjsct4c7P6k1ysX9256","title":"echo HELLO","kind":"execute","status":"in_progress","rawInput":"echo HELLO","content":[{"type":"content","content":{"type":"text","text":"Echo HELLO to stdout"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_VAByyMjsct4c7P6k1ysX9256","status":"failed","content":[{"type":"content","content":{"type":"text","text":"```console\ntool output rejected by policy: retry once\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" call"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" was"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" rejected"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" said"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ret"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ry"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" once"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ret"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ry"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_tDV4j1p5eAeHTtQhXOfn6856","title":"echo HELLO","kind":"execute","status":"in_progress","rawInput":"echo HELLO","content":[{"type":"content","content":{"type":"text","text":"Echo HELLO to stdout"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_tDV4j1p5eAeHTtQhXOfn6856","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nHELLO\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" second"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" attempt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" succeeded"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" final"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" final"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The final tool result verbatim:\n\n```\nHELLO\n```"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-cc-posttool-context/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-cc-posttool-context/stdout.expected.jsonl index 9e19a80897..da09fe35c3 100644 --- a/examples/acp-agent/tests/snapshots/hook-cc-posttool-context/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-cc-posttool-context/stdout.expected.jsonl @@ -1,80 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_HbCMzTslWBZTSphWN0z97382","title":"echo HELLO","kind":"execute","status":"in_progress","rawInput":"echo HELLO","content":[{"type":"content","content":{"type":"text","text":"Run echo HELLO"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_HbCMzTslWBZTSphWN0z97382","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nHELLO\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" asked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" was"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" an"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" of"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"0"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"success"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":")."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" was"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"It"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" completed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" successfully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" exit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"0"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"."}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The tool result was:\n\n```\nHELLO\n```\n\nIt completed successfully with exit code 0."}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/session.jsonl b/examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/session.jsonl index 888f2f5c13..3b86a1c456 100644 --- a/examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/session.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/session.jsonl @@ -56,8 +56,8 @@ {"type":"tool/call","seq":54,"time":1783352172557,"data":{"turn":1,"step":1,"callId":"call_00_6k0oGSliVHxGSgqBmMEO4311","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Echo HELLO\"}"}} {"type":"hook/invoked","seq":55,"time":1783352172558,"data":{"turn":1,"point":"PreToolUse","dialect":"claude","handlerId":"claude:PreToolUse:1","matcher":"bash"}} {"type":"hook/result","seq":56,"time":1783352172573,"data":{"turn":1,"point":"PreToolUse","handlerId":"claude:PreToolUse:1","decision":"ask","exitCode":0,"durationMs":14.113374999999905}} -{"type":"approval/asked","seq":57,"time":1783962235813,"data":{"id":"97616288-1a5e-4110-a75d-7616a24adcc4","toolName":"bash","callId":"call_00_6k0oGSliVHxGSgqBmMEO4311","reason":"bash requires manual approval in this session"}} -{"type":"approval/decided","seq":58,"time":1783962235813,"data":{"id":"97616288-1a5e-4110-a75d-7616a24adcc4","outcome":"rejected"}} +{"type":"approval/asked","seq":57,"time":1783962235813,"data":{"id":"e5dc594b-3ffa-4390-848c-e10b81550c68","toolName":"bash","callId":"call_00_6k0oGSliVHxGSgqBmMEO4311","reason":"bash requires manual approval in this session"}} +{"type":"approval/decided","seq":58,"time":1783962235813,"data":{"id":"e5dc594b-3ffa-4390-848c-e10b81550c68","outcome":"rejected"}} {"type":"tool/result","seq":59,"time":1783962235814,"data":{"turn":1,"step":1,"callId":"call_00_6k0oGSliVHxGSgqBmMEO4311","content":[{"type":"text","text":"Error: the user rejected tool \"bash\""}],"isError":true},"sourceEventSeqs":[54],"surfaceOp":"append"} {"type":"step/end","seq":60,"time":1783962235814,"data":{"turn":1,"step":1}} {"type":"step/start","seq":61,"time":1783962235814,"data":{"turn":1,"step":2}} diff --git a/examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/stdout.expected.jsonl index a14e4cafb6..979ff3326b 100644 --- a/examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/stdout.expected.jsonl @@ -1,68 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" simple"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_6k0oGSliVHxGSgqBmMEO4311","title":"echo HELLO","kind":"execute","status":"in_progress","rawInput":"echo HELLO","content":[{"type":"content","content":{"type":"text","text":"Echo HELLO"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_6k0oGSliVHxGSgqBmMEO4311","status":"failed","content":[{"type":"content","content":{"type":"text","text":"```console\nError: the user rejected tool \"bash\"\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" an"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" error"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" saying"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" requires"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" manual"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" approval"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" session"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'ll"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" got"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Error"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" requires"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" manual"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" approval"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" session"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The tool result I got back verbatim is:\n\n```\nError: bash requires manual approval in this session\n```"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-cc-pretool-deny/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-cc-pretool-deny/stdout.expected.jsonl index 59c21ed411..2bb15b6f03 100644 --- a/examples/acp-agent/tests/snapshots/hook-cc-pretool-deny/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-cc-pretool-deny/stdout.expected.jsonl @@ -1,75 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" simple"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","title":"echo HELLO","kind":"execute","status":"in_progress","rawInput":"echo HELLO","content":[{"type":"content","content":{"type":"text","text":"Run echo HELLO"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","status":"failed","content":[{"type":"content","content":{"type":"text","text":"```console\nError: bash is disabled by policy in this session\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" disabled"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" error"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":">"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" Error"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" disabled"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" session"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" cannot"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" because"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" disabled"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"."}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-cc-promptsubmit-block/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-cc-promptsubmit-block/stdout.expected.jsonl index 6a1310e749..cb25d1c6bb 100644 --- a/examples/acp-agent/tests/snapshots/hook-cc-promptsubmit-block/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-cc-promptsubmit-block/stdout.expected.jsonl @@ -1,4 +1,3 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"cancelled"}} diff --git a/examples/acp-agent/tests/snapshots/hook-cc-promptsubmit-context/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-cc-promptsubmit-context/stdout.expected.jsonl index c700da5011..05c4f9235b 100644 --- a/examples/acp-agent/tests/snapshots/hook-cc-promptsubmit-context/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-cc-promptsubmit-context/stdout.expected.jsonl @@ -1,26 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"What is my favorite color?","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" favorite"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" color"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" te"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"al"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stated"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" context"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" provided"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plugin"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"te"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"al"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"teal"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-cc-stop-continue/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-cc-stop-continue/stdout.expected.jsonl index cb8001573f..0f8f000343 100644 --- a/examples/acp-agent/tests/snapshots/hook-cc-stop-continue/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-cc-stop-continue/stdout.expected.jsonl @@ -1,44 +1,5 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Reply with the single word","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"FIR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ST"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"FIR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ST"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"SEC"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"OND"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"SEC"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"OND"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"FIRST"}}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"SECOND"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-codex-posttool-block/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-codex-posttool-block/stdout.expected.jsonl index 02ddcc549b..d86218d3b7 100644 --- a/examples/acp-agent/tests/snapshots/hook-codex-posttool-block/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-codex-posttool-block/stdout.expected.jsonl @@ -1,71 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Call the bash tool exactly","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" call"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" once"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`,"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" quote"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_1rmSWHhVchVg7PDTmegT0421","title":"echo HELLO","kind":"execute","status":"in_progress","rawInput":"echo HELLO","content":[{"type":"content","content":{"type":"text","text":"Echo HELLO to stdout"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_1rmSWHhVchVg7PDTmegT0421","status":"failed","content":[{"type":"content","content":{"type":"text","text":"```console\ntool output rejected by codex policy: summarize instead\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" was"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" rejected"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"x"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" quote"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" what"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" got"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"<"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":">"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" rejected"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"x"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" summarize"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" instead"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"</"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":">\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```\n<tool_result>tool output rejected by codex policy: summarize instead</tool_result>\n```"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-codex-posttool-context/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-codex-posttool-context/stdout.expected.jsonl index 18ef664117..567b676605 100644 --- a/examples/acp-agent/tests/snapshots/hook-codex-posttool-context/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-codex-posttool-context/stdout.expected.jsonl @@ -1,70 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"echo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_Q6wHtakaip2QNfIXaVJY5458","title":"echo HELLO","kind":"execute","status":"in_progress","rawInput":"echo HELLO","content":[{"type":"content","content":{"type":"text","text":"Run echo HELLO"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_Q6wHtakaip2QNfIXaVJY5458","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nHELLO\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" asked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" got"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"That"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" received"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"HE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"LL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"O"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The tool result I received is:\n\n```\nHELLO\n```"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-codex-pretool-block/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-codex-pretool-block/stdout.expected.jsonl index 749e68ec30..6022fd5747 100644 --- a/examples/acp-agent/tests/snapshots/hook-codex-pretool-block/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-codex-pretool-block/stdout.expected.jsonl @@ -1,72 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" simple"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_tv0SMeLXaTuyuVrOxnV97085","title":"echo HELLO","kind":"execute","status":"in_progress","rawInput":"echo HELLO","content":[{"type":"content","content":{"type":"text","text":"Run echo HELLO"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_tv0SMeLXaTuyuVrOxnV97085","status":"failed","content":[{"type":"content","content":{"type":"text","text":"```console\nError: bash is disabled by codex policy in this session\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" disabled"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" session"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" got"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Error"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" disabled"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" code"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"x"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" session"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"```"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The tool result I got back verbatim is:\n\n```\nError: bash is disabled by codex policy in this session\n```"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-codex-promptsubmit-block/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-codex-promptsubmit-block/stdout.expected.jsonl index 6a1310e749..cb25d1c6bb 100644 --- a/examples/acp-agent/tests/snapshots/hook-codex-promptsubmit-block/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-codex-promptsubmit-block/stdout.expected.jsonl @@ -1,4 +1,3 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"cancelled"}} diff --git a/examples/acp-agent/tests/snapshots/hook-codex-promptsubmit-context/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-codex-promptsubmit-context/stdout.expected.jsonl index 2a47058980..05c4f9235b 100644 --- a/examples/acp-agent/tests/snapshots/hook-codex-promptsubmit-context/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-codex-promptsubmit-context/stdout.expected.jsonl @@ -1,45 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"What is my favorite color?","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" asked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" about"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" their"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" favorite"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" color"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" context"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tells"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" they"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" previously"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stated"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" te"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"al"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" They"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" asked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" color"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" without"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" any"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"te"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"al"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"teal"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/hook-codex-stop-continue/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/hook-codex-stop-continue/stdout.expected.jsonl index e7b1d906e9..0f8f000343 100644 --- a/examples/acp-agent/tests/snapshots/hook-codex-stop-continue/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/hook-codex-stop-continue/stdout.expected.jsonl @@ -1,44 +1,5 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Reply with the single word","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"FIR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ST"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"FIR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ST"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"SEC"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"OND"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"SEC"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"OND"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"FIRST"}}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"SECOND"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/lsp-definition/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/lsp-definition/stdout.expected.jsonl index ea9960c652..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/lsp-definition/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/lsp-definition/stdout.expected.jsonl @@ -1,8 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the lsp tool exactly","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_lsp_definition","title":"LSP goToDefinition subject.ts:1:7","kind":"search","status":"in_progress","locations":[{"path":"subject.ts","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_lsp_definition","status":"completed","content":[{"type":"content","content":{"type":"text","text":"subject.ts:1:7\n… 1 more location omitted (limit 1)."}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json index 4e34a49176..3d28b1dfb8 100644 --- a/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json @@ -1,68 +1,5 @@ { "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, { "name": "bash", "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", @@ -170,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, { "name": "get_goal", "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", diff --git a/examples/acp-agent/tests/snapshots/model-switching/input.json b/examples/acp-agent/tests/snapshots/model-switching/input.json deleted file mode 100644 index 3612f367f6..0000000000 --- a/examples/acp-agent/tests/snapshots/model-switching/input.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "steps": [ - { - "op": "initialize" - }, - { - "op": "newSession" - }, - { - "op": "prompt", - "text": "Without using tools, reply with exactly FLASH and stop." - }, - { - "op": "setConfigOption", - "configId": "model", - "value": "[\"deepseek\",\"deepseek-v4-pro\"]" - }, - { - "op": "prompt", - "text": "Without using tools, reply with exactly PRO and stop." - } - ] -} diff --git a/examples/acp-agent/tests/snapshots/model-switching/session.jsonl b/examples/acp-agent/tests/snapshots/model-switching/session.jsonl deleted file mode 100644 index 198f77cb21..0000000000 --- a/examples/acp-agent/tests/snapshots/model-switching/session.jsonl +++ /dev/null @@ -1,70 +0,0 @@ -{"type":"session","version":0,"id":"622d16ce-0a94-476b-97a4-26dad50b1fbf","createdAt":1784086275585,"cwd":"/var/folders/_g/59jgff8x2gqd39f5vy1wnbfc0000gn/T/acp-snap-cwd-Cwf7Bh","delegationDepth":0} -{"type":"turn/start","seq":0,"time":1784086275588,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":1,"time":1784086275588,"data":{"content":[{"type":"text","text":"Without using tools, reply with exactly FLASH and stop."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"session/title","seq":2,"time":1784086275588,"data":{"title":"Without using tools, reply with","messageSeqs":[1],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":3,"time":1784086275590,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":4,"time":1784086275590,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"assistant/chunk","seq":5,"time":1784086276525,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":6,"time":1784086276526,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":7,"time":1784086276605,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":8,"time":1784086276639,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":9,"time":1784086276640,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":10,"time":1784086276640,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":11,"time":1784086276640,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":12,"time":1784086276640,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":13,"time":1784086276661,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} -{"type":"assistant/chunk","seq":14,"time":1784086276661,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":15,"time":1784086276661,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"FL"}}} -{"type":"assistant/chunk","seq":16,"time":1784086276661,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ASH"}}} -{"type":"assistant/chunk","seq":17,"time":1784086276661,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\""}}} -{"type":"assistant/chunk","seq":18,"time":1784086276661,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":19,"time":1784086276710,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" stop"}}} -{"type":"assistant/chunk","seq":20,"time":1784086276710,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":21,"time":1784086276771,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" without"}}} -{"type":"assistant/chunk","seq":22,"time":1784086276771,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" using"}}} -{"type":"assistant/chunk","seq":23,"time":1784086276772,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" any"}}} -{"type":"assistant/chunk","seq":24,"time":1784086276772,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" tools"}}} -{"type":"assistant/chunk","seq":25,"time":1784086276772,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":26,"time":1784086276777,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":27,"time":1784086276777,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"FL"}}} -{"type":"assistant/chunk","seq":28,"time":1784086276778,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":1,"text":"ASH"}}} -{"type":"assistant/chunk","seq":29,"time":1784086276778,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly \"FLASH\" and stop, without using any tools."}}}} -{"type":"assistant/chunk","seq":30,"time":1784086276778,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"FLASH"}}}} -{"type":"assistant/chunk","seq":31,"time":1784086276778,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3133,"outputTokens":23,"cacheReadTokens":0,"reasoningTokens":20}}}} -{"type":"assistant/chunk","seq":32,"time":1784086276778,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":33,"time":1784086276782,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to reply with exactly \"FLASH\" and stop, without using any tools."},{"type":"text","text":"FLASH"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":3133,"outputTokens":23,"cacheReadTokens":0,"reasoningTokens":20}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],"surfaceOp":"append"} -{"type":"step/end","seq":34,"time":1784086276782,"data":{"turn":1,"step":1}} -{"type":"turn/end","seq":35,"time":1784086276783,"data":{"turn":1,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":36,"time":1784086276811,"data":{"turn":2,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":37,"time":1784086276812,"data":{"content":[{"type":"text","text":"Without using tools, reply with exactly PRO and stop."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"step/start","seq":38,"time":1784086276812,"data":{"turn":2,"step":1}} -{"type":"request/header","seq":39,"time":1784298376621,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-pro"},"system":"{{system}}","tools":"{{tools}}"},"reason":"change"}} -{"type":"assistant/chunk","seq":40,"time":1784086278053,"data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":41,"time":1784086278053,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":42,"time":1784086278242,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":43,"time":1784086278312,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":44,"time":1784086278312,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":45,"time":1784086278313,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":46,"time":1784086278313,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":47,"time":1784086278355,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":48,"time":1784086278356,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} -{"type":"assistant/chunk","seq":49,"time":1784086278356,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":50,"time":1784086278356,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"PRO"}}} -{"type":"assistant/chunk","seq":51,"time":1784086278400,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\""}}} -{"type":"assistant/chunk","seq":52,"time":1784086278400,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":53,"time":1784086278400,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" stop"}}} -{"type":"assistant/chunk","seq":54,"time":1784086278400,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":55,"time":1784086278441,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" without"}}} -{"type":"assistant/chunk","seq":56,"time":1784086278442,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" using"}}} -{"type":"assistant/chunk","seq":57,"time":1784086278442,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" any"}}} -{"type":"assistant/chunk","seq":58,"time":1784086278442,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" tools"}}} -{"type":"assistant/chunk","seq":59,"time":1784086278442,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":60,"time":1784086278494,"data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":61,"time":1784086278495,"data":{"turn":2,"step":1,"chunk":{"type":"text-delta","index":1,"text":"PRO"}}} -{"type":"assistant/chunk","seq":62,"time":1784086278495,"data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly \"PRO\" and stop, without using any tools."}}}} -{"type":"assistant/chunk","seq":63,"time":1784086278495,"data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"PRO"}}}} -{"type":"assistant/chunk","seq":64,"time":1784086278495,"data":{"turn":2,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3149,"outputTokens":21,"cacheReadTokens":0,"reasoningTokens":19}}}} -{"type":"assistant/chunk","seq":65,"time":1784086278495,"data":{"turn":2,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":66,"time":1784086278495,"data":{"turn":2,"step":1,"content":[{"type":"reasoning","text":"The user wants me to reply with exactly \"PRO\" and stop, without using any tools."},{"type":"text","text":"PRO"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":3149,"outputTokens":21,"cacheReadTokens":0,"reasoningTokens":19}},"sourceEventSeqs":[40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65],"surfaceOp":"append"} -{"type":"step/end","seq":67,"time":1784086278495,"data":{"turn":2,"step":1}} -{"type":"turn/end","seq":68,"time":1784086278495,"data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/model-switching/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/model-switching/stdout.expected.jsonl deleted file mode 100644 index 85bb5a7137..0000000000 --- a/examples/acp-agent/tests/snapshots/model-switching/stdout.expected.jsonl +++ /dev/null @@ -1,49 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Without using tools, reply with","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"FL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ASH"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" without"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" any"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"FL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ASH"}}}} -{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} -{"jsonrpc":"2.0","id":4,"result":{"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-pro\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"PRO"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" without"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" any"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PRO"}}}} -{"jsonrpc":"2.0","id":5,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md deleted file mode 100644 index 371780ab3d..0000000000 --- a/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md +++ /dev/null @@ -1,57 +0,0 @@ -You are an AI agent powered by the DeepSeek Harness SDK. - -You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. - -Verify your work by running the code or tests. Keep answers brief and factual. - - -Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. - -Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes. - -Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session. - -Check the [exit code: N] marker on every bash result; investigate failures before moving on. - -Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. - -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - -Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. - -Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). -<!-- dsh-user-approval-policy:never --> - -Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. - -Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. - -<!-- request/header change 1 --> - -You are an AI agent powered by the DeepSeek Harness SDK. - -You are a coding assistant powered by the deepseek-v4-pro model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. - -Verify your work by running the code or tests. Keep answers brief and factual. - - -Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. - -Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes. - -Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session. - -Check the [exit code: N] marker on every bash result; investigate failures before moving on. - -Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. - -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - -Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. - -Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). -<!-- dsh-user-approval-policy:never --> - -Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. - -Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. diff --git a/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json deleted file mode 100644 index 8bfac915b0..0000000000 --- a/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json +++ /dev/null @@ -1,1510 +0,0 @@ -{ - "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, - { - "name": "bash", - "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", - "parameters": { - "type": "object", - "properties": { - "command": { - "type": "string", - "description": "The bash command to execute." - }, - "description": { - "type": "string", - "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." - }, - "timeoutMs": { - "type": "number", - "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." - }, - "workdir": { - "type": "string", - "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." - }, - "run_in_background": { - "type": "boolean", - "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." - } - }, - "required": [ - "command", - "description" - ] - } - }, - { - "name": "create_goal", - "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The concrete completion objective inferred from the direct human request." - }, - "max_goal_rounds": { - "type": "number", - "description": "Optional positive safe-integer limit on automatic continuation rounds." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "edit", - "description": "Edit an existing UTF-8 text file by replacing literal text.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to edit, resolved by the filesystem backend." - }, - "old_string": { - "type": "string", - "description": "Literal text to replace. Must match exactly." - }, - "new_string": { - "type": "string", - "description": "Literal replacement text. Use an empty string to delete the match." - }, - "replace_all": { - "type": "boolean", - "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "old_string", - "new_string" - ] - } - }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, - { - "name": "get_goal", - "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "ralph", - "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The immutable completion objective for every fresh Ralph round." - }, - "maxRounds": { - "type": "number", - "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "read", - "description": "Read a UTF-8 text file and return line-numbered content.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to read, resolved by the filesystem backend." - }, - "offset": { - "type": "number", - "description": "1-based first line to return. Defaults to 1." - }, - "limit": { - "type": "number", - "description": "Maximum number of lines to return. Defaults to 2000." - } - }, - "required": [ - "file_path" - ] - } - }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, - { - "name": "skill", - "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", - "parameters": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The exact skill name from the available skills list." - } - }, - "required": [ - "name" - ] - } - }, - { - "name": "subagent", - "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "subagent_fork", - "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "task_kill", - "description": "Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "reason": { - "type": "string", - "description": "Optional short reason, recorded in the log and forwarded to the task." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "task_list", - "description": "List your background tasks (running and finished) with their ids, kinds, and statuses.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "task_output", - "description": "Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "wait": { - "type": "boolean", - "description": "Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive." - }, - "timeout_ms": { - "type": "number", - "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "todo_write", - "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", - "parameters": { - "type": "object", - "properties": { - "todos": { - "type": "array", - "description": "The COMPLETE task list, replacing any previous list.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "content": { - "type": "string", - "description": "What the task is — a short imperative line." - }, - "status": { - "type": "string", - "description": "pending (not started) | in_progress (now) | completed (done).", - "enum": [ - "pending", - "in_progress", - "completed" - ] - } - }, - "required": [ - "content", - "status" - ] - } - } - }, - "required": [ - "todos" - ] - } - }, - { - "name": "update_goal", - "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", - "parameters": { - "type": "object", - "properties": { - "goal_id": { - "type": "string", - "description": "Exact id returned by get_goal." - }, - "revision": { - "type": "number", - "description": "Exact positive revision returned by get_goal." - }, - "action": { - "type": "string", - "description": "edit | pause | resume | complete | blocked", - "enum": [ - "edit", - "pause", - "resume", - "complete", - "blocked" - ] - }, - "objective": { - "type": "string", - "description": "Replacement objective; valid only with action edit." - }, - "max_goal_rounds": { - "type": "number", - "description": "Replacement cap; valid only with action edit." - }, - "blocked_reason": { - "type": "string", - "description": "Concrete blocking condition; required only with action blocked." - } - }, - "required": [ - "goal_id", - "revision", - "action" - ] - } - }, - { - "name": "workflow", - "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return <value>` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", - "parameters": { - "type": "object", - "properties": { - "script": { - "type": "string", - "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)." - }, - "meta": { - "type": "object", - "description": "The workflow identity block (plain JSON — never code).", - "additionalProperties": true, - "properties": { - "name": { - "type": "string", - "description": "Short kebab-case workflow name." - }, - "description": { - "type": "string", - "description": "One-line description of what the workflow does." - }, - "whenToUse": { - "type": "string", - "description": "Optional guidance on when this workflow applies." - }, - "phases": { - "type": "array", - "description": "Optional phase declarations matched by phase() calls.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "title": { - "type": "string", - "description": "The phase title phase() calls match by exact string." - }, - "detail": { - "type": "string", - "description": "Optional one-line description of the phase." - }, - "provider": { - "type": "string", - "description": "Optional provider override this phase is expected to use." - }, - "model": { - "type": "string", - "description": "Optional model override this phase is expected to use." - } - }, - "required": [ - "title" - ] - } - } - }, - "required": [ - "name", - "description" - ] - }, - "args": { - "type": "object", - "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", - "additionalProperties": true - } - }, - "required": [ - "script", - "meta" - ] - } - }, - { - "name": "write", - "description": "Create or fully replace a UTF-8 text file.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to write, resolved by the filesystem backend." - }, - "content": { - "type": "string", - "description": "Full UTF-8 text content to write." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "content" - ] - } - } - ], - "changes": [ - [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, - { - "name": "bash", - "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", - "parameters": { - "type": "object", - "properties": { - "command": { - "type": "string", - "description": "The bash command to execute." - }, - "description": { - "type": "string", - "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." - }, - "timeoutMs": { - "type": "number", - "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." - }, - "workdir": { - "type": "string", - "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." - }, - "run_in_background": { - "type": "boolean", - "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." - } - }, - "required": [ - "command", - "description" - ] - } - }, - { - "name": "create_goal", - "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The concrete completion objective inferred from the direct human request." - }, - "max_goal_rounds": { - "type": "number", - "description": "Optional positive safe-integer limit on automatic continuation rounds." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "edit", - "description": "Edit an existing UTF-8 text file by replacing literal text.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to edit, resolved by the filesystem backend." - }, - "old_string": { - "type": "string", - "description": "Literal text to replace. Must match exactly." - }, - "new_string": { - "type": "string", - "description": "Literal replacement text. Use an empty string to delete the match." - }, - "replace_all": { - "type": "boolean", - "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "old_string", - "new_string" - ] - } - }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, - { - "name": "get_goal", - "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "ralph", - "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The immutable completion objective for every fresh Ralph round." - }, - "maxRounds": { - "type": "number", - "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "read", - "description": "Read a UTF-8 text file and return line-numbered content.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to read, resolved by the filesystem backend." - }, - "offset": { - "type": "number", - "description": "1-based first line to return. Defaults to 1." - }, - "limit": { - "type": "number", - "description": "Maximum number of lines to return. Defaults to 2000." - } - }, - "required": [ - "file_path" - ] - } - }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, - { - "name": "skill", - "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", - "parameters": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The exact skill name from the available skills list." - } - }, - "required": [ - "name" - ] - } - }, - { - "name": "subagent", - "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "subagent_fork", - "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "task_kill", - "description": "Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "reason": { - "type": "string", - "description": "Optional short reason, recorded in the log and forwarded to the task." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "task_list", - "description": "List your background tasks (running and finished) with their ids, kinds, and statuses.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "task_output", - "description": "Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "wait": { - "type": "boolean", - "description": "Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive." - }, - "timeout_ms": { - "type": "number", - "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "todo_write", - "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", - "parameters": { - "type": "object", - "properties": { - "todos": { - "type": "array", - "description": "The COMPLETE task list, replacing any previous list.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "content": { - "type": "string", - "description": "What the task is — a short imperative line." - }, - "status": { - "type": "string", - "description": "pending (not started) | in_progress (now) | completed (done).", - "enum": [ - "pending", - "in_progress", - "completed" - ] - } - }, - "required": [ - "content", - "status" - ] - } - } - }, - "required": [ - "todos" - ] - } - }, - { - "name": "update_goal", - "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", - "parameters": { - "type": "object", - "properties": { - "goal_id": { - "type": "string", - "description": "Exact id returned by get_goal." - }, - "revision": { - "type": "number", - "description": "Exact positive revision returned by get_goal." - }, - "action": { - "type": "string", - "description": "edit | pause | resume | complete | blocked", - "enum": [ - "edit", - "pause", - "resume", - "complete", - "blocked" - ] - }, - "objective": { - "type": "string", - "description": "Replacement objective; valid only with action edit." - }, - "max_goal_rounds": { - "type": "number", - "description": "Replacement cap; valid only with action edit." - }, - "blocked_reason": { - "type": "string", - "description": "Concrete blocking condition; required only with action blocked." - } - }, - "required": [ - "goal_id", - "revision", - "action" - ] - } - }, - { - "name": "workflow", - "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return <value>` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", - "parameters": { - "type": "object", - "properties": { - "script": { - "type": "string", - "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)." - }, - "meta": { - "type": "object", - "description": "The workflow identity block (plain JSON — never code).", - "additionalProperties": true, - "properties": { - "name": { - "type": "string", - "description": "Short kebab-case workflow name." - }, - "description": { - "type": "string", - "description": "One-line description of what the workflow does." - }, - "whenToUse": { - "type": "string", - "description": "Optional guidance on when this workflow applies." - }, - "phases": { - "type": "array", - "description": "Optional phase declarations matched by phase() calls.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "title": { - "type": "string", - "description": "The phase title phase() calls match by exact string." - }, - "detail": { - "type": "string", - "description": "Optional one-line description of the phase." - }, - "provider": { - "type": "string", - "description": "Optional provider override this phase is expected to use." - }, - "model": { - "type": "string", - "description": "Optional model override this phase is expected to use." - } - }, - "required": [ - "title" - ] - } - } - }, - "required": [ - "name", - "description" - ] - }, - "args": { - "type": "object", - "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", - "additionalProperties": true - } - }, - "required": [ - "script", - "meta" - ] - } - }, - { - "name": "write", - "description": "Create or fully replace a UTF-8 text file.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to write, resolved by the filesystem backend." - }, - "content": { - "type": "string", - "description": "Full UTF-8 text content to write." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "content" - ] - } - } - ] - ] -} diff --git a/examples/acp-agent/tests/snapshots/modes-advertise/input.json b/examples/acp-agent/tests/snapshots/modes-advertise/input.json deleted file mode 100644 index 26c56b3425..0000000000 --- a/examples/acp-agent/tests/snapshots/modes-advertise/input.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "steps": [ - { - "op": "initialize" - }, - { - "op": "newSession" - }, - { - "op": "setMode", - "modeId": "plan" - }, - { - "op": "setMode", - "modeId": "default" - }, - { - "op": "setModeExpectError", - "modeId": "yolo" - } - ] -} diff --git a/examples/acp-agent/tests/snapshots/modes-advertise/session.jsonl b/examples/acp-agent/tests/snapshots/modes-advertise/session.jsonl deleted file mode 100644 index a6f73319bc..0000000000 --- a/examples/acp-agent/tests/snapshots/modes-advertise/session.jsonl +++ /dev/null @@ -1 +0,0 @@ -{"type":"session","version":0,"id":"00000000-0000-0000-0000-000000000000","createdAt":0} diff --git a/examples/acp-agent/tests/snapshots/modes-advertise/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/modes-advertise/stdout.expected.jsonl deleted file mode 100644 index f7cc8fe1df..0000000000 --- a/examples/acp-agent/tests/snapshots/modes-advertise/stdout.expected.jsonl +++ /dev/null @@ -1,8 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"current_mode_update","currentModeId":"plan"}}} -{"jsonrpc":"2.0","id":3,"result":{}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"current_mode_update","currentModeId":"default"}}} -{"jsonrpc":"2.0","id":4,"result":{}} -{"jsonrpc":"2.0","id":5,"error":{"code":-32602,"message":"Invalid params: unknown session mode \"yolo\" — available modes: default, plan"}} diff --git a/examples/acp-agent/tests/snapshots/multi-turn/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/multi-turn/stdout.expected.jsonl index ea06457e19..52e86a6a94 100644 --- a/examples/acp-agent/tests/snapshots/multi-turn/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/multi-turn/stdout.expected.jsonl @@ -1,45 +1,6 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Reply with exactly the word:","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" no"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WO"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" no"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"T"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"WO"}}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"TWO"}}}} {"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/packed-chunks/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/packed-chunks/stdout.expected.jsonl index 59c21ed411..2bb15b6f03 100644 --- a/examples/acp-agent/tests/snapshots/packed-chunks/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/packed-chunks/stdout.expected.jsonl @@ -1,75 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" simple"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" result"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","title":"echo HELLO","kind":"execute","status":"in_progress","rawInput":"echo HELLO","content":[{"type":"content","content":{"type":"text","text":"Run echo HELLO"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","status":"failed","content":[{"type":"content","content":{"type":"text","text":"```console\nError: bash is disabled by policy in this session\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" disabled"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" report"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" error"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":">"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" Error"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" disabled"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" session"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" cannot"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" because"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" disabled"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"."}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/parallel-tool-calls/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/parallel-tool-calls/stdout.expected.jsonl index 43066629e4..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/parallel-tool-calls/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/parallel-tool-calls/stdout.expected.jsonl @@ -1,10 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the read tool twice","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_read_a","title":"Read a.txt","kind":"read","status":"in_progress","locations":[{"path":"a.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_read_b","title":"Read b.txt","kind":"read","status":"in_progress","locations":[{"path":"b.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_read_a","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/a.txt</path>\n<type>file</type>\n<content>\n1: alpha\n\n(End of file - total 1 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_read_b","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/b.txt</path>\n<type>file</type>\n<content>\n1: beta\n\n(End of file - total 1 lines)\n</content>"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/permission-switching/input.json b/examples/acp-agent/tests/snapshots/permission-switching/input.json deleted file mode 100644 index 9adb6b1562..0000000000 --- a/examples/acp-agent/tests/snapshots/permission-switching/input.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "steps": [ - { - "op": "initialize" - }, - { - "op": "newSession" - }, - { - "op": "setConfigOption", - "configId": "permission", - "value": "workspace-write" - }, - { - "op": "prompt", - "text": "Use the bash tool to run exactly this one command in a single call: printf 'before\\n' > out.txt && cat out.txt. Then reply with the single word DONE and stop." - }, - { - "op": "setConfigOption", - "configId": "permission", - "value": "danger-full-access" - }, - { - "op": "prompt", - "text": "Use the bash tool to run exactly: cat out.txt. Then reply with the single word DONE and stop." - }, - { - "op": "prompt", - "text": "Without using any tools, state your current approval policy in one short sentence and stop." - } - ] -} diff --git a/examples/acp-agent/tests/snapshots/permission-switching/session.jsonl b/examples/acp-agent/tests/snapshots/permission-switching/session.jsonl deleted file mode 100644 index 381458957c..0000000000 --- a/examples/acp-agent/tests/snapshots/permission-switching/session.jsonl +++ /dev/null @@ -1,239 +0,0 @@ -{"type":"session","version":0,"id":"df041acb-2f14-4d5f-b6e2-2fb6b9eb6427","createdAt":1783860666204,"cwd":"/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-4oJKT4","delegationDepth":0} -{"type":"turn/start","seq":0,"time":1783860666206,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"permission/preset","seq":1,"time":1783962244578,"data":{"preset":"workspace-write"}} -{"type":"sandbox/mode","seq":2,"time":1784518115721,"data":{"mode":"workspace-write"}} -{"type":"approval/policy","seq":3,"time":1783962244578,"data":{"policy":"ask"}} -{"type":"user/message","seq":4,"time":1783962244578,"data":{"content":[{"type":"text","text":"Use the bash tool to run exactly this one command in a single call: printf 'before\\n' > out.txt && cat out.txt. Then reply with the single word DONE and stop."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"session/title","seq":5,"time":1783962244578,"data":{"title":"Use the bash tool to","messageSeqs":[4],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":6,"time":1783962244579,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":7,"time":1783962244580,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"assistant/chunk","seq":8,"time":1783860667444,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":9,"time":1783860667445,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":10,"time":1783860667445,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":11,"time":1783860667446,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":12,"time":1783860667446,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":13,"time":1783860667446,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":14,"time":1783860667478,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} -{"type":"assistant/chunk","seq":15,"time":1783860667478,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":16,"time":1783860667478,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" specific"}}} -{"type":"assistant/chunk","seq":17,"time":1783860667479,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} -{"type":"assistant/chunk","seq":18,"time":1783860667501,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":19,"time":1783860667502,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" then"}}} -{"type":"assistant/chunk","seq":20,"time":1783860667502,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":21,"time":1783860667502,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":22,"time":1783860667502,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":23,"time":1783860667595,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"D"}}} -{"type":"assistant/chunk","seq":24,"time":1783860667596,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} -{"type":"assistant/chunk","seq":25,"time":1783860667623,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} -{"type":"assistant/chunk","seq":26,"time":1783860667624,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":27,"time":1783860667624,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":28,"time":1783860667624,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":29,"time":1783860667624,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":30,"time":1783860667656,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":31,"time":1783860667657,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":32,"time":1783860667657,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":33,"time":1783860667657,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":34,"time":1783860667657,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"printf"}}} -{"type":"assistant/chunk","seq":35,"time":1783860667686,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" '"}}} -{"type":"assistant/chunk","seq":36,"time":1783860667687,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"before"}}} -{"type":"assistant/chunk","seq":37,"time":1783860667687,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"\\\\n"}}} -{"type":"assistant/chunk","seq":38,"time":1783860667687,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"'"}}} -{"type":"assistant/chunk","seq":39,"time":1783860667687,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" >"}}} -{"type":"assistant/chunk","seq":40,"time":1783860667687,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" out"}}} -{"type":"assistant/chunk","seq":41,"time":1783860667710,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":42,"time":1783860667710,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" &&"}}} -{"type":"assistant/chunk","seq":43,"time":1783860667711,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" cat"}}} -{"type":"assistant/chunk","seq":44,"time":1783860667738,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" out"}}} -{"type":"assistant/chunk","seq":45,"time":1783860667739,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":46,"time":1783860667739,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":47,"time":1783860667776,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":48,"time":1783860667776,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":49,"time":1783860667776,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":50,"time":1783860667776,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":51,"time":1783860667796,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":52,"time":1783860667796,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":53,"time":1783860667834,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"Write"}}} -{"type":"assistant/chunk","seq":54,"time":1783860667835,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" and"}}} -{"type":"assistant/chunk","seq":55,"time":1783860667863,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" then"}}} -{"type":"assistant/chunk","seq":56,"time":1783860667863,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" read"}}} -{"type":"assistant/chunk","seq":57,"time":1783860667889,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":" out"}}} -{"type":"assistant/chunk","seq":58,"time":1783860667918,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":59,"time":1783860667918,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":60,"time":1783860667918,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":61,"time":1783860667918,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run a specific command and then reply with \"DONE\"."}}}} -{"type":"assistant/chunk","seq":62,"time":1783962244582,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","arguments":"{\"command\": \"printf 'before\\\\n' > out.txt && cat out.txt\", \"description\": \"Write and then read out.txt\"}"}}}} -{"type":"assistant/chunk","seq":63,"time":1783962244582,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1411,"outputTokens":92,"cacheReadTokens":0,"reasoningTokens":17}}}} -{"type":"assistant/chunk","seq":64,"time":1783962244582,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":65,"time":1783962244582,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to run a specific command and then reply with \"DONE\"."},{"type":"tool-call","id":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","arguments":"{\"command\": \"printf 'before\\\\n' > out.txt && cat out.txt\", \"description\": \"Write and then read out.txt\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":1411,"outputTokens":92,"cacheReadTokens":0,"reasoningTokens":17}},"sourceEventSeqs":[8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64],"surfaceOp":"append"} -{"type":"tool/call","seq":66,"time":1783962244582,"data":{"turn":1,"step":1,"callId":"call_00_E1vtulcKU1LKUgLahxdR3767","name":"bash","arguments":"{\"command\": \"printf 'before\\\\n' > out.txt && cat out.txt\", \"description\": \"Write and then read out.txt\"}"}} -{"type":"tool/result","seq":67,"time":1783962244599,"data":{"turn":1,"step":1,"callId":"call_00_E1vtulcKU1LKUgLahxdR3767","content":[{"type":"text","text":"before\n"}],"isError":false},"sourceEventSeqs":[66],"surfaceOp":"append"} -{"type":"step/end","seq":68,"time":1783962244599,"data":{"turn":1,"step":1}} -{"type":"step/start","seq":69,"time":1783962244600,"data":{"turn":1,"step":2}} -{"type":"assistant/chunk","seq":70,"time":1783860669145,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":71,"time":1783860669172,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":72,"time":1783860669174,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} -{"type":"assistant/chunk","seq":73,"time":1783860669209,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" ran"}}} -{"type":"assistant/chunk","seq":74,"time":1783860669210,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" successfully"}}} -{"type":"assistant/chunk","seq":75,"time":1783860669235,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":76,"time":1783860669235,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" output"}}} -{"type":"assistant/chunk","seq":77,"time":1783860669236,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":78,"time":1783860669262,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"before"}}} -{"type":"assistant/chunk","seq":79,"time":1783860669264,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} -{"type":"assistant/chunk","seq":80,"time":1783860669264,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" Now"}}} -{"type":"assistant/chunk","seq":81,"time":1783860669264,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":82,"time":1783860669264,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" need"}}} -{"type":"assistant/chunk","seq":83,"time":1783860669292,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":84,"time":1783860669292,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":85,"time":1783860669322,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":86,"time":1783860669323,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" just"}}} -{"type":"assistant/chunk","seq":87,"time":1783860669356,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":88,"time":1783860669357,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" word"}}} -{"type":"assistant/chunk","seq":89,"time":1783860669357,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" D"}}} -{"type":"assistant/chunk","seq":90,"time":1783860669357,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} -{"type":"assistant/chunk","seq":91,"time":1783860669357,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":92,"time":1783860669357,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":93,"time":1783860669357,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} -{"type":"assistant/chunk","seq":94,"time":1783860669357,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} -{"type":"assistant/chunk","seq":95,"time":1783860669357,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The command ran successfully, output \"before\". Now I need to reply with just the word DONE."}}}} -{"type":"assistant/chunk","seq":96,"time":1783962244601,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} -{"type":"assistant/chunk","seq":97,"time":1783962244601,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":109,"outputTokens":24,"cacheReadTokens":1408,"reasoningTokens":21}}}} -{"type":"assistant/chunk","seq":98,"time":1783962244601,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":99,"time":1783962244601,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The command ran successfully, output \"before\". Now I need to reply with just the word DONE."},{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":109,"outputTokens":24,"cacheReadTokens":1408,"reasoningTokens":21}},"sourceEventSeqs":[70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98],"surfaceOp":"append"} -{"type":"step/end","seq":100,"time":1783962244601,"data":{"turn":1,"step":2}} -{"type":"turn/end","seq":101,"time":1783962244601,"data":{"turn":1,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":102,"time":1783962244623,"data":{"turn":2,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"permission/preset","seq":103,"time":1783962244624,"data":{"preset":"danger-full-access"}} -{"type":"sandbox/mode","seq":104,"time":1784518115842,"data":{"mode":"danger-full-access"}} -{"type":"approval/policy","seq":105,"time":1783962244624,"data":{"policy":"never"}} -{"type":"user/message","seq":106,"time":1783962244624,"data":{"content":[{"type":"text","text":"Use the bash tool to run exactly: cat out.txt. Then reply with the single word DONE and stop."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"user/message","seq":107,"time":1783962244624,"data":{"content":[{"type":"text","text":"The approval policy changed from \"ask\" to \"never\" (changed by the user)."}],"source":{"kind":"plugin","plugin":"user-approval"}},"surfaceOp":"append"} -{"type":"step/start","seq":108,"time":1783962244624,"data":{"turn":2,"step":1}} -{"type":"request/header","seq":109,"time":1784000791271,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"change"}} -{"type":"assistant/chunk","seq":110,"time":1783860671025,"data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":111,"time":1783860671026,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":112,"time":1783860671026,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":113,"time":1783860671026,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":114,"time":1783860671026,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":115,"time":1783860671079,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":116,"time":1783860671080,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} -{"type":"assistant/chunk","seq":117,"time":1783860671080,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":118,"time":1783860671080,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"cat"}}} -{"type":"assistant/chunk","seq":119,"time":1783860671080,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" out"}}} -{"type":"assistant/chunk","seq":120,"time":1783860671080,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".txt"}}} -{"type":"assistant/chunk","seq":121,"time":1783860671097,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":122,"time":1783860671101,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":123,"time":1783860671101,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" then"}}} -{"type":"assistant/chunk","seq":124,"time":1783860671102,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":125,"time":1783860671102,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":126,"time":1783860671102,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":127,"time":1783860671175,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"D"}}} -{"type":"assistant/chunk","seq":128,"time":1783860671175,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} -{"type":"assistant/chunk","seq":129,"time":1783860671211,"data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} -{"type":"assistant/chunk","seq":130,"time":1783860671212,"data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":131,"time":1783860671212,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":132,"time":1783860671228,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":133,"time":1783860671229,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":134,"time":1783860671229,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":135,"time":1783860671229,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":136,"time":1783860671261,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":137,"time":1783860671262,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":138,"time":1783860671301,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"Read"}}} -{"type":"assistant/chunk","seq":139,"time":1783860671316,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":" out"}}} -{"type":"assistant/chunk","seq":140,"time":1783860671316,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":141,"time":1783860671316,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":142,"time":1783860671316,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":143,"time":1783860671316,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":144,"time":1783860671350,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":145,"time":1783860671351,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":146,"time":1783860671351,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":147,"time":1783860671351,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":148,"time":1783860671388,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"cat"}}} -{"type":"assistant/chunk","seq":149,"time":1783860671388,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":" out"}}} -{"type":"assistant/chunk","seq":150,"time":1783860671435,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":151,"time":1783860671435,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":152,"time":1783860671436,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":153,"time":1783860671436,"data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run `cat out.txt` and then reply with \"DONE\"."}}}} -{"type":"assistant/chunk","seq":154,"time":1783962244626,"data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","arguments":"{\"description\": \"Read out.txt\", \"command\": \"cat out.txt\"}"}}}} -{"type":"assistant/chunk","seq":155,"time":1783962244626,"data":{"turn":2,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1608,"outputTokens":82,"cacheReadTokens":0,"reasoningTokens":19}}}} -{"type":"assistant/chunk","seq":156,"time":1783962244626,"data":{"turn":2,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":157,"time":1783962244626,"data":{"turn":2,"step":1,"content":[{"type":"reasoning","text":"The user wants me to run `cat out.txt` and then reply with \"DONE\"."},{"type":"tool-call","id":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","arguments":"{\"description\": \"Read out.txt\", \"command\": \"cat out.txt\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":1608,"outputTokens":82,"cacheReadTokens":0,"reasoningTokens":19}},"sourceEventSeqs":[110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156],"surfaceOp":"append"} -{"type":"tool/call","seq":158,"time":1783962244626,"data":{"turn":2,"step":1,"callId":"call_00_7Jb7FWHNjIBVML49dEJl1990","name":"bash","arguments":"{\"description\": \"Read out.txt\", \"command\": \"cat out.txt\"}"}} -{"type":"tool/result","seq":159,"time":1783962244631,"data":{"turn":2,"step":1,"callId":"call_00_7Jb7FWHNjIBVML49dEJl1990","content":[{"type":"text","text":"before\n"}],"isError":false},"sourceEventSeqs":[158],"surfaceOp":"append"} -{"type":"step/end","seq":160,"time":1783962244631,"data":{"turn":2,"step":1}} -{"type":"step/start","seq":161,"time":1783962244631,"data":{"turn":2,"step":2}} -{"type":"assistant/chunk","seq":162,"time":1783860673229,"data":{"turn":2,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} -{"type":"assistant/chunk","seq":163,"time":1783860673229,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":0,"text":"D"}}} -{"type":"assistant/chunk","seq":164,"time":1783860673229,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":0,"text":"ONE"}}} -{"type":"assistant/chunk","seq":165,"time":1783962244632,"data":{"turn":2,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}}} -{"type":"assistant/chunk","seq":166,"time":1783962244632,"data":{"turn":2,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":40,"outputTokens":3,"cacheReadTokens":1664,"reasoningTokens":0}}}} -{"type":"assistant/chunk","seq":167,"time":1783962244632,"data":{"turn":2,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":168,"time":1783962244632,"data":{"turn":2,"step":2,"content":[{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":40,"outputTokens":3,"cacheReadTokens":1664,"reasoningTokens":0}},"sourceEventSeqs":[162,163,164,165,166,167],"surfaceOp":"append"} -{"type":"step/end","seq":169,"time":1783962244632,"data":{"turn":2,"step":2}} -{"type":"turn/end","seq":170,"time":1783962244632,"data":{"turn":2,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":171,"time":1783962244637,"data":{"turn":3,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":172,"time":1783962244637,"data":{"content":[{"type":"text","text":"Without using any tools, state your current approval policy in one short sentence and stop."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"step/start","seq":173,"time":1783962244637,"data":{"turn":3,"step":1}} -{"type":"assistant/chunk","seq":174,"time":1783860674433,"data":{"turn":3,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":175,"time":1783860674435,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":176,"time":1783860674435,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":177,"time":1783860674465,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":178,"time":1783860674465,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":179,"time":1783860674499,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":180,"time":1783860674500,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" state"}}} -{"type":"assistant/chunk","seq":181,"time":1783860674500,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":182,"time":1783860674500,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" current"}}} -{"type":"assistant/chunk","seq":183,"time":1783860674500,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" approval"}}} -{"type":"assistant/chunk","seq":184,"time":1783860674525,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" policy"}}} -{"type":"assistant/chunk","seq":185,"time":1783860674526,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" without"}}} -{"type":"assistant/chunk","seq":186,"time":1783860674526,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" using"}}} -{"type":"assistant/chunk","seq":187,"time":1783860674526,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" any"}}} -{"type":"assistant/chunk","seq":188,"time":1783860674526,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" tools"}}} -{"type":"assistant/chunk","seq":189,"time":1783860674550,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":190,"time":1783860674550,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" From"}}} -{"type":"assistant/chunk","seq":191,"time":1783860674581,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":192,"time":1783860674582,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" context"}}} -{"type":"assistant/chunk","seq":193,"time":1783860674582,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" provided"}}} -{"type":"assistant/chunk","seq":194,"time":1783860674610,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":195,"time":1783860674611,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":196,"time":1783860674611,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" approval"}}} -{"type":"assistant/chunk","seq":197,"time":1783860674611,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" policy"}}} -{"type":"assistant/chunk","seq":198,"time":1783860674638,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" changed"}}} -{"type":"assistant/chunk","seq":199,"time":1783860674638,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" from"}}} -{"type":"assistant/chunk","seq":200,"time":1783860674638,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":201,"time":1783860674638,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ask"}}} -{"type":"assistant/chunk","seq":202,"time":1783860674638,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\""}}} -{"type":"assistant/chunk","seq":203,"time":1783860674640,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":204,"time":1783860674698,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":205,"time":1783860674698,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"never"}}} -{"type":"assistant/chunk","seq":206,"time":1783860674700,"data":{"turn":3,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} -{"type":"assistant/chunk","seq":207,"time":1783860674726,"data":{"turn":3,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":208,"time":1783860674726,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":"My"}}} -{"type":"assistant/chunk","seq":209,"time":1783860674727,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" approval"}}} -{"type":"assistant/chunk","seq":210,"time":1783860674727,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" policy"}}} -{"type":"assistant/chunk","seq":211,"time":1783860674754,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" is"}}} -{"type":"assistant/chunk","seq":212,"time":1783860674757,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" set"}}} -{"type":"assistant/chunk","seq":213,"time":1783860674757,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" to"}}} -{"type":"assistant/chunk","seq":214,"time":1783860674757,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" \""}}} -{"type":"assistant/chunk","seq":215,"time":1783860674757,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":"never"}}} -{"type":"assistant/chunk","seq":216,"time":1783860674786,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":"\""}}} -{"type":"assistant/chunk","seq":217,"time":1783860674817,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" —"}}} -{"type":"assistant/chunk","seq":218,"time":1783860674846,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" no"}}} -{"type":"assistant/chunk","seq":219,"time":1783860674875,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" actions"}}} -{"type":"assistant/chunk","seq":220,"time":1783860674879,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" requiring"}}} -{"type":"assistant/chunk","seq":221,"time":1783860674880,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" approval"}}} -{"type":"assistant/chunk","seq":222,"time":1783860674904,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" are"}}} -{"type":"assistant/chunk","seq":223,"time":1783860674906,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" permitted"}}} -{"type":"assistant/chunk","seq":224,"time":1783860674906,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":225,"time":1783860674939,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" and"}}} -{"type":"assistant/chunk","seq":226,"time":1783860674940,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" they"}}} -{"type":"assistant/chunk","seq":227,"time":1783860674940,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" are"}}} -{"type":"assistant/chunk","seq":228,"time":1783860674940,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" rejected"}}} -{"type":"assistant/chunk","seq":229,"time":1783860674940,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":" automatically"}}} -{"type":"assistant/chunk","seq":230,"time":1783860674940,"data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":1,"text":"."}}} -{"type":"assistant/chunk","seq":231,"time":1783860674940,"data":{"turn":3,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to state the current approval policy without using any tools. From the context provided, the approval policy changed from \"ask\" to \"never\"."}}}} -{"type":"assistant/chunk","seq":232,"time":1783962244639,"data":{"turn":3,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"My approval policy is set to \"never\" — no actions requiring approval are permitted, and they are rejected automatically."}}}} -{"type":"assistant/chunk","seq":233,"time":1783962244639,"data":{"turn":3,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":64,"outputTokens":56,"cacheReadTokens":1664,"reasoningTokens":32}}}} -{"type":"assistant/chunk","seq":234,"time":1783962244639,"data":{"turn":3,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":235,"time":1783962244640,"data":{"turn":3,"step":1,"content":[{"type":"reasoning","text":"The user wants me to state the current approval policy without using any tools. From the context provided, the approval policy changed from \"ask\" to \"never\"."},{"type":"text","text":"My approval policy is set to \"never\" — no actions requiring approval are permitted, and they are rejected automatically."}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":64,"outputTokens":56,"cacheReadTokens":1664,"reasoningTokens":32}},"sourceEventSeqs":[174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234],"surfaceOp":"append"} -{"type":"step/end","seq":236,"time":1783962244640,"data":{"turn":3,"step":1}} -{"type":"turn/end","seq":237,"time":1783962244640,"data":{"turn":3,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/permission-switching/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/permission-switching/stdout.expected.jsonl deleted file mode 100644 index 7e51129a1d..0000000000 --- a/examples/acp-agent/tests/snapshots/permission-switching/stdout.expected.jsonl +++ /dev/null @@ -1,129 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"workspace-write","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" specific"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_E1vtulcKU1LKUgLahxdR3767","title":"printf 'before\\n' > out.txt && cat out.txt","kind":"execute","status":"in_progress","rawInput":"printf 'before\\n' > out.txt && cat out.txt","content":[{"type":"content","content":{"type":"text","text":"Write and then read out.txt"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_E1vtulcKU1LKUgLahxdR3767","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nbefore\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ran"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" successfully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" output"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"before"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} -{"jsonrpc":"2.0","id":5,"result":{"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"cat"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" out"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_7Jb7FWHNjIBVML49dEJl1990","title":"cat out.txt","kind":"execute","status":"in_progress","rawInput":"cat out.txt","content":[{"type":"content","content":{"type":"text","text":"Read out.txt"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_7Jb7FWHNjIBVML49dEJl1990","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nbefore\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","id":6,"result":{"stopReason":"end_turn"}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" state"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" current"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" approval"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" without"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" any"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" From"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" context"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" provided"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" approval"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" changed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" from"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ask"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"never"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"My"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" approval"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" policy"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" set"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"never"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" —"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" no"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" actions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" requiring"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" approval"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" are"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" permitted"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" they"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" are"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" rejected"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" automatically"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","id":7,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md deleted file mode 100644 index 55b309bbc3..0000000000 --- a/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md +++ /dev/null @@ -1,56 +0,0 @@ -You are an AI agent powered by the DeepSeek Harness SDK. - -You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. - -Verify your work by running the code or tests. Keep answers brief and factual. - - -Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. - -Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes. - -Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session. - -Check the [exit code: N] marker on every bash result; investigate failures before moving on. - -Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. - -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - -Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. - -<!-- dsh-user-approval-policy:ask --> - -Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. - -Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. - -<!-- request/header change 1 --> - -You are an AI agent powered by the DeepSeek Harness SDK. - -You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. - -Verify your work by running the code or tests. Keep answers brief and factual. - - -Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. - -Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes. - -Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session. - -Check the [exit code: N] marker on every bash result; investigate failures before moving on. - -Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. - -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - -Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. - -Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). -<!-- dsh-user-approval-policy:never --> - -Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. - -Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. diff --git a/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json deleted file mode 100644 index 8bfac915b0..0000000000 --- a/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json +++ /dev/null @@ -1,1510 +0,0 @@ -{ - "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, - { - "name": "bash", - "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", - "parameters": { - "type": "object", - "properties": { - "command": { - "type": "string", - "description": "The bash command to execute." - }, - "description": { - "type": "string", - "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." - }, - "timeoutMs": { - "type": "number", - "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." - }, - "workdir": { - "type": "string", - "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." - }, - "run_in_background": { - "type": "boolean", - "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." - } - }, - "required": [ - "command", - "description" - ] - } - }, - { - "name": "create_goal", - "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The concrete completion objective inferred from the direct human request." - }, - "max_goal_rounds": { - "type": "number", - "description": "Optional positive safe-integer limit on automatic continuation rounds." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "edit", - "description": "Edit an existing UTF-8 text file by replacing literal text.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to edit, resolved by the filesystem backend." - }, - "old_string": { - "type": "string", - "description": "Literal text to replace. Must match exactly." - }, - "new_string": { - "type": "string", - "description": "Literal replacement text. Use an empty string to delete the match." - }, - "replace_all": { - "type": "boolean", - "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "old_string", - "new_string" - ] - } - }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, - { - "name": "get_goal", - "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "ralph", - "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The immutable completion objective for every fresh Ralph round." - }, - "maxRounds": { - "type": "number", - "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "read", - "description": "Read a UTF-8 text file and return line-numbered content.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to read, resolved by the filesystem backend." - }, - "offset": { - "type": "number", - "description": "1-based first line to return. Defaults to 1." - }, - "limit": { - "type": "number", - "description": "Maximum number of lines to return. Defaults to 2000." - } - }, - "required": [ - "file_path" - ] - } - }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, - { - "name": "skill", - "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", - "parameters": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The exact skill name from the available skills list." - } - }, - "required": [ - "name" - ] - } - }, - { - "name": "subagent", - "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "subagent_fork", - "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "task_kill", - "description": "Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "reason": { - "type": "string", - "description": "Optional short reason, recorded in the log and forwarded to the task." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "task_list", - "description": "List your background tasks (running and finished) with their ids, kinds, and statuses.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "task_output", - "description": "Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "wait": { - "type": "boolean", - "description": "Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive." - }, - "timeout_ms": { - "type": "number", - "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "todo_write", - "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", - "parameters": { - "type": "object", - "properties": { - "todos": { - "type": "array", - "description": "The COMPLETE task list, replacing any previous list.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "content": { - "type": "string", - "description": "What the task is — a short imperative line." - }, - "status": { - "type": "string", - "description": "pending (not started) | in_progress (now) | completed (done).", - "enum": [ - "pending", - "in_progress", - "completed" - ] - } - }, - "required": [ - "content", - "status" - ] - } - } - }, - "required": [ - "todos" - ] - } - }, - { - "name": "update_goal", - "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", - "parameters": { - "type": "object", - "properties": { - "goal_id": { - "type": "string", - "description": "Exact id returned by get_goal." - }, - "revision": { - "type": "number", - "description": "Exact positive revision returned by get_goal." - }, - "action": { - "type": "string", - "description": "edit | pause | resume | complete | blocked", - "enum": [ - "edit", - "pause", - "resume", - "complete", - "blocked" - ] - }, - "objective": { - "type": "string", - "description": "Replacement objective; valid only with action edit." - }, - "max_goal_rounds": { - "type": "number", - "description": "Replacement cap; valid only with action edit." - }, - "blocked_reason": { - "type": "string", - "description": "Concrete blocking condition; required only with action blocked." - } - }, - "required": [ - "goal_id", - "revision", - "action" - ] - } - }, - { - "name": "workflow", - "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return <value>` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", - "parameters": { - "type": "object", - "properties": { - "script": { - "type": "string", - "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)." - }, - "meta": { - "type": "object", - "description": "The workflow identity block (plain JSON — never code).", - "additionalProperties": true, - "properties": { - "name": { - "type": "string", - "description": "Short kebab-case workflow name." - }, - "description": { - "type": "string", - "description": "One-line description of what the workflow does." - }, - "whenToUse": { - "type": "string", - "description": "Optional guidance on when this workflow applies." - }, - "phases": { - "type": "array", - "description": "Optional phase declarations matched by phase() calls.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "title": { - "type": "string", - "description": "The phase title phase() calls match by exact string." - }, - "detail": { - "type": "string", - "description": "Optional one-line description of the phase." - }, - "provider": { - "type": "string", - "description": "Optional provider override this phase is expected to use." - }, - "model": { - "type": "string", - "description": "Optional model override this phase is expected to use." - } - }, - "required": [ - "title" - ] - } - } - }, - "required": [ - "name", - "description" - ] - }, - "args": { - "type": "object", - "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", - "additionalProperties": true - } - }, - "required": [ - "script", - "meta" - ] - } - }, - { - "name": "write", - "description": "Create or fully replace a UTF-8 text file.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to write, resolved by the filesystem backend." - }, - "content": { - "type": "string", - "description": "Full UTF-8 text content to write." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "content" - ] - } - } - ], - "changes": [ - [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, - { - "name": "bash", - "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", - "parameters": { - "type": "object", - "properties": { - "command": { - "type": "string", - "description": "The bash command to execute." - }, - "description": { - "type": "string", - "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." - }, - "timeoutMs": { - "type": "number", - "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." - }, - "workdir": { - "type": "string", - "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." - }, - "run_in_background": { - "type": "boolean", - "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." - } - }, - "required": [ - "command", - "description" - ] - } - }, - { - "name": "create_goal", - "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The concrete completion objective inferred from the direct human request." - }, - "max_goal_rounds": { - "type": "number", - "description": "Optional positive safe-integer limit on automatic continuation rounds." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "edit", - "description": "Edit an existing UTF-8 text file by replacing literal text.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to edit, resolved by the filesystem backend." - }, - "old_string": { - "type": "string", - "description": "Literal text to replace. Must match exactly." - }, - "new_string": { - "type": "string", - "description": "Literal replacement text. Use an empty string to delete the match." - }, - "replace_all": { - "type": "boolean", - "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "old_string", - "new_string" - ] - } - }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, - { - "name": "get_goal", - "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "ralph", - "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The immutable completion objective for every fresh Ralph round." - }, - "maxRounds": { - "type": "number", - "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "read", - "description": "Read a UTF-8 text file and return line-numbered content.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to read, resolved by the filesystem backend." - }, - "offset": { - "type": "number", - "description": "1-based first line to return. Defaults to 1." - }, - "limit": { - "type": "number", - "description": "Maximum number of lines to return. Defaults to 2000." - } - }, - "required": [ - "file_path" - ] - } - }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, - { - "name": "skill", - "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", - "parameters": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The exact skill name from the available skills list." - } - }, - "required": [ - "name" - ] - } - }, - { - "name": "subagent", - "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "subagent_fork", - "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "task_kill", - "description": "Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "reason": { - "type": "string", - "description": "Optional short reason, recorded in the log and forwarded to the task." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "task_list", - "description": "List your background tasks (running and finished) with their ids, kinds, and statuses.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "task_output", - "description": "Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "wait": { - "type": "boolean", - "description": "Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive." - }, - "timeout_ms": { - "type": "number", - "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "todo_write", - "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", - "parameters": { - "type": "object", - "properties": { - "todos": { - "type": "array", - "description": "The COMPLETE task list, replacing any previous list.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "content": { - "type": "string", - "description": "What the task is — a short imperative line." - }, - "status": { - "type": "string", - "description": "pending (not started) | in_progress (now) | completed (done).", - "enum": [ - "pending", - "in_progress", - "completed" - ] - } - }, - "required": [ - "content", - "status" - ] - } - } - }, - "required": [ - "todos" - ] - } - }, - { - "name": "update_goal", - "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", - "parameters": { - "type": "object", - "properties": { - "goal_id": { - "type": "string", - "description": "Exact id returned by get_goal." - }, - "revision": { - "type": "number", - "description": "Exact positive revision returned by get_goal." - }, - "action": { - "type": "string", - "description": "edit | pause | resume | complete | blocked", - "enum": [ - "edit", - "pause", - "resume", - "complete", - "blocked" - ] - }, - "objective": { - "type": "string", - "description": "Replacement objective; valid only with action edit." - }, - "max_goal_rounds": { - "type": "number", - "description": "Replacement cap; valid only with action edit." - }, - "blocked_reason": { - "type": "string", - "description": "Concrete blocking condition; required only with action blocked." - } - }, - "required": [ - "goal_id", - "revision", - "action" - ] - } - }, - { - "name": "workflow", - "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return <value>` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", - "parameters": { - "type": "object", - "properties": { - "script": { - "type": "string", - "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)." - }, - "meta": { - "type": "object", - "description": "The workflow identity block (plain JSON — never code).", - "additionalProperties": true, - "properties": { - "name": { - "type": "string", - "description": "Short kebab-case workflow name." - }, - "description": { - "type": "string", - "description": "One-line description of what the workflow does." - }, - "whenToUse": { - "type": "string", - "description": "Optional guidance on when this workflow applies." - }, - "phases": { - "type": "array", - "description": "Optional phase declarations matched by phase() calls.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "title": { - "type": "string", - "description": "The phase title phase() calls match by exact string." - }, - "detail": { - "type": "string", - "description": "Optional one-line description of the phase." - }, - "provider": { - "type": "string", - "description": "Optional provider override this phase is expected to use." - }, - "model": { - "type": "string", - "description": "Optional model override this phase is expected to use." - } - }, - "required": [ - "title" - ] - } - } - }, - "required": [ - "name", - "description" - ] - }, - "args": { - "type": "object", - "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", - "additionalProperties": true - } - }, - "required": [ - "script", - "meta" - ] - } - }, - { - "name": "write", - "description": "Create or fully replace a UTF-8 text file.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to write, resolved by the filesystem backend." - }, - "content": { - "type": "string", - "description": "Full UTF-8 text content to write." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "content" - ] - } - } - ] - ] -} diff --git a/examples/acp-agent/tests/snapshots/permission-switching/workspace/notes.txt b/examples/acp-agent/tests/snapshots/permission-switching/workspace/notes.txt deleted file mode 100644 index a6eda7f939..0000000000 --- a/examples/acp-agent/tests/snapshots/permission-switching/workspace/notes.txt +++ /dev/null @@ -1 +0,0 @@ -hello from the sandboxed workspace diff --git a/examples/acp-agent/tests/snapshots/plan-mode-reject/input.json b/examples/acp-agent/tests/snapshots/plan-mode-reject/input.json deleted file mode 100644 index 07c135a87f..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode-reject/input.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "steps": [ - { - "op": "initialize" - }, - { - "op": "newSession" - }, - { - "op": "setMode", - "modeId": "plan" - }, - { - "op": "prompt", - "text": "Read the file notes.txt (use the relative path notes.txt exactly, never an absolute path), then present a short plan titled '# Fix the greeting typo' via exit_plan_mode, exactly once. If the review does not approve, summarize the reviewer's feedback in plain text and end your reply - do not present the plan again." - } - ], - "elicitationAnswers": [ - { - "action": "accept", - "custom": "Also add a verification step that re-reads the file after the fix." - } - ] -} diff --git a/examples/acp-agent/tests/snapshots/plan-mode-reject/session.jsonl b/examples/acp-agent/tests/snapshots/plan-mode-reject/session.jsonl deleted file mode 100644 index cad0f9cfb4..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode-reject/session.jsonl +++ /dev/null @@ -1,425 +0,0 @@ -{"type":"session","version":0,"id":"50138298-1385-449e-b252-146acb0571d0","createdAt":1784525384931,"cwd":"/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-DTr6Ra","delegationDepth":0} -{"type":"turn/start","seq":0,"time":1784525384935,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"plan/mode","seq":1,"time":1784525384935,"data":{"active":true}} -{"type":"user/message","seq":2,"time":1784525384935,"data":{"content":[{"type":"text","text":"Read the file notes.txt (use the relative path notes.txt exactly, never an absolute path), then present a short plan titled '# Fix the greeting typo' via exit_plan_mode, exactly once. If the review does not approve, summarize the reviewer's feedback in plain text and end your reply - do not present the plan again."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"session/title","seq":3,"time":1784525384935,"data":{"title":"Read the file notes.txt (use","messageSeqs":[2],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":4,"time":1784525384938,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":5,"time":1784525384938,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"assistant/chunk","seq":6,"time":1784525385351,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":7,"time":1784525385352,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":8,"time":1784525385471,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":9,"time":1784525385503,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":10,"time":1784525385503,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":11,"time":1784525385504,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":12,"time":1784525385504,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" read"}}} -{"type":"assistant/chunk","seq":13,"time":1784525385533,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":14,"time":1784525385534,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":15,"time":1784525385564,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" notes"}}} -{"type":"assistant/chunk","seq":16,"time":1784525385565,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".txt"}}} -{"type":"assistant/chunk","seq":17,"time":1784525385565,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" using"}}} -{"type":"assistant/chunk","seq":18,"time":1784525385595,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":19,"time":1784525385596,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" relative"}}} -{"type":"assistant/chunk","seq":20,"time":1784525385597,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" path"}}} -{"type":"assistant/chunk","seq":21,"time":1784525385597,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":22,"time":1784525385597,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" then"}}} -{"type":"assistant/chunk","seq":23,"time":1784525385597,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" present"}}} -{"type":"assistant/chunk","seq":24,"time":1784525385626,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":25,"time":1784525385626,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" plan"}}} -{"type":"assistant/chunk","seq":26,"time":1784525385626,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" via"}}} -{"type":"assistant/chunk","seq":27,"time":1784525385657,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" exit"}}} -{"type":"assistant/chunk","seq":28,"time":1784525385658,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_"}}} -{"type":"assistant/chunk","seq":29,"time":1784525385658,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"plan"}}} -{"type":"assistant/chunk","seq":30,"time":1784525385658,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_mode"}}} -{"type":"assistant/chunk","seq":31,"time":1784525385658,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":32,"time":1784525385658,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} -{"type":"assistant/chunk","seq":33,"time":1784525385688,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":34,"time":1784525385689,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" start"}}} -{"type":"assistant/chunk","seq":35,"time":1784525385719,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" by"}}} -{"type":"assistant/chunk","seq":36,"time":1784525385719,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" reading"}}} -{"type":"assistant/chunk","seq":37,"time":1784525385720,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":38,"time":1784525385720,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":39,"time":1784525385720,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":40,"time":1784525385812,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":41,"time":1784525385813,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":42,"time":1784525385843,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":43,"time":1784525385844,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":44,"time":1784525385844,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":"file"}}} -{"type":"assistant/chunk","seq":45,"time":1784525385844,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":"_path"}}} -{"type":"assistant/chunk","seq":46,"time":1784525385844,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":47,"time":1784525385844,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":48,"time":1784525385874,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":49,"time":1784525385875,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":"notes"}}} -{"type":"assistant/chunk","seq":50,"time":1784525385875,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":51,"time":1784525385906,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":52,"time":1784525385906,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":53,"time":1784525385972,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to read the file notes.txt using the relative path, then present a plan via exit_plan_mode. Let me start by reading the file."}}}} -{"type":"assistant/chunk","seq":54,"time":1784525385972,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","arguments":"{\"file_path\": \"notes.txt\"}"}}}} -{"type":"assistant/chunk","seq":55,"time":1784525385972,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3171,"outputTokens":78,"cacheReadTokens":0,"reasoningTokens":33}}}} -{"type":"assistant/chunk","seq":56,"time":1784525385972,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":57,"time":1784525385977,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to read the file notes.txt using the relative path, then present a plan via exit_plan_mode. Let me start by reading the file."},{"type":"tool-call","id":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","arguments":"{\"file_path\": \"notes.txt\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":3171,"outputTokens":78,"cacheReadTokens":0,"reasoningTokens":33}},"sourceEventSeqs":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56],"surfaceOp":"append"} -{"type":"tool/call","seq":58,"time":1784525385977,"data":{"turn":1,"step":1,"callId":"call_00_Tez1Df1H9v8RqxqYIs5o6697","name":"read","arguments":"{\"file_path\": \"notes.txt\"}"}} -{"type":"tool/result","seq":59,"time":1784525385985,"data":{"turn":1,"step":1,"callId":"call_00_Tez1Df1H9v8RqxqYIs5o6697","content":[{"type":"text","text":"<path>/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-DTr6Ra/notes.txt</path>\n<type>file</type>\n<content>\n1: project notes\n2: - the greeting message still says \"helo wrld\"\n\n(End of file - total 2 lines)\n</content>"}],"isError":false},"sourceEventSeqs":[58],"surfaceOp":"append"} -{"type":"step/end","seq":60,"time":1784525385986,"data":{"turn":1,"step":1}} -{"type":"step/start","seq":61,"time":1784525385987,"data":{"turn":1,"step":2}} -{"type":"assistant/chunk","seq":62,"time":1784525386578,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":63,"time":1784525386579,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":64,"time":1784525386701,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":65,"time":1784525386729,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" contains"}}} -{"type":"assistant/chunk","seq":66,"time":1784525386730,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":67,"time":1784525386730,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" single"}}} -{"type":"assistant/chunk","seq":68,"time":1784525386760,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" note"}}} -{"type":"assistant/chunk","seq":69,"time":1784525386787,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":":"}}} -{"type":"assistant/chunk","seq":70,"time":1784525386787,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":71,"time":1784525386816,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"the"}}} -{"type":"assistant/chunk","seq":72,"time":1784525386817,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" greeting"}}} -{"type":"assistant/chunk","seq":73,"time":1784525386817,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" message"}}} -{"type":"assistant/chunk","seq":74,"time":1784525386817,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" still"}}} -{"type":"assistant/chunk","seq":75,"time":1784525386817,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" says"}}} -{"type":"assistant/chunk","seq":76,"time":1784525386818,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" '"}}} -{"type":"assistant/chunk","seq":77,"time":1784525386845,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"hel"}}} -{"type":"assistant/chunk","seq":78,"time":1784525386845,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"o"}}} -{"type":"assistant/chunk","seq":79,"time":1784525386846,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" wr"}}} -{"type":"assistant/chunk","seq":80,"time":1784525386846,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ld"}}} -{"type":"assistant/chunk","seq":81,"time":1784525386846,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"'\"."}}} -{"type":"assistant/chunk","seq":82,"time":1784525386846,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" The"}}} -{"type":"assistant/chunk","seq":83,"time":1784525386872,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":84,"time":1784525386873,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":85,"time":1784525386873,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":86,"time":1784525386902,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" plan"}}} -{"type":"assistant/chunk","seq":87,"time":1784525386902,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" titled"}}} -{"type":"assistant/chunk","seq":88,"time":1784525386902,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \"#"}}} -{"type":"assistant/chunk","seq":89,"time":1784525386930,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" Fix"}}} -{"type":"assistant/chunk","seq":90,"time":1784525386930,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":91,"time":1784525386931,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" greeting"}}} -{"type":"assistant/chunk","seq":92,"time":1784525386959,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" typ"}}} -{"type":"assistant/chunk","seq":93,"time":1784525386959,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"o"}}} -{"type":"assistant/chunk","seq":94,"time":1784525386959,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} -{"type":"assistant/chunk","seq":95,"time":1784525386959,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} -{"type":"assistant/chunk","seq":96,"time":1784525386959,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":97,"time":1784525386959,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" present"}}} -{"type":"assistant/chunk","seq":98,"time":1784525386987,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":99,"time":1784525386988,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" simple"}}} -{"type":"assistant/chunk","seq":100,"time":1784525387016,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" plan"}}} -{"type":"assistant/chunk","seq":101,"time":1784525387017,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":102,"time":1784525387017,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" fix"}}} -{"type":"assistant/chunk","seq":103,"time":1784525387046,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" this"}}} -{"type":"assistant/chunk","seq":104,"time":1784525387047,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" typ"}}} -{"type":"assistant/chunk","seq":105,"time":1784525387047,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"o"}}} -{"type":"assistant/chunk","seq":106,"time":1784525387047,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":107,"time":1784525387160,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":108,"time":1784525387160,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":109,"time":1784525387188,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":110,"time":1784525387189,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":111,"time":1784525387189,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"plan"}}} -{"type":"assistant/chunk","seq":112,"time":1784525387189,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":113,"time":1784525387189,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":114,"time":1784525387217,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":115,"time":1784525387217,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"#"}}} -{"type":"assistant/chunk","seq":116,"time":1784525387217,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" Fix"}}} -{"type":"assistant/chunk","seq":117,"time":1784525387217,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":118,"time":1784525387245,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" greeting"}}} -{"type":"assistant/chunk","seq":119,"time":1784525387246,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" typ"}}} -{"type":"assistant/chunk","seq":120,"time":1784525387246,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"o"}}} -{"type":"assistant/chunk","seq":121,"time":1784525387246,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\\n\\n"}}} -{"type":"assistant/chunk","seq":122,"time":1784525387246,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"**"}}} -{"type":"assistant/chunk","seq":123,"time":1784525387273,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"Issue"}}} -{"type":"assistant/chunk","seq":124,"time":1784525387302,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":":**"}}} -{"type":"assistant/chunk","seq":125,"time":1784525387303,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" The"}}} -{"type":"assistant/chunk","seq":126,"time":1784525387303,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" greeting"}}} -{"type":"assistant/chunk","seq":127,"time":1784525387332,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" message"}}} -{"type":"assistant/chunk","seq":128,"time":1784525387333,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" currently"}}} -{"type":"assistant/chunk","seq":129,"time":1784525387360,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" displays"}}} -{"type":"assistant/chunk","seq":130,"time":1784525387389,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" \\\""}}} -{"type":"assistant/chunk","seq":131,"time":1784525387389,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"hel"}}} -{"type":"assistant/chunk","seq":132,"time":1784525387389,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"o"}}} -{"type":"assistant/chunk","seq":133,"time":1784525387389,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" wr"}}} -{"type":"assistant/chunk","seq":134,"time":1784525387389,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"ld"}}} -{"type":"assistant/chunk","seq":135,"time":1784525387417,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\\\""}}} -{"type":"assistant/chunk","seq":136,"time":1784525387417,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" instead"}}} -{"type":"assistant/chunk","seq":137,"time":1784525387418,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" of"}}} -{"type":"assistant/chunk","seq":138,"time":1784525387418,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":139,"time":1784525387446,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" correct"}}} -{"type":"assistant/chunk","seq":140,"time":1784525387447,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" \\\""}}} -{"type":"assistant/chunk","seq":141,"time":1784525387447,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"Hello"}}} -{"type":"assistant/chunk","seq":142,"time":1784525387447,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" World"}}} -{"type":"assistant/chunk","seq":143,"time":1784525387476,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\\\".\\n\\n"}}} -{"type":"assistant/chunk","seq":144,"time":1784525387476,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"**"}}} -{"type":"assistant/chunk","seq":145,"time":1784525387476,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"Plan"}}} -{"type":"assistant/chunk","seq":146,"time":1784525387503,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":":**\\n\\n"}}} -{"type":"assistant/chunk","seq":147,"time":1784525387504,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"1"}}} -{"type":"assistant/chunk","seq":148,"time":1784525387504,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"."}}} -{"type":"assistant/chunk","seq":149,"time":1784525387504,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" **"}}} -{"type":"assistant/chunk","seq":150,"time":1784525387504,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"Find"}}} -{"type":"assistant/chunk","seq":151,"time":1784525387533,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":152,"time":1784525387534,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" source"}}} -{"type":"assistant/chunk","seq":153,"time":1784525387561,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" file"}}} -{"type":"assistant/chunk","seq":154,"time":1784525387562,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"**"}}} -{"type":"assistant/chunk","seq":155,"time":1784525387589,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" —"}}} -{"type":"assistant/chunk","seq":156,"time":1784525387590,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" Loc"}}} -{"type":"assistant/chunk","seq":157,"time":1784525387619,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"ate"}}} -{"type":"assistant/chunk","seq":158,"time":1784525387619,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":159,"time":1784525387647,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" file"}}} -{"type":"assistant/chunk","seq":160,"time":1784525387647,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" that"}}} -{"type":"assistant/chunk","seq":161,"time":1784525387675,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" contains"}}} -{"type":"assistant/chunk","seq":162,"time":1784525387676,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":163,"time":1784525387676,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" greeting"}}} -{"type":"assistant/chunk","seq":164,"time":1784525387706,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" string"}}} -{"type":"assistant/chunk","seq":165,"time":1784525387707,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" \\\""}}} -{"type":"assistant/chunk","seq":166,"time":1784525387736,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"hel"}}} -{"type":"assistant/chunk","seq":167,"time":1784525387737,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"o"}}} -{"type":"assistant/chunk","seq":168,"time":1784525387737,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" wr"}}} -{"type":"assistant/chunk","seq":169,"time":1784525387737,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"ld"}}} -{"type":"assistant/chunk","seq":170,"time":1784525387737,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\\\".\\n"}}} -{"type":"assistant/chunk","seq":171,"time":1784525387764,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"2"}}} -{"type":"assistant/chunk","seq":172,"time":1784525387764,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"."}}} -{"type":"assistant/chunk","seq":173,"time":1784525387764,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" **"}}} -{"type":"assistant/chunk","seq":174,"time":1784525387765,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"Fix"}}} -{"type":"assistant/chunk","seq":175,"time":1784525387796,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":176,"time":1784525387796,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" typ"}}} -{"type":"assistant/chunk","seq":177,"time":1784525387796,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"o"}}} -{"type":"assistant/chunk","seq":178,"time":1784525387796,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"**"}}} -{"type":"assistant/chunk","seq":179,"time":1784525387796,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" —"}}} -{"type":"assistant/chunk","seq":180,"time":1784525387825,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" Replace"}}} -{"type":"assistant/chunk","seq":181,"time":1784525387826,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" \\\""}}} -{"type":"assistant/chunk","seq":182,"time":1784525387826,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"hel"}}} -{"type":"assistant/chunk","seq":183,"time":1784525387854,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"o"}}} -{"type":"assistant/chunk","seq":184,"time":1784525387854,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" wr"}}} -{"type":"assistant/chunk","seq":185,"time":1784525387854,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"ld"}}} -{"type":"assistant/chunk","seq":186,"time":1784525387855,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\\\""}}} -{"type":"assistant/chunk","seq":187,"time":1784525387855,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" with"}}} -{"type":"assistant/chunk","seq":188,"time":1784525387855,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" \\\""}}} -{"type":"assistant/chunk","seq":189,"time":1784525387884,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"Hello"}}} -{"type":"assistant/chunk","seq":190,"time":1784525387884,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" World"}}} -{"type":"assistant/chunk","seq":191,"time":1784525387884,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\\\""}}} -{"type":"assistant/chunk","seq":192,"time":1784525387884,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" in"}}} -{"type":"assistant/chunk","seq":193,"time":1784525387884,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" that"}}} -{"type":"assistant/chunk","seq":194,"time":1784525387911,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" source"}}} -{"type":"assistant/chunk","seq":195,"time":1784525387940,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" file"}}} -{"type":"assistant/chunk","seq":196,"time":1784525387940,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":".\\n"}}} -{"type":"assistant/chunk","seq":197,"time":1784525387940,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"3"}}} -{"type":"assistant/chunk","seq":198,"time":1784525387940,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"."}}} -{"type":"assistant/chunk","seq":199,"time":1784525387940,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" **"}}} -{"type":"assistant/chunk","seq":200,"time":1784525387940,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"Verify"}}} -{"type":"assistant/chunk","seq":201,"time":1784525387968,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"**"}}} -{"type":"assistant/chunk","seq":202,"time":1784525387968,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" —"}}} -{"type":"assistant/chunk","seq":203,"time":1784525387969,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" Confirm"}}} -{"type":"assistant/chunk","seq":204,"time":1784525388000,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":205,"time":1784525388000,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" fix"}}} -{"type":"assistant/chunk","seq":206,"time":1784525388028,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" is"}}} -{"type":"assistant/chunk","seq":207,"time":1784525388029,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" correct"}}} -{"type":"assistant/chunk","seq":208,"time":1784525388057,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" by"}}} -{"type":"assistant/chunk","seq":209,"time":1784525388058,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" reading"}}} -{"type":"assistant/chunk","seq":210,"time":1784525388105,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":211,"time":1784525388105,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" changed"}}} -{"type":"assistant/chunk","seq":212,"time":1784525388117,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":" file"}}} -{"type":"assistant/chunk","seq":213,"time":1784525388117,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"."}}} -{"type":"assistant/chunk","seq":214,"time":1784525388117,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":215,"time":1784525388146,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":216,"time":1784525388177,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The file contains a single note: \"the greeting message still says 'helo wrld'\". The user wants a plan titled \"# Fix the greeting typo\". Let me present a simple plan to fix this typo."}}}} -{"type":"assistant/chunk","seq":217,"time":1784525388177,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","arguments":"{\"plan\": \"# Fix the greeting typo\\n\\n**Issue:** The greeting message currently displays \\\"helo wrld\\\" instead of the correct \\\"Hello World\\\".\\n\\n**Plan:**\\n\\n1. **Find the source file** — Locate the file that contains the greeting string \\\"helo wrld\\\".\\n2. **Fix the typo** — Replace \\\"helo wrld\\\" with \\\"Hello World\\\" in that source file.\\n3. **Verify** — Confirm the fix is correct by reading the changed file.\"}"}}}} -{"type":"assistant/chunk","seq":218,"time":1784525388178,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":274,"outputTokens":187,"cacheReadTokens":3072,"reasoningTokens":44}}}} -{"type":"assistant/chunk","seq":219,"time":1784525388178,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":220,"time":1784525388178,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The file contains a single note: \"the greeting message still says 'helo wrld'\". The user wants a plan titled \"# Fix the greeting typo\". Let me present a simple plan to fix this typo."},{"type":"tool-call","id":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","arguments":"{\"plan\": \"# Fix the greeting typo\\n\\n**Issue:** The greeting message currently displays \\\"helo wrld\\\" instead of the correct \\\"Hello World\\\".\\n\\n**Plan:**\\n\\n1. **Find the source file** — Locate the file that contains the greeting string \\\"helo wrld\\\".\\n2. **Fix the typo** — Replace \\\"helo wrld\\\" with \\\"Hello World\\\" in that source file.\\n3. **Verify** — Confirm the fix is correct by reading the changed file.\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":274,"outputTokens":187,"cacheReadTokens":3072,"reasoningTokens":44}},"sourceEventSeqs":[62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219],"surfaceOp":"append"} -{"type":"tool/call","seq":221,"time":1784525388178,"data":{"turn":1,"step":2,"callId":"call_00_ucsiIH3qJOCb1B6d3dmm4387","name":"exit_plan_mode","arguments":"{\"plan\": \"# Fix the greeting typo\\n\\n**Issue:** The greeting message currently displays \\\"helo wrld\\\" instead of the correct \\\"Hello World\\\".\\n\\n**Plan:**\\n\\n1. **Find the source file** — Locate the file that contains the greeting string \\\"helo wrld\\\".\\n2. **Fix the typo** — Replace \\\"helo wrld\\\" with \\\"Hello World\\\" in that source file.\\n3. **Verify** — Confirm the fix is correct by reading the changed file.\"}"}} -{"type":"tool/result","seq":222,"time":1784525388182,"data":{"turn":1,"step":2,"callId":"call_00_ucsiIH3qJOCb1B6d3dmm4387","content":[{"type":"text","text":"Error: The user chose to keep planning; their feedback: Also add a verification step that re-reads the file after the fix."}],"isError":true},"sourceEventSeqs":[221],"surfaceOp":"append"} -{"type":"step/end","seq":223,"time":1784525388182,"data":{"turn":1,"step":2}} -{"type":"step/start","seq":224,"time":1784525388183,"data":{"turn":1,"step":3}} -{"type":"assistant/chunk","seq":225,"time":1784525388812,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":226,"time":1784525388812,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":227,"time":1784525388919,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":228,"time":1784525388951,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":229,"time":1784525388951,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":230,"time":1784525388951,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":231,"time":1784525388978,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" add"}}} -{"type":"assistant/chunk","seq":232,"time":1784525389007,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":233,"time":1784525389007,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" verification"}}} -{"type":"assistant/chunk","seq":234,"time":1784525389008,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" step"}}} -{"type":"assistant/chunk","seq":235,"time":1784525389008,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" that"}}} -{"type":"assistant/chunk","seq":236,"time":1784525389038,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" re"}}} -{"type":"assistant/chunk","seq":237,"time":1784525389038,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"-read"}}} -{"type":"assistant/chunk","seq":238,"time":1784525389038,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"s"}}} -{"type":"assistant/chunk","seq":239,"time":1784525389038,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":240,"time":1784525389038,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":241,"time":1784525389038,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" after"}}} -{"type":"assistant/chunk","seq":242,"time":1784525389069,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":243,"time":1784525389070,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" fix"}}} -{"type":"assistant/chunk","seq":244,"time":1784525389070,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":245,"time":1784525389070,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" But"}}} -{"type":"assistant/chunk","seq":246,"time":1784525389101,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" they"}}} -{"type":"assistant/chunk","seq":247,"time":1784525389101,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" said"}}} -{"type":"assistant/chunk","seq":248,"time":1784525389133,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":249,"time":1784525389133,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" keep"}}} -{"type":"assistant/chunk","seq":250,"time":1784525389168,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" planning"}}} -{"type":"assistant/chunk","seq":251,"time":1784525389169,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" —"}}} -{"type":"assistant/chunk","seq":252,"time":1784525389193,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" they"}}} -{"type":"assistant/chunk","seq":253,"time":1784525389193,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" didn"}}} -{"type":"assistant/chunk","seq":254,"time":1784525389221,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"'t"}}} -{"type":"assistant/chunk","seq":255,"time":1784525389221,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" approve"}}} -{"type":"assistant/chunk","seq":256,"time":1784525389250,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":257,"time":1784525389278,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" They"}}} -{"type":"assistant/chunk","seq":258,"time":1784525389278,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" also"}}} -{"type":"assistant/chunk","seq":259,"time":1784525389309,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" said"}}} -{"type":"assistant/chunk","seq":260,"time":1784525389310,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":261,"time":1784525389310,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"do"}}} -{"type":"assistant/chunk","seq":262,"time":1784525389339,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" not"}}} -{"type":"assistant/chunk","seq":263,"time":1784525389339,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" present"}}} -{"type":"assistant/chunk","seq":264,"time":1784525389339,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":265,"time":1784525389339,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" plan"}}} -{"type":"assistant/chunk","seq":266,"time":1784525389367,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" again"}}} -{"type":"assistant/chunk","seq":267,"time":1784525389367,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"\""}}} -{"type":"assistant/chunk","seq":268,"time":1784525389398,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" if"}}} -{"type":"assistant/chunk","seq":269,"time":1784525389431,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" not"}}} -{"type":"assistant/chunk","seq":270,"time":1784525389462,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" approved"}}} -{"type":"assistant/chunk","seq":271,"time":1784525389463,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":272,"time":1784525389463,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} -{"type":"assistant/chunk","seq":273,"time":1784525389494,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":274,"time":1784525389495,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" re"}}} -{"type":"assistant/chunk","seq":275,"time":1784525389495,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"-read"}}} -{"type":"assistant/chunk","seq":276,"time":1784525389495,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":277,"time":1784525389495,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" instructions"}}} -{"type":"assistant/chunk","seq":278,"time":1784525389525,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":":\n\n"}}} -{"type":"assistant/chunk","seq":279,"time":1784525389525,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"\"If"}}} -{"type":"assistant/chunk","seq":280,"time":1784525389557,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":281,"time":1784525389558,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" review"}}} -{"type":"assistant/chunk","seq":282,"time":1784525389558,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" does"}}} -{"type":"assistant/chunk","seq":283,"time":1784525389558,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" not"}}} -{"type":"assistant/chunk","seq":284,"time":1784525389558,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" approve"}}} -{"type":"assistant/chunk","seq":285,"time":1784525389558,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":286,"time":1784525389590,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" summarize"}}} -{"type":"assistant/chunk","seq":287,"time":1784525389590,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":288,"time":1784525389590,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" reviewer"}}} -{"type":"assistant/chunk","seq":289,"time":1784525389623,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"'s"}}} -{"type":"assistant/chunk","seq":290,"time":1784525389623,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" feedback"}}} -{"type":"assistant/chunk","seq":291,"time":1784525389624,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" in"}}} -{"type":"assistant/chunk","seq":292,"time":1784525389624,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" plain"}}} -{"type":"assistant/chunk","seq":293,"time":1784525389624,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" text"}}} -{"type":"assistant/chunk","seq":294,"time":1784525389654,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":295,"time":1784525389654,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" end"}}} -{"type":"assistant/chunk","seq":296,"time":1784525389655,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" your"}}} -{"type":"assistant/chunk","seq":297,"time":1784525389655,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":298,"time":1784525389655,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" -"}}} -{"type":"assistant/chunk","seq":299,"time":1784525389686,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" do"}}} -{"type":"assistant/chunk","seq":300,"time":1784525389686,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" not"}}} -{"type":"assistant/chunk","seq":301,"time":1784525389686,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" present"}}} -{"type":"assistant/chunk","seq":302,"time":1784525389687,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":303,"time":1784525389687,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" plan"}}} -{"type":"assistant/chunk","seq":304,"time":1784525389687,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" again"}}} -{"type":"assistant/chunk","seq":305,"time":1784525389718,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":".\"\n\n"}}} -{"type":"assistant/chunk","seq":306,"time":1784525389718,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"So"}}} -{"type":"assistant/chunk","seq":307,"time":1784525389719,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":308,"time":1784525389719,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" should"}}} -{"type":"assistant/chunk","seq":309,"time":1784525389719,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" summarize"}}} -{"type":"assistant/chunk","seq":310,"time":1784525389765,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":311,"time":1784525389782,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" feedback"}}} -{"type":"assistant/chunk","seq":312,"time":1784525389783,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":313,"time":1784525389783,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" end"}}} -{"type":"assistant/chunk","seq":314,"time":1784525389783,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" my"}}} -{"type":"assistant/chunk","seq":315,"time":1784525389811,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":316,"time":1784525389811,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" without"}}} -{"type":"assistant/chunk","seq":317,"time":1784525389843,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" presenting"}}} -{"type":"assistant/chunk","seq":318,"time":1784525389844,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":319,"time":1784525389844,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" plan"}}} -{"type":"assistant/chunk","seq":320,"time":1784525389844,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" again"}}} -{"type":"assistant/chunk","seq":321,"time":1784525389844,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":322,"time":1784525389875,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":323,"time":1784525389875,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"The"}}} -{"type":"assistant/chunk","seq":324,"time":1784525389875,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" reviewer"}}} -{"type":"assistant/chunk","seq":325,"time":1784525389906,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"'s"}}} -{"type":"assistant/chunk","seq":326,"time":1784525389934,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" feedback"}}} -{"type":"assistant/chunk","seq":327,"time":1784525389934,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":":"}}} -{"type":"assistant/chunk","seq":328,"time":1784525389965,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":329,"time":1784525389994,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" plan"}}} -{"type":"assistant/chunk","seq":330,"time":1784525390022,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" already"}}} -{"type":"assistant/chunk","seq":331,"time":1784525390023,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" includes"}}} -{"type":"assistant/chunk","seq":332,"time":1784525390053,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" a"}}} -{"type":"assistant/chunk","seq":333,"time":1784525390055,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" \""}}} -{"type":"assistant/chunk","seq":334,"time":1784525390083,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"Verify"}}} -{"type":"assistant/chunk","seq":335,"time":1784525390084,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"\""}}} -{"type":"assistant/chunk","seq":336,"time":1784525390084,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" step"}}} -{"type":"assistant/chunk","seq":337,"time":1784525390084,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" ("}}} -{"type":"assistant/chunk","seq":338,"time":1784525390114,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"step"}}} -{"type":"assistant/chunk","seq":339,"time":1784525390115,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":340,"time":1784525390145,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"3"}}} -{"type":"assistant/chunk","seq":341,"time":1784525390146,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"),"}}} -{"type":"assistant/chunk","seq":342,"time":1784525390146,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" but"}}} -{"type":"assistant/chunk","seq":343,"time":1784525390146,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" they"}}} -{"type":"assistant/chunk","seq":344,"time":1784525390173,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" want"}}} -{"type":"assistant/chunk","seq":345,"time":1784525390173,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" it"}}} -{"type":"assistant/chunk","seq":346,"time":1784525390205,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" to"}}} -{"type":"assistant/chunk","seq":347,"time":1784525390205,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" be"}}} -{"type":"assistant/chunk","seq":348,"time":1784525390206,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" more"}}} -{"type":"assistant/chunk","seq":349,"time":1784525390234,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" explicit"}}} -{"type":"assistant/chunk","seq":350,"time":1784525390234,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" —"}}} -{"type":"assistant/chunk","seq":351,"time":1784525390235,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" specifically"}}} -{"type":"assistant/chunk","seq":352,"time":1784525390264,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" re"}}} -{"type":"assistant/chunk","seq":353,"time":1784525390296,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"-reading"}}} -{"type":"assistant/chunk","seq":354,"time":1784525390296,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":355,"time":1784525390297,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" file"}}} -{"type":"assistant/chunk","seq":356,"time":1784525390329,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" after"}}} -{"type":"assistant/chunk","seq":357,"time":1784525390329,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":358,"time":1784525390329,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" fix"}}} -{"type":"assistant/chunk","seq":359,"time":1784525390329,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" to"}}} -{"type":"assistant/chunk","seq":360,"time":1784525390367,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" confirm"}}} -{"type":"assistant/chunk","seq":361,"time":1784525390367,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":362,"time":1784525390367,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" change"}}} -{"type":"assistant/chunk","seq":363,"time":1784525390392,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"."}}} -{"type":"assistant/chunk","seq":364,"time":1784525390392,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" Since"}}} -{"type":"assistant/chunk","seq":365,"time":1784525390423,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":366,"time":1784525390454,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" plan"}}} -{"type":"assistant/chunk","seq":367,"time":1784525390454,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" was"}}} -{"type":"assistant/chunk","seq":368,"time":1784525390485,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" not"}}} -{"type":"assistant/chunk","seq":369,"time":1784525390485,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" approved"}}} -{"type":"assistant/chunk","seq":370,"time":1784525390513,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" and"}}} -{"type":"assistant/chunk","seq":371,"time":1784525390544,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" I"}}} -{"type":"assistant/chunk","seq":372,"time":1784525390572,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"'m"}}} -{"type":"assistant/chunk","seq":373,"time":1784525390602,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" instructed"}}} -{"type":"assistant/chunk","seq":374,"time":1784525390603,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" not"}}} -{"type":"assistant/chunk","seq":375,"time":1784525390603,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" to"}}} -{"type":"assistant/chunk","seq":376,"time":1784525390603,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" present"}}} -{"type":"assistant/chunk","seq":377,"time":1784525390629,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" it"}}} -{"type":"assistant/chunk","seq":378,"time":1784525390629,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" again"}}} -{"type":"assistant/chunk","seq":379,"time":1784525390629,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":","}}} -{"type":"assistant/chunk","seq":380,"time":1784525390629,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" I"}}} -{"type":"assistant/chunk","seq":381,"time":1784525390629,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"'ll"}}} -{"type":"assistant/chunk","seq":382,"time":1784525390657,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" incorporate"}}} -{"type":"assistant/chunk","seq":383,"time":1784525390689,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" that"}}} -{"type":"assistant/chunk","seq":384,"time":1784525390725,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" feedback"}}} -{"type":"assistant/chunk","seq":385,"time":1784525390751,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":":"}}} -{"type":"assistant/chunk","seq":386,"time":1784525390751,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":387,"time":1784525390779,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" verification"}}} -{"type":"assistant/chunk","seq":388,"time":1784525390811,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" step"}}} -{"type":"assistant/chunk","seq":389,"time":1784525390811,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" should"}}} -{"type":"assistant/chunk","seq":390,"time":1784525390812,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" say"}}} -{"type":"assistant/chunk","seq":391,"time":1784525390838,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" **"}}} -{"type":"assistant/chunk","seq":392,"time":1784525390839,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"\""}}} -{"type":"assistant/chunk","seq":393,"time":1784525390870,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"Re"}}} -{"type":"assistant/chunk","seq":394,"time":1784525390901,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"-read"}}} -{"type":"assistant/chunk","seq":395,"time":1784525390901,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":396,"time":1784525390901,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" file"}}} -{"type":"assistant/chunk","seq":397,"time":1784525390902,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" to"}}} -{"type":"assistant/chunk","seq":398,"time":1784525390933,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" confirm"}}} -{"type":"assistant/chunk","seq":399,"time":1784525390933,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":400,"time":1784525390934,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" change"}}} -{"type":"assistant/chunk","seq":401,"time":1784525390965,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" took"}}} -{"type":"assistant/chunk","seq":402,"time":1784525390996,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" effect"}}} -{"type":"assistant/chunk","seq":403,"time":1784525390996,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"\""}}} -{"type":"assistant/chunk","seq":404,"time":1784525390996,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"**"}}} -{"type":"assistant/chunk","seq":405,"time":1784525391024,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" rather"}}} -{"type":"assistant/chunk","seq":406,"time":1784525391024,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" than"}}} -{"type":"assistant/chunk","seq":407,"time":1784525391024,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" just"}}} -{"type":"assistant/chunk","seq":408,"time":1784525391052,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":409,"time":1784525391053,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" generic"}}} -{"type":"assistant/chunk","seq":410,"time":1784525391081,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" \""}}} -{"type":"assistant/chunk","seq":411,"time":1784525391081,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":"Confirm"}}} -{"type":"assistant/chunk","seq":412,"time":1784525391081,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" the"}}} -{"type":"assistant/chunk","seq":413,"time":1784525391109,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" fix"}}} -{"type":"assistant/chunk","seq":414,"time":1784525391109,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" is"}}} -{"type":"assistant/chunk","seq":415,"time":1784525391111,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":" correct"}}} -{"type":"assistant/chunk","seq":416,"time":1784525391111,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":1,"text":".\""}}} -{"type":"assistant/chunk","seq":417,"time":1784525391112,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to add a verification step that re-reads the file after the fix. But they said to keep planning — they didn't approve. They also said \"do not present the plan again\" if not approved. Let me re-read the instructions:\n\n\"If the review does not approve, summarize the reviewer's feedback in plain text and end your reply - do not present the plan again.\"\n\nSo I should summarize the feedback and end my reply without presenting the plan again."}}}} -{"type":"assistant/chunk","seq":418,"time":1784525391112,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The reviewer's feedback: the plan already includes a \"Verify\" step (step 3), but they want it to be more explicit — specifically re-reading the file after the fix to confirm the change. Since the plan was not approved and I'm instructed not to present it again, I'll incorporate that feedback: the verification step should say **\"Re-read the file to confirm the change took effect\"** rather than just the generic \"Confirm the fix is correct.\""}}}} -{"type":"assistant/chunk","seq":419,"time":1784525391112,"data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":243,"outputTokens":191,"cacheReadTokens":3328,"reasoningTokens":96}}}} -{"type":"assistant/chunk","seq":420,"time":1784525391112,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":421,"time":1784525391113,"data":{"turn":1,"step":3,"content":[{"type":"reasoning","text":"The user wants me to add a verification step that re-reads the file after the fix. But they said to keep planning — they didn't approve. They also said \"do not present the plan again\" if not approved. Let me re-read the instructions:\n\n\"If the review does not approve, summarize the reviewer's feedback in plain text and end your reply - do not present the plan again.\"\n\nSo I should summarize the feedback and end my reply without presenting the plan again."},{"type":"text","text":"The reviewer's feedback: the plan already includes a \"Verify\" step (step 3), but they want it to be more explicit — specifically re-reading the file after the fix to confirm the change. Since the plan was not approved and I'm instructed not to present it again, I'll incorporate that feedback: the verification step should say **\"Re-read the file to confirm the change took effect\"** rather than just the generic \"Confirm the fix is correct.\""}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":243,"outputTokens":191,"cacheReadTokens":3328,"reasoningTokens":96}},"sourceEventSeqs":[225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420],"surfaceOp":"append"} -{"type":"step/end","seq":422,"time":1784525391113,"data":{"turn":1,"step":3}} -{"type":"turn/end","seq":423,"time":1784525391113,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/plan-mode-reject/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/plan-mode-reject/stdout.expected.jsonl deleted file mode 100644 index 976bfd36e5..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode-reject/stdout.expected.jsonl +++ /dev/null @@ -1,279 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"current_mode_update","currentModeId":"plan"}}} -{"jsonrpc":"2.0","id":3,"result":{}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Read the file notes.txt (use","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" notes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" using"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" relative"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" path"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" present"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" via"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_mode"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" start"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_Tez1Df1H9v8RqxqYIs5o6697","title":"Read notes.txt","kind":"read","status":"in_progress","locations":[{"path":"notes.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_Tez1Df1H9v8RqxqYIs5o6697","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/notes.txt</path>\n<type>file</type>\n<content>\n1: project notes\n2: - the greeting message still says \"helo wrld\"\n\n(End of file - total 2 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" contains"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" note"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" greeting"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" message"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" still"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" says"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" '"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hel"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"o"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wr"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ld"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" titled"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \"#"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Fix"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" greeting"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" typ"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"o"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" present"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" simple"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" fix"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" typ"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"o"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_ucsiIH3qJOCb1B6d3dmm4387","title":"Fix the greeting typo","kind":"other","status":"in_progress","content":[{"type":"content","content":{"type":"text","text":"# Fix the greeting typo\n\n**Issue:** The greeting message currently displays \"helo wrld\" instead of the correct \"Hello World\".\n\n**Plan:**\n\n1. **Find the source file** — Locate the file that contains the greeting string \"helo wrld\".\n2. **Fix the typo** — Replace \"helo wrld\" with \"Hello World\" in that source file.\n3. **Verify** — Confirm the fix is correct by reading the changed file."}}]}}} -{"jsonrpc":"2.0","id":1,"method":"elicitation/create","params":{"sessionId":"{{sessionId}}","mode":"form","message":"Approve this plan and leave plan mode?\n\n# Fix the greeting typo\n\n**Issue:** The greeting message currently displays \"helo wrld\" instead of the correct \"Hello World\".\n\n**Plan:**\n\n1. **Find the source file** — Locate the file that contains the greeting string \"helo wrld\".\n2. **Fix the typo** — Replace \"helo wrld\" with \"Hello World\" in that source file.\n3. **Verify** — Confirm the fix is correct by reading the changed file.","requestedSchema":{"type":"object","title":"Plan review","properties":{"choice":{"type":"string","title":"Approve this plan and leave plan mode?","description":"Choose one option, or fill a custom answer below.","oneOf":[{"const":"Approve","title":"Approve: Leave plan mode; the plan is carried out from the next step."},{"const":"Keep planning","title":"Keep planning: Stay in plan mode; feedback goes back to the model."}]},"custom":{"type":"string","title":"Custom answer","description":"Optional free-form answer. Leave empty to use the selected option."}},"required":[]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_ucsiIH3qJOCb1B6d3dmm4387","status":"failed","content":[{"type":"content","content":{"type":"text","text":"Error: The user chose to keep planning; their feedback: Also add a verification step that re-reads the file after the fix."}}],"title":"Plan review"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" add"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verification"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" step"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" re"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" after"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" fix"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" But"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" they"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" said"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" keep"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" planning"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" —"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" they"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" didn"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'t"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" approve"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" They"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" also"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" said"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"do"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" present"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" again"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" if"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" approved"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" re"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instructions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"If"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" review"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" does"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" approve"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" summarize"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reviewer"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" feedback"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plain"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" text"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" end"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" your"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" -"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" do"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" present"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" again"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"So"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" summarize"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" feedback"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" end"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" my"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" without"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" presenting"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" again"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" reviewer"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"'s"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" feedback"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" already"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" includes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Verify"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" step"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"step"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"3"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"),"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" but"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" they"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" want"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" be"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" more"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" explicit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" —"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" specifically"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" re"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"-reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" after"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" fix"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" confirm"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" change"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" Since"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" was"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" approved"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"'m"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" instructed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" present"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" again"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"'ll"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" incorporate"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" feedback"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" verification"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" step"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" say"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" **"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Re"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"-read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" confirm"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" change"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" took"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" effect"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"**"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" rather"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" than"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" generic"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Confirm"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" fix"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" correct"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":".\""}}}} -{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/plan-mode-reject/workspace/notes.txt b/examples/acp-agent/tests/snapshots/plan-mode-reject/workspace/notes.txt deleted file mode 100644 index 0230df4b3b..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode-reject/workspace/notes.txt +++ /dev/null @@ -1,2 +0,0 @@ -project notes -- the greeting message still says "helo wrld" diff --git a/examples/acp-agent/tests/snapshots/plan-mode/input.json b/examples/acp-agent/tests/snapshots/plan-mode/input.json deleted file mode 100644 index afc80dc900..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode/input.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "steps": [ - { - "op": "initialize" - }, - { - "op": "newSession" - }, - { - "op": "setMode", - "modeId": "plan" - }, - { - "op": "prompt", - "text": "The typo is on line 2 of notes.txt itself; the workspace contains no other file. Inspect it with the bash tool: run exactly `cat notes.txt` (relative path, no other command). Then present a one-step plan titled '# Fix the greeting typo' via exit_plan_mode: the single step is editing line 2 of notes.txt to say hello world. Do not edit anything before the review approves. After it approves, apply exactly that one edit to notes.txt with the edit tool and stop — no other commands, do not look for any other file." - }, - { - "op": "prompt", - "text": "Read notes.txt (relative path notes.txt) and reply with the single word DONE if line 2 now says hello world." - } - ], - "elicitationAnswers": [ - { - "action": "accept", - "choice": "Approve" - } - ] -} diff --git a/examples/acp-agent/tests/snapshots/plan-mode/session.jsonl b/examples/acp-agent/tests/snapshots/plan-mode/session.jsonl deleted file mode 100644 index 71a1189702..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode/session.jsonl +++ /dev/null @@ -1,532 +0,0 @@ -{"type":"session","version":0,"id":"5fa52100-2da3-4be1-ac1d-6c2e1fba01c6","createdAt":1784525374896,"cwd":"/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-tia05W","delegationDepth":0} -{"type":"turn/start","seq":0,"time":1784525374902,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"plan/mode","seq":1,"time":1784525374902,"data":{"active":true}} -{"type":"user/message","seq":2,"time":1784525374902,"data":{"content":[{"type":"text","text":"The typo is on line 2 of notes.txt itself; the workspace contains no other file. Inspect it with the bash tool: run exactly `cat notes.txt` (relative path, no other command). Then present a one-step plan titled '# Fix the greeting typo' via exit_plan_mode: the single step is editing line 2 of notes.txt to say hello world. Do not edit anything before the review approves. After it approves, apply exactly that one edit to notes.txt with the edit tool and stop — no other commands, do not look for any other file."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"session/title","seq":3,"time":1784525374902,"data":{"title":"The typo is on line","messageSeqs":[2],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":4,"time":1784525374904,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":5,"time":1784525374905,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"assistant/chunk","seq":6,"time":1784525375472,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":7,"time":1784525375473,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":8,"time":1784525375620,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":9,"time":1784525375643,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":10,"time":1784525375644,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":11,"time":1784525375644,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":12,"time":1784525375644,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":":\n"}}} -{"type":"assistant/chunk","seq":13,"time":1784525375644,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"1"}}} -{"type":"assistant/chunk","seq":14,"time":1784525375644,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":15,"time":1784525375670,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Run"}}} -{"type":"assistant/chunk","seq":16,"time":1784525375670,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":17,"time":1784525375671,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"cat"}}} -{"type":"assistant/chunk","seq":18,"time":1784525375671,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" notes"}}} -{"type":"assistant/chunk","seq":19,"time":1784525375698,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".txt"}}} -{"type":"assistant/chunk","seq":20,"time":1784525375699,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"`"}}} -{"type":"assistant/chunk","seq":21,"time":1784525375699,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":22,"time":1784525375699,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" inspect"}}} -{"type":"assistant/chunk","seq":23,"time":1784525375727,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":24,"time":1784525375727,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":25,"time":1784525375755,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\n"}}} -{"type":"assistant/chunk","seq":26,"time":1784525375756,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"2"}}} -{"type":"assistant/chunk","seq":27,"time":1784525375756,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":28,"time":1784525375756,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Present"}}} -{"type":"assistant/chunk","seq":29,"time":1784525375784,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":30,"time":1784525375784,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" plan"}}} -{"type":"assistant/chunk","seq":31,"time":1784525375785,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" via"}}} -{"type":"assistant/chunk","seq":32,"time":1784525375813,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" exit"}}} -{"type":"assistant/chunk","seq":33,"time":1784525375814,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_"}}} -{"type":"assistant/chunk","seq":34,"time":1784525375814,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"plan"}}} -{"type":"assistant/chunk","seq":35,"time":1784525375814,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_mode"}}} -{"type":"assistant/chunk","seq":36,"time":1784525375841,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\n"}}} -{"type":"assistant/chunk","seq":37,"time":1784525375841,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"3"}}} -{"type":"assistant/chunk","seq":38,"time":1784525375842,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":39,"time":1784525375842,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" After"}}} -{"type":"assistant/chunk","seq":40,"time":1784525375870,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" approval"}}} -{"type":"assistant/chunk","seq":41,"time":1784525375870,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} -{"type":"assistant/chunk","seq":42,"time":1784525375870,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" make"}}} -{"type":"assistant/chunk","seq":43,"time":1784525375898,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":44,"time":1784525375926,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" edit"}}} -{"type":"assistant/chunk","seq":45,"time":1784525375927,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\n\n"}}} -{"type":"assistant/chunk","seq":46,"time":1784525375927,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"Let"}}} -{"type":"assistant/chunk","seq":47,"time":1784525375927,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":48,"time":1784525375927,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" start"}}} -{"type":"assistant/chunk","seq":49,"time":1784525375954,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":50,"time":1784525375955,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" step"}}} -{"type":"assistant/chunk","seq":51,"time":1784525375983,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":52,"time":1784525375983,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"1"}}} -{"type":"assistant/chunk","seq":53,"time":1784525375983,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":54,"time":1784525376068,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":55,"time":1784525376068,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":56,"time":1784525376097,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":57,"time":1784525376097,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":58,"time":1784525376097,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"command"}}} -{"type":"assistant/chunk","seq":59,"time":1784525376098,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":60,"time":1784525376098,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":61,"time":1784525376125,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":62,"time":1784525376125,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"cat"}}} -{"type":"assistant/chunk","seq":63,"time":1784525376126,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":" notes"}}} -{"type":"assistant/chunk","seq":64,"time":1784525376126,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":65,"time":1784525376154,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":66,"time":1784525376182,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":67,"time":1784525376183,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":68,"time":1784525376183,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"description"}}} -{"type":"assistant/chunk","seq":69,"time":1784525376183,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":70,"time":1784525376183,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":71,"time":1784525376211,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":72,"time":1784525376211,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"In"}}} -{"type":"assistant/chunk","seq":73,"time":1784525376240,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"spect"}}} -{"type":"assistant/chunk","seq":74,"time":1784525376240,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":" notes"}}} -{"type":"assistant/chunk","seq":75,"time":1784525376240,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":76,"time":1784525376240,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":" contents"}}} -{"type":"assistant/chunk","seq":77,"time":1784525376268,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":78,"time":1784525376269,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":79,"time":1784525376333,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to:\n1. Run `cat notes.txt` to inspect the file\n2. Present a plan via exit_plan_mode\n3. After approval, make the edit\n\nLet me start with step 1."}}}} -{"type":"assistant/chunk","seq":80,"time":1784525376333,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","arguments":"{\"command\": \"cat notes.txt\", \"description\": \"Inspect notes.txt contents\"}"}}}} -{"type":"assistant/chunk","seq":81,"time":1784525376333,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3222,"outputTokens":112,"cacheReadTokens":0,"reasoningTokens":47}}}} -{"type":"assistant/chunk","seq":82,"time":1784525376333,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":83,"time":1784525376337,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to:\n1. Run `cat notes.txt` to inspect the file\n2. Present a plan via exit_plan_mode\n3. After approval, make the edit\n\nLet me start with step 1."},{"type":"tool-call","id":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","arguments":"{\"command\": \"cat notes.txt\", \"description\": \"Inspect notes.txt contents\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":3222,"outputTokens":112,"cacheReadTokens":0,"reasoningTokens":47}},"sourceEventSeqs":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82],"surfaceOp":"append"} -{"type":"tool/call","seq":84,"time":1784525376338,"data":{"turn":1,"step":1,"callId":"call_00_jRYWnAwUo7zSx2WVsRZ83655","name":"bash","arguments":"{\"command\": \"cat notes.txt\", \"description\": \"Inspect notes.txt contents\"}"}} -{"type":"tool/result","seq":85,"time":1784525376456,"data":{"turn":1,"step":1,"callId":"call_00_jRYWnAwUo7zSx2WVsRZ83655","content":[{"type":"text","text":"project notes\n- the greeting message still says \"helo wrld\"\n"}],"isError":false},"sourceEventSeqs":[84],"surfaceOp":"append"} -{"type":"step/end","seq":86,"time":1784525376457,"data":{"turn":1,"step":1}} -{"type":"step/start","seq":87,"time":1784525376457,"data":{"turn":1,"step":2}} -{"type":"assistant/chunk","seq":88,"time":1784525376956,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":89,"time":1784525376956,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":90,"time":1784525377129,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":91,"time":1784525377150,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" has"}}} -{"type":"assistant/chunk","seq":92,"time":1784525377179,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" two"}}} -{"type":"assistant/chunk","seq":93,"time":1784525377179,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" lines"}}} -{"type":"assistant/chunk","seq":94,"time":1784525377207,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":":\n"}}} -{"type":"assistant/chunk","seq":95,"time":1784525377207,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-"}}} -{"type":"assistant/chunk","seq":96,"time":1784525377207,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" Line"}}} -{"type":"assistant/chunk","seq":97,"time":1784525377207,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":98,"time":1784525377208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"1"}}} -{"type":"assistant/chunk","seq":99,"time":1784525377208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":":"}}} -{"type":"assistant/chunk","seq":100,"time":1784525377208,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":101,"time":1784525377235,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"project"}}} -{"type":"assistant/chunk","seq":102,"time":1784525377235,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" notes"}}} -{"type":"assistant/chunk","seq":103,"time":1784525377235,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"`\n"}}} -{"type":"assistant/chunk","seq":104,"time":1784525377235,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-"}}} -{"type":"assistant/chunk","seq":105,"time":1784525377235,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" Line"}}} -{"type":"assistant/chunk","seq":106,"time":1784525377235,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":107,"time":1784525377264,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"2"}}} -{"type":"assistant/chunk","seq":108,"time":1784525377264,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":":"}}} -{"type":"assistant/chunk","seq":109,"time":1784525377265,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" `"}}} -{"type":"assistant/chunk","seq":110,"time":1784525377265,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-"}}} -{"type":"assistant/chunk","seq":111,"time":1784525377265,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":112,"time":1784525377292,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" greeting"}}} -{"type":"assistant/chunk","seq":113,"time":1784525377292,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" message"}}} -{"type":"assistant/chunk","seq":114,"time":1784525377292,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" still"}}} -{"type":"assistant/chunk","seq":115,"time":1784525377293,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" says"}}} -{"type":"assistant/chunk","seq":116,"time":1784525377293,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":117,"time":1784525377293,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"hel"}}} -{"type":"assistant/chunk","seq":118,"time":1784525377323,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"o"}}} -{"type":"assistant/chunk","seq":119,"time":1784525377323,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" wr"}}} -{"type":"assistant/chunk","seq":120,"time":1784525377323,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ld"}}} -{"type":"assistant/chunk","seq":121,"time":1784525377323,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\""}}} -{"type":"assistant/chunk","seq":122,"time":1784525377323,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"`\n\n"}}} -{"type":"assistant/chunk","seq":123,"time":1784525377324,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":124,"time":1784525377349,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":125,"time":1784525377349,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" says"}}} -{"type":"assistant/chunk","seq":126,"time":1784525377378,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" line"}}} -{"type":"assistant/chunk","seq":127,"time":1784525377379,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":128,"time":1784525377379,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"2"}}} -{"type":"assistant/chunk","seq":129,"time":1784525377405,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" has"}}} -{"type":"assistant/chunk","seq":130,"time":1784525377405,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":131,"time":1784525377434,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" typ"}}} -{"type":"assistant/chunk","seq":132,"time":1784525377435,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"o"}}} -{"type":"assistant/chunk","seq":133,"time":1784525377435,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":134,"time":1784525377435,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" should"}}} -{"type":"assistant/chunk","seq":135,"time":1784525377462,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" say"}}} -{"type":"assistant/chunk","seq":136,"time":1784525377491,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":137,"time":1784525377491,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"hello"}}} -{"type":"assistant/chunk","seq":138,"time":1784525377491,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" world"}}} -{"type":"assistant/chunk","seq":139,"time":1784525377492,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} -{"type":"assistant/chunk","seq":140,"time":1784525377492,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" So"}}} -{"type":"assistant/chunk","seq":141,"time":1784525377520,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":142,"time":1784525377549,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" need"}}} -{"type":"assistant/chunk","seq":143,"time":1784525377549,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":144,"time":1784525377549,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" replace"}}} -{"type":"assistant/chunk","seq":145,"time":1784525377575,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" line"}}} -{"type":"assistant/chunk","seq":146,"time":1784525377576,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":147,"time":1784525377576,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"2"}}} -{"type":"assistant/chunk","seq":148,"time":1784525377576,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":149,"time":1784525377604,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":150,"time":1784525377632,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"hello"}}} -{"type":"assistant/chunk","seq":151,"time":1784525377632,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" world"}}} -{"type":"assistant/chunk","seq":152,"time":1784525377684,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\".\n\n"}}} -{"type":"assistant/chunk","seq":153,"time":1784525377685,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"Let"}}} -{"type":"assistant/chunk","seq":154,"time":1784525377685,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":155,"time":1784525377685,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" present"}}} -{"type":"assistant/chunk","seq":156,"time":1784525377685,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":157,"time":1784525377689,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" plan"}}} -{"type":"assistant/chunk","seq":158,"time":1784525377689,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":159,"time":1784525377774,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":160,"time":1784525377774,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":161,"time":1784525377803,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":162,"time":1784525377803,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":163,"time":1784525377803,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"plan"}}} -{"type":"assistant/chunk","seq":164,"time":1784525377803,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":165,"time":1784525377834,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":166,"time":1784525377834,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":167,"time":1784525377834,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"#"}}} -{"type":"assistant/chunk","seq":168,"time":1784525377834,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" Fix"}}} -{"type":"assistant/chunk","seq":169,"time":1784525377859,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":170,"time":1784525377860,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" greeting"}}} -{"type":"assistant/chunk","seq":171,"time":1784525377860,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" typ"}}} -{"type":"assistant/chunk","seq":172,"time":1784525377860,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"o"}}} -{"type":"assistant/chunk","seq":173,"time":1784525377860,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"\\n\\n"}}} -{"type":"assistant/chunk","seq":174,"time":1784525377860,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"##"}}} -{"type":"assistant/chunk","seq":175,"time":1784525377887,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" Single"}}} -{"type":"assistant/chunk","seq":176,"time":1784525377887,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" step"}}} -{"type":"assistant/chunk","seq":177,"time":1784525377916,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"\\n"}}} -{"type":"assistant/chunk","seq":178,"time":1784525377916,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"1"}}} -{"type":"assistant/chunk","seq":179,"time":1784525377944,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"."}}} -{"type":"assistant/chunk","seq":180,"time":1784525377944,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" **"}}} -{"type":"assistant/chunk","seq":181,"time":1784525377944,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"Edit"}}} -{"type":"assistant/chunk","seq":182,"time":1784525377973,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" line"}}} -{"type":"assistant/chunk","seq":183,"time":1784525378010,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":184,"time":1784525378010,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"2"}}} -{"type":"assistant/chunk","seq":185,"time":1784525378010,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" of"}}} -{"type":"assistant/chunk","seq":186,"time":1784525378010,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" `"}}} -{"type":"assistant/chunk","seq":187,"time":1784525378030,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"notes"}}} -{"type":"assistant/chunk","seq":188,"time":1784525378030,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":189,"time":1784525378030,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"`"}}} -{"type":"assistant/chunk","seq":190,"time":1784525378030,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"**"}}} -{"type":"assistant/chunk","seq":191,"time":1784525378030,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" —"}}} -{"type":"assistant/chunk","seq":192,"time":1784525378030,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" Replace"}}} -{"type":"assistant/chunk","seq":193,"time":1784525378057,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":194,"time":1784525378057,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" content"}}} -{"type":"assistant/chunk","seq":195,"time":1784525378087,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" of"}}} -{"type":"assistant/chunk","seq":196,"time":1784525378087,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" line"}}} -{"type":"assistant/chunk","seq":197,"time":1784525378115,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" "}}} -{"type":"assistant/chunk","seq":198,"time":1784525378115,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"2"}}} -{"type":"assistant/chunk","seq":199,"time":1784525378115,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" (`"}}} -{"type":"assistant/chunk","seq":200,"time":1784525378144,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"-"}}} -{"type":"assistant/chunk","seq":201,"time":1784525378145,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":202,"time":1784525378145,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" greeting"}}} -{"type":"assistant/chunk","seq":203,"time":1784525378145,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" message"}}} -{"type":"assistant/chunk","seq":204,"time":1784525378145,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" still"}}} -{"type":"assistant/chunk","seq":205,"time":1784525378145,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" says"}}} -{"type":"assistant/chunk","seq":206,"time":1784525378200,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" \\\""}}} -{"type":"assistant/chunk","seq":207,"time":1784525378200,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"hel"}}} -{"type":"assistant/chunk","seq":208,"time":1784525378200,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"o"}}} -{"type":"assistant/chunk","seq":209,"time":1784525378201,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" wr"}}} -{"type":"assistant/chunk","seq":210,"time":1784525378201,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"ld"}}} -{"type":"assistant/chunk","seq":211,"time":1784525378201,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"\\\""}}} -{"type":"assistant/chunk","seq":212,"time":1784525378201,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"`)"}}} -{"type":"assistant/chunk","seq":213,"time":1784525378201,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" with"}}} -{"type":"assistant/chunk","seq":214,"time":1784525378201,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" `"}}} -{"type":"assistant/chunk","seq":215,"time":1784525378201,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"hello"}}} -{"type":"assistant/chunk","seq":216,"time":1784525378229,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":" world"}}} -{"type":"assistant/chunk","seq":217,"time":1784525378230,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"`"}}} -{"type":"assistant/chunk","seq":218,"time":1784525378257,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"."}}} -{"type":"assistant/chunk","seq":219,"time":1784525378257,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":220,"time":1784525378257,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":221,"time":1784525378320,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The file has two lines:\n- Line 1: `project notes`\n- Line 2: `- the greeting message still says \"helo wrld\"`\n\nThe user says line 2 has a typo and should say \"hello world\". So I need to replace line 2 with \"hello world\".\n\nLet me present the plan."}}}} -{"type":"assistant/chunk","seq":222,"time":1784525378320,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","arguments":"{\"plan\": \"# Fix the greeting typo\\n\\n## Single step\\n1. **Edit line 2 of `notes.txt`** — Replace the content of line 2 (`- the greeting message still says \\\"helo wrld\\\"`) with `hello world`.\"}"}}}} -{"type":"assistant/chunk","seq":223,"time":1784525378320,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":33,"outputTokens":166,"cacheReadTokens":3328,"reasoningTokens":70}}}} -{"type":"assistant/chunk","seq":224,"time":1784525378321,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":225,"time":1784525378321,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The file has two lines:\n- Line 1: `project notes`\n- Line 2: `- the greeting message still says \"helo wrld\"`\n\nThe user says line 2 has a typo and should say \"hello world\". So I need to replace line 2 with \"hello world\".\n\nLet me present the plan."},{"type":"tool-call","id":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","arguments":"{\"plan\": \"# Fix the greeting typo\\n\\n## Single step\\n1. **Edit line 2 of `notes.txt`** — Replace the content of line 2 (`- the greeting message still says \\\"helo wrld\\\"`) with `hello world`.\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":33,"outputTokens":166,"cacheReadTokens":3328,"reasoningTokens":70}},"sourceEventSeqs":[88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224],"surfaceOp":"append"} -{"type":"tool/call","seq":226,"time":1784525378322,"data":{"turn":1,"step":2,"callId":"call_00_6RLxuiGtAFswvfLnWdt63143","name":"exit_plan_mode","arguments":"{\"plan\": \"# Fix the greeting typo\\n\\n## Single step\\n1. **Edit line 2 of `notes.txt`** — Replace the content of line 2 (`- the greeting message still says \\\"helo wrld\\\"`) with `hello world`.\"}"}} -{"type":"tool/result","seq":227,"time":1784525378329,"data":{"turn":1,"step":2,"callId":"call_00_6RLxuiGtAFswvfLnWdt63143","content":[{"type":"text","text":"Plan approved — plan mode exited; carry out the plan starting with your next step."}],"isError":false},"sourceEventSeqs":[226],"surfaceOp":"append"} -{"type":"step/end","seq":228,"time":1784525378329,"data":{"turn":1,"step":2}} -{"type":"plan/mode","seq":229,"time":1784525378329,"data":{"active":false}} -{"type":"step/start","seq":230,"time":1784525378330,"data":{"turn":1,"step":3}} -{"type":"request/header","seq":231,"time":1784553020470,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"change"}} -{"type":"assistant/chunk","seq":232,"time":1784525378723,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":233,"time":1784525378723,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":234,"time":1784525378807,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" plan"}}} -{"type":"assistant/chunk","seq":235,"time":1784525378835,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" is"}}} -{"type":"assistant/chunk","seq":236,"time":1784525378836,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" approved"}}} -{"type":"assistant/chunk","seq":237,"time":1784525378836,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":238,"time":1784525378836,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" Now"}}} -{"type":"assistant/chunk","seq":239,"time":1784525378836,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":240,"time":1784525378837,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" need"}}} -{"type":"assistant/chunk","seq":241,"time":1784525378866,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":242,"time":1784525378867,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" apply"}}} -{"type":"assistant/chunk","seq":243,"time":1784525378867,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} -{"type":"assistant/chunk","seq":244,"time":1784525378867,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" that"}}} -{"type":"assistant/chunk","seq":245,"time":1784525378899,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" one"}}} -{"type":"assistant/chunk","seq":246,"time":1784525378899,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" edit"}}} -{"type":"assistant/chunk","seq":247,"time":1784525378899,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":":"}}} -{"type":"assistant/chunk","seq":248,"time":1784525378900,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" change"}}} -{"type":"assistant/chunk","seq":249,"time":1784525378927,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" line"}}} -{"type":"assistant/chunk","seq":250,"time":1784525378928,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":251,"time":1784525378928,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"2"}}} -{"type":"assistant/chunk","seq":252,"time":1784525378928,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" of"}}} -{"type":"assistant/chunk","seq":253,"time":1784525378928,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" notes"}}} -{"type":"assistant/chunk","seq":254,"time":1784525378959,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":".txt"}}} -{"type":"assistant/chunk","seq":255,"time":1784525378960,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":256,"time":1784525378961,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" say"}}} -{"type":"assistant/chunk","seq":257,"time":1784525378961,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":258,"time":1784525378961,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"hello"}}} -{"type":"assistant/chunk","seq":259,"time":1784525378961,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" world"}}} -{"type":"assistant/chunk","seq":260,"time":1784525378989,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} -{"type":"assistant/chunk","seq":261,"time":1784525378990,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":262,"time":1784525379021,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"'ll"}}} -{"type":"assistant/chunk","seq":263,"time":1784525379021,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" use"}}} -{"type":"assistant/chunk","seq":264,"time":1784525379022,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":265,"time":1784525379022,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" edit"}}} -{"type":"assistant/chunk","seq":266,"time":1784525379052,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" tool"}}} -{"type":"assistant/chunk","seq":267,"time":1784525379052,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":268,"time":1784525379083,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" replace"}}} -{"type":"assistant/chunk","seq":269,"time":1784525379084,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":270,"time":1784525379084,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" current"}}} -{"type":"assistant/chunk","seq":271,"time":1784525379115,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" line"}}} -{"type":"assistant/chunk","seq":272,"time":1784525379116,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":273,"time":1784525379116,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"2"}}} -{"type":"assistant/chunk","seq":274,"time":1784525379116,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":" content"}}} -{"type":"assistant/chunk","seq":275,"time":1784525379145,"data":{"turn":1,"step":3,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":276,"time":1784525379211,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":277,"time":1784525379211,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":278,"time":1784525379240,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":279,"time":1784525379241,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":280,"time":1784525379241,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"file"}}} -{"type":"assistant/chunk","seq":281,"time":1784525379241,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"_path"}}} -{"type":"assistant/chunk","seq":282,"time":1784525379271,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":283,"time":1784525379272,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":284,"time":1784525379272,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":285,"time":1784525379272,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"notes"}}} -{"type":"assistant/chunk","seq":286,"time":1784525379300,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":287,"time":1784525379300,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":288,"time":1784525379330,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":289,"time":1784525379330,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":290,"time":1784525379330,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"old"}}} -{"type":"assistant/chunk","seq":291,"time":1784525379330,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"_string"}}} -{"type":"assistant/chunk","seq":292,"time":1784525379362,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":293,"time":1784525379362,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":294,"time":1784525379362,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":295,"time":1784525379362,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"-"}}} -{"type":"assistant/chunk","seq":296,"time":1784525379393,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":297,"time":1784525379394,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":" greeting"}}} -{"type":"assistant/chunk","seq":298,"time":1784525379394,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":" message"}}} -{"type":"assistant/chunk","seq":299,"time":1784525379394,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":" still"}}} -{"type":"assistant/chunk","seq":300,"time":1784525379424,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":" says"}}} -{"type":"assistant/chunk","seq":301,"time":1784525379425,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":" \\\""}}} -{"type":"assistant/chunk","seq":302,"time":1784525379425,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"hel"}}} -{"type":"assistant/chunk","seq":303,"time":1784525379425,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"o"}}} -{"type":"assistant/chunk","seq":304,"time":1784525379455,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":" wr"}}} -{"type":"assistant/chunk","seq":305,"time":1784525379456,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"ld"}}} -{"type":"assistant/chunk","seq":306,"time":1784525379456,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\\\""}}} -{"type":"assistant/chunk","seq":307,"time":1784525379456,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":308,"time":1784525379486,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":309,"time":1784525379487,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":310,"time":1784525379519,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"new"}}} -{"type":"assistant/chunk","seq":311,"time":1784525379520,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"_string"}}} -{"type":"assistant/chunk","seq":312,"time":1784525379520,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":313,"time":1784525379520,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":314,"time":1784525379548,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":315,"time":1784525379548,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"hello"}}} -{"type":"assistant/chunk","seq":316,"time":1784525379548,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":" world"}}} -{"type":"assistant/chunk","seq":317,"time":1784525379548,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":318,"time":1784525379579,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":319,"time":1784525379646,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The plan is approved. Now I need to apply exactly that one edit: change line 2 of notes.txt to say \"hello world\". I'll use the edit tool to replace the current line 2 content."}}}} -{"type":"assistant/chunk","seq":320,"time":1784525379646,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","arguments":"{\"file_path\": \"notes.txt\", \"old_string\": \"- the greeting message still says \\\"helo wrld\\\"\", \"new_string\": \"hello world\"}"}}}} -{"type":"assistant/chunk","seq":321,"time":1784525379646,"data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":3269,"outputTokens":134,"cacheReadTokens":0,"reasoningTokens":43}}}} -{"type":"assistant/chunk","seq":322,"time":1784525379646,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":323,"time":1784525379647,"data":{"turn":1,"step":3,"content":[{"type":"reasoning","text":"The plan is approved. Now I need to apply exactly that one edit: change line 2 of notes.txt to say \"hello world\". I'll use the edit tool to replace the current line 2 content."},{"type":"tool-call","id":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","arguments":"{\"file_path\": \"notes.txt\", \"old_string\": \"- the greeting message still says \\\"helo wrld\\\"\", \"new_string\": \"hello world\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":3269,"outputTokens":134,"cacheReadTokens":0,"reasoningTokens":43}},"sourceEventSeqs":[232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322],"surfaceOp":"append"} -{"type":"tool/call","seq":324,"time":1784525379647,"data":{"turn":1,"step":3,"callId":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","name":"edit","arguments":"{\"file_path\": \"notes.txt\", \"old_string\": \"- the greeting message still says \\\"helo wrld\\\"\", \"new_string\": \"hello world\"}"}} -{"type":"tool/result","seq":325,"time":1784525379652,"data":{"turn":1,"step":3,"callId":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","content":[{"type":"text","text":"Error: edit requires reading \"/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-tia05W/notes.txt\" first"}],"isError":true,"error":{"name":"FsError","code":"FS_NOT_OBSERVED"}},"sourceEventSeqs":[324],"surfaceOp":"append"} -{"type":"step/end","seq":326,"time":1784525379652,"data":{"turn":1,"step":3}} -{"type":"step/start","seq":327,"time":1784525379655,"data":{"turn":1,"step":4}} -{"type":"assistant/chunk","seq":328,"time":1784525380205,"data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":329,"time":1784525380205,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"I"}}} -{"type":"assistant/chunk","seq":330,"time":1784525380298,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" need"}}} -{"type":"assistant/chunk","seq":331,"time":1784525380329,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":332,"time":1784525380330,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" read"}}} -{"type":"assistant/chunk","seq":333,"time":1784525380330,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":334,"time":1784525380360,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" file"}}} -{"type":"assistant/chunk","seq":335,"time":1784525380361,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" first"}}} -{"type":"assistant/chunk","seq":336,"time":1784525380361,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" before"}}} -{"type":"assistant/chunk","seq":337,"time":1784525380361,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" editing"}}} -{"type":"assistant/chunk","seq":338,"time":1784525380361,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} -{"type":"assistant/chunk","seq":339,"time":1784525380391,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":340,"time":1784525380392,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} -{"type":"assistant/chunk","seq":341,"time":1784525380392,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":342,"time":1784525380392,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" read"}}} -{"type":"assistant/chunk","seq":343,"time":1784525380392,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} -{"type":"assistant/chunk","seq":344,"time":1784525380422,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} -{"type":"assistant/chunk","seq":345,"time":1784525380422,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" then"}}} -{"type":"assistant/chunk","seq":346,"time":1784525380423,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" apply"}}} -{"type":"assistant/chunk","seq":347,"time":1784525380423,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":348,"time":1784525380423,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":" edit"}}} -{"type":"assistant/chunk","seq":349,"time":1784525380423,"data":{"turn":1,"step":4,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":350,"time":1784525380516,"data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":351,"time":1784525380516,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":352,"time":1784525380547,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":353,"time":1784525380547,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":354,"time":1784525380547,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":"file"}}} -{"type":"assistant/chunk","seq":355,"time":1784525380547,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":"_path"}}} -{"type":"assistant/chunk","seq":356,"time":1784525380547,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":357,"time":1784525380579,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":358,"time":1784525380580,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":359,"time":1784525380580,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":"notes"}}} -{"type":"assistant/chunk","seq":360,"time":1784525380580,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":361,"time":1784525380610,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":362,"time":1784525380610,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":363,"time":1784525380678,"data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"I need to read the file first before editing it. Let me read it and then apply the edit."}}}} -{"type":"assistant/chunk","seq":364,"time":1784525380678,"data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","arguments":"{\"file_path\": \"notes.txt\"}"}}}} -{"type":"assistant/chunk","seq":365,"time":1784525380678,"data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":262,"outputTokens":66,"cacheReadTokens":3200,"reasoningTokens":21}}}} -{"type":"assistant/chunk","seq":366,"time":1784525380678,"data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":367,"time":1784525380679,"data":{"turn":1,"step":4,"content":[{"type":"reasoning","text":"I need to read the file first before editing it. Let me read it and then apply the edit."},{"type":"tool-call","id":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","arguments":"{\"file_path\": \"notes.txt\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":262,"outputTokens":66,"cacheReadTokens":3200,"reasoningTokens":21}},"sourceEventSeqs":[328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366],"surfaceOp":"append"} -{"type":"tool/call","seq":368,"time":1784525380679,"data":{"turn":1,"step":4,"callId":"call_00_XG9RoTfylfw20IP0dmrV7315","name":"read","arguments":"{\"file_path\": \"notes.txt\"}"}} -{"type":"tool/result","seq":369,"time":1784525380686,"data":{"turn":1,"step":4,"callId":"call_00_XG9RoTfylfw20IP0dmrV7315","content":[{"type":"text","text":"<path>/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-tia05W/notes.txt</path>\n<type>file</type>\n<content>\n1: project notes\n2: - the greeting message still says \"helo wrld\"\n\n(End of file - total 2 lines)\n</content>"}],"isError":false},"sourceEventSeqs":[368],"surfaceOp":"append"} -{"type":"step/end","seq":370,"time":1784525380686,"data":{"turn":1,"step":4}} -{"type":"step/start","seq":371,"time":1784525380687,"data":{"turn":1,"step":5}} -{"type":"assistant/chunk","seq":372,"time":1784525381105,"data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":373,"time":1784525381105,"data":{"turn":1,"step":5,"chunk":{"type":"reasoning-delta","index":0,"text":"Now"}}} -{"type":"assistant/chunk","seq":374,"time":1784525381207,"data":{"turn":1,"step":5,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} -{"type":"assistant/chunk","seq":375,"time":1784525381237,"data":{"turn":1,"step":5,"chunk":{"type":"reasoning-delta","index":0,"text":" can"}}} -{"type":"assistant/chunk","seq":376,"time":1784525381237,"data":{"turn":1,"step":5,"chunk":{"type":"reasoning-delta","index":0,"text":" apply"}}} -{"type":"assistant/chunk","seq":377,"time":1784525381237,"data":{"turn":1,"step":5,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} -{"type":"assistant/chunk","seq":378,"time":1784525381238,"data":{"turn":1,"step":5,"chunk":{"type":"reasoning-delta","index":0,"text":" edit"}}} -{"type":"assistant/chunk","seq":379,"time":1784525381274,"data":{"turn":1,"step":5,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":380,"time":1784525381363,"data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":381,"time":1784525381363,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":382,"time":1784525381364,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":383,"time":1784525381364,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":384,"time":1784525381394,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"file"}}} -{"type":"assistant/chunk","seq":385,"time":1784525381395,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"_path"}}} -{"type":"assistant/chunk","seq":386,"time":1784525381395,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":387,"time":1784525381395,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":388,"time":1784525381427,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":389,"time":1784525381427,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"notes"}}} -{"type":"assistant/chunk","seq":390,"time":1784525381428,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":391,"time":1784525381428,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":392,"time":1784525381457,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":393,"time":1784525381458,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":394,"time":1784525381489,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"old"}}} -{"type":"assistant/chunk","seq":395,"time":1784525381490,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"_string"}}} -{"type":"assistant/chunk","seq":396,"time":1784525381490,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":397,"time":1784525381490,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":398,"time":1784525381520,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":399,"time":1784525381520,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"-"}}} -{"type":"assistant/chunk","seq":400,"time":1784525381521,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":" the"}}} -{"type":"assistant/chunk","seq":401,"time":1784525381521,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":" greeting"}}} -{"type":"assistant/chunk","seq":402,"time":1784525381521,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":" message"}}} -{"type":"assistant/chunk","seq":403,"time":1784525381521,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":" still"}}} -{"type":"assistant/chunk","seq":404,"time":1784525381552,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":" says"}}} -{"type":"assistant/chunk","seq":405,"time":1784525381552,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":" \\\""}}} -{"type":"assistant/chunk","seq":406,"time":1784525381552,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"hel"}}} -{"type":"assistant/chunk","seq":407,"time":1784525381552,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"o"}}} -{"type":"assistant/chunk","seq":408,"time":1784525381552,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":" wr"}}} -{"type":"assistant/chunk","seq":409,"time":1784525381552,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"ld"}}} -{"type":"assistant/chunk","seq":410,"time":1784525381583,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\\\""}}} -{"type":"assistant/chunk","seq":411,"time":1784525381583,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":412,"time":1784525381614,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":", "}}} -{"type":"assistant/chunk","seq":413,"time":1784525381615,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":414,"time":1784525381615,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"new"}}} -{"type":"assistant/chunk","seq":415,"time":1784525381615,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"_string"}}} -{"type":"assistant/chunk","seq":416,"time":1784525381647,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":417,"time":1784525381647,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":418,"time":1784525381647,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":419,"time":1784525381647,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"hello"}}} -{"type":"assistant/chunk","seq":420,"time":1784525381683,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":" world"}}} -{"type":"assistant/chunk","seq":421,"time":1784525381684,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":422,"time":1784525381709,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":423,"time":1784525381744,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Now I can apply the edit."}}}} -{"type":"assistant/chunk","seq":424,"time":1784525381744,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","arguments":"{\"file_path\": \"notes.txt\", \"old_string\": \"- the greeting message still says \\\"helo wrld\\\"\", \"new_string\": \"hello world\"}"}}}} -{"type":"assistant/chunk","seq":425,"time":1784525381745,"data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":169,"outputTokens":98,"cacheReadTokens":3456,"reasoningTokens":7}}}} -{"type":"assistant/chunk","seq":426,"time":1784525381745,"data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":427,"time":1784525381746,"data":{"turn":1,"step":5,"content":[{"type":"reasoning","text":"Now I can apply the edit."},{"type":"tool-call","id":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","arguments":"{\"file_path\": \"notes.txt\", \"old_string\": \"- the greeting message still says \\\"helo wrld\\\"\", \"new_string\": \"hello world\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":169,"outputTokens":98,"cacheReadTokens":3456,"reasoningTokens":7}},"sourceEventSeqs":[372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426],"surfaceOp":"append"} -{"type":"tool/call","seq":428,"time":1784525381746,"data":{"turn":1,"step":5,"callId":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","name":"edit","arguments":"{\"file_path\": \"notes.txt\", \"old_string\": \"- the greeting message still says \\\"helo wrld\\\"\", \"new_string\": \"hello world\"}"}} -{"type":"tool/result","seq":429,"time":1784525381766,"data":{"turn":1,"step":5,"callId":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","content":[{"type":"text","text":"The file /var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-tia05W/notes.txt has been updated successfully."}],"isError":false,"meta":{"diffs":[{"path":"notes.txt","oldText":"project notes\n- the greeting message still says \"helo wrld\"","newText":"project notes\nhello world"}]}},"sourceEventSeqs":[428],"surfaceOp":"append"} -{"type":"step/end","seq":430,"time":1784525381766,"data":{"turn":1,"step":5}} -{"type":"step/start","seq":431,"time":1784525381768,"data":{"turn":1,"step":6}} -{"type":"assistant/chunk","seq":432,"time":1784525382334,"data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":433,"time":1784525382334,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} -{"type":"assistant/chunk","seq":434,"time":1784525382411,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" edit"}}} -{"type":"assistant/chunk","seq":435,"time":1784525382439,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" was"}}} -{"type":"assistant/chunk","seq":436,"time":1784525382440,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" applied"}}} -{"type":"assistant/chunk","seq":437,"time":1784525382440,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" successfully"}}} -{"type":"assistant/chunk","seq":438,"time":1784525382467,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":439,"time":1784525382468,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" Line"}}} -{"type":"assistant/chunk","seq":440,"time":1784525382468,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":441,"time":1784525382468,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":"2"}}} -{"type":"assistant/chunk","seq":442,"time":1784525382496,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" of"}}} -{"type":"assistant/chunk","seq":443,"time":1784525382497,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" notes"}}} -{"type":"assistant/chunk","seq":444,"time":1784525382497,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":".txt"}}} -{"type":"assistant/chunk","seq":445,"time":1784525382497,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" now"}}} -{"type":"assistant/chunk","seq":446,"time":1784525382524,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" reads"}}} -{"type":"assistant/chunk","seq":447,"time":1784525382524,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":448,"time":1784525382524,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":"hello"}}} -{"type":"assistant/chunk","seq":449,"time":1784525382524,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" world"}}} -{"type":"assistant/chunk","seq":450,"time":1784525382525,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} -{"type":"assistant/chunk","seq":451,"time":1784525382553,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":" Done"}}} -{"type":"assistant/chunk","seq":452,"time":1784525382554,"data":{"turn":1,"step":6,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":453,"time":1784525382580,"data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":454,"time":1784525382580,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":"Done"}}} -{"type":"assistant/chunk","seq":455,"time":1784525382580,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":"."}}} -{"type":"assistant/chunk","seq":456,"time":1784525382608,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":" Line"}}} -{"type":"assistant/chunk","seq":457,"time":1784525382608,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":" "}}} -{"type":"assistant/chunk","seq":458,"time":1784525382609,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":"2"}}} -{"type":"assistant/chunk","seq":459,"time":1784525382609,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":" of"}}} -{"type":"assistant/chunk","seq":460,"time":1784525382636,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":461,"time":1784525382636,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":"notes"}}} -{"type":"assistant/chunk","seq":462,"time":1784525382636,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":".txt"}}} -{"type":"assistant/chunk","seq":463,"time":1784525382637,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":"`"}}} -{"type":"assistant/chunk","seq":464,"time":1784525382637,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":" now"}}} -{"type":"assistant/chunk","seq":465,"time":1784525382637,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":" reads"}}} -{"type":"assistant/chunk","seq":466,"time":1784525382664,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":" `"}}} -{"type":"assistant/chunk","seq":467,"time":1784525382664,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":"hello"}}} -{"type":"assistant/chunk","seq":468,"time":1784525382697,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":" world"}}} -{"type":"assistant/chunk","seq":469,"time":1784525382697,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":1,"text":"`."}}} -{"type":"assistant/chunk","seq":470,"time":1784525382697,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The edit was applied successfully. Line 2 of notes.txt now reads \"hello world\". Done."}}}} -{"type":"assistant/chunk","seq":471,"time":1784525382697,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"Done. Line 2 of `notes.txt` now reads `hello world`."}}}} -{"type":"assistant/chunk","seq":472,"time":1784525382697,"data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":196,"outputTokens":37,"cacheReadTokens":3584,"reasoningTokens":20}}}} -{"type":"assistant/chunk","seq":473,"time":1784525382697,"data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":474,"time":1784525382698,"data":{"turn":1,"step":6,"content":[{"type":"reasoning","text":"The edit was applied successfully. Line 2 of notes.txt now reads \"hello world\". Done."},{"type":"text","text":"Done. Line 2 of `notes.txt` now reads `hello world`."}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":196,"outputTokens":37,"cacheReadTokens":3584,"reasoningTokens":20}},"sourceEventSeqs":[432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473],"surfaceOp":"append"} -{"type":"step/end","seq":475,"time":1784525382698,"data":{"turn":1,"step":6}} -{"type":"turn/end","seq":476,"time":1784525382698,"data":{"turn":1,"reason":{"kind":"completed"}}} -{"type":"turn/start","seq":477,"time":1784525382723,"data":{"turn":2,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":478,"time":1784525382723,"data":{"content":[{"type":"text","text":"Read notes.txt (relative path notes.txt) and reply with the single word DONE if line 2 now says hello world."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"step/start","seq":479,"time":1784525382724,"data":{"turn":2,"step":1}} -{"type":"assistant/chunk","seq":480,"time":1784525383445,"data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":481,"time":1784525383446,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":""}}} -{"type":"assistant/chunk","seq":482,"time":1784525383458,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":"{"}}} -{"type":"assistant/chunk","seq":483,"time":1784525383458,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":484,"time":1784525383458,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":"file"}}} -{"type":"assistant/chunk","seq":485,"time":1784525383459,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":"_path"}}} -{"type":"assistant/chunk","seq":486,"time":1784525383459,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":487,"time":1784525383459,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":": "}}} -{"type":"assistant/chunk","seq":488,"time":1784525383486,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":489,"time":1784525383486,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":"notes"}}} -{"type":"assistant/chunk","seq":490,"time":1784525383486,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":".txt"}}} -{"type":"assistant/chunk","seq":491,"time":1784525383486,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":"\""}}} -{"type":"assistant/chunk","seq":492,"time":1784525383520,"data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","argumentsDelta":"}"}}} -{"type":"assistant/chunk","seq":493,"time":1784525383584,"data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","arguments":"{\"file_path\": \"notes.txt\"}"}}}} -{"type":"assistant/chunk","seq":494,"time":1784525383584,"data":{"turn":2,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":115,"outputTokens":45,"cacheReadTokens":3712,"reasoningTokens":0}}}} -{"type":"assistant/chunk","seq":495,"time":1784525383585,"data":{"turn":2,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":496,"time":1784525383585,"data":{"turn":2,"step":1,"content":[{"type":"tool-call","id":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","arguments":"{\"file_path\": \"notes.txt\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":115,"outputTokens":45,"cacheReadTokens":3712,"reasoningTokens":0}},"sourceEventSeqs":[480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495],"surfaceOp":"append"} -{"type":"tool/call","seq":497,"time":1784525383585,"data":{"turn":2,"step":1,"callId":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","name":"read","arguments":"{\"file_path\": \"notes.txt\"}"}} -{"type":"tool/result","seq":498,"time":1784525383589,"data":{"turn":2,"step":1,"callId":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","content":[{"type":"text","text":"<path>/var/folders/2g/b32ct0qn1d728l_v6tdkjytr0000gn/T/acp-snap-cwd-tia05W/notes.txt</path>\n<type>file</type>\n<content>\n1: project notes\n2: hello world\n\n(End of file - total 2 lines)\n</content>"}],"isError":false},"sourceEventSeqs":[497],"surfaceOp":"append"} -{"type":"step/end","seq":499,"time":1784525383590,"data":{"turn":2,"step":1}} -{"type":"step/start","seq":500,"time":1784525383590,"data":{"turn":2,"step":2}} -{"type":"assistant/chunk","seq":501,"time":1784525384009,"data":{"turn":2,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"assistant/chunk","seq":502,"time":1784525384010,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"Line"}}} -{"type":"assistant/chunk","seq":503,"time":1784525384158,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} -{"type":"assistant/chunk","seq":504,"time":1784525384189,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"2"}}} -{"type":"assistant/chunk","seq":505,"time":1784525384190,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" says"}}} -{"type":"assistant/chunk","seq":506,"time":1784525384190,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} -{"type":"assistant/chunk","seq":507,"time":1784525384190,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"hello"}}} -{"type":"assistant/chunk","seq":508,"time":1784525384190,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" world"}}} -{"type":"assistant/chunk","seq":509,"time":1784525384191,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} -{"type":"assistant/chunk","seq":510,"time":1784525384221,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" The"}}} -{"type":"assistant/chunk","seq":511,"time":1784525384222,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} -{"type":"assistant/chunk","seq":512,"time":1784525384222,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} -{"type":"assistant/chunk","seq":513,"time":1784525384255,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} -{"type":"assistant/chunk","seq":514,"time":1784525384256,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} -{"type":"assistant/chunk","seq":515,"time":1784525384256,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} -{"type":"assistant/chunk","seq":516,"time":1784525384257,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} -{"type":"assistant/chunk","seq":517,"time":1784525384284,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} -{"type":"assistant/chunk","seq":518,"time":1784525384313,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" single"}}} -{"type":"assistant/chunk","seq":519,"time":1784525384313,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" word"}}} -{"type":"assistant/chunk","seq":520,"time":1784525384314,"data":{"turn":2,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} -{"type":"assistant/chunk","seq":521,"time":1784525384348,"data":{"turn":2,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":522,"time":1784525384348,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} -{"type":"assistant/chunk","seq":523,"time":1784525384349,"data":{"turn":2,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} -{"type":"assistant/chunk","seq":524,"time":1784525384349,"data":{"turn":2,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Line 2 says \"hello world\". The user wants me to reply with a single word."}}}} -{"type":"assistant/chunk","seq":525,"time":1784525384349,"data":{"turn":2,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} -{"type":"assistant/chunk","seq":526,"time":1784525384349,"data":{"turn":2,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":247,"outputTokens":22,"cacheReadTokens":3712,"reasoningTokens":19}}}} -{"type":"assistant/chunk","seq":527,"time":1784525384349,"data":{"turn":2,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":528,"time":1784525384350,"data":{"turn":2,"step":2,"content":[{"type":"reasoning","text":"Line 2 says \"hello world\". The user wants me to reply with a single word."},{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":247,"outputTokens":22,"cacheReadTokens":3712,"reasoningTokens":19}},"sourceEventSeqs":[501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527],"surfaceOp":"append"} -{"type":"step/end","seq":529,"time":1784525384350,"data":{"turn":2,"step":2}} -{"type":"turn/end","seq":530,"time":1784525384350,"data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/plan-mode/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/plan-mode/stdout.expected.jsonl deleted file mode 100644 index 0976b68317..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode/stdout.expected.jsonl +++ /dev/null @@ -1,267 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"current_mode_update","currentModeId":"plan"}}} -{"jsonrpc":"2.0","id":3,"result":{}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"The typo is on line","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"cat"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" notes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" inspect"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Present"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" via"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_mode"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"3"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" After"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" approval"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" make"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" start"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" step"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_jRYWnAwUo7zSx2WVsRZ83655","title":"cat notes.txt","kind":"execute","status":"in_progress","rawInput":"cat notes.txt","content":[{"type":"content","content":{"type":"text","text":"Inspect notes.txt contents"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_jRYWnAwUo7zSx2WVsRZ83655","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nproject notes\n- the greeting message still says \"helo wrld\"\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" has"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" two"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" lines"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"project"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" notes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" greeting"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" message"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" still"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" says"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hel"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"o"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wr"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ld"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"`\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" says"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" has"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" typ"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"o"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" say"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" world"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" So"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" replace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" world"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" present"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_6RLxuiGtAFswvfLnWdt63143","title":"Fix the greeting typo","kind":"other","status":"in_progress","content":[{"type":"content","content":{"type":"text","text":"# Fix the greeting typo\n\n## Single step\n1. **Edit line 2 of `notes.txt`** — Replace the content of line 2 (`- the greeting message still says \"helo wrld\"`) with `hello world`."}}]}}} -{"jsonrpc":"2.0","id":1,"method":"elicitation/create","params":{"sessionId":"{{sessionId}}","mode":"form","message":"Approve this plan and leave plan mode?\n\n# Fix the greeting typo\n\n## Single step\n1. **Edit line 2 of `notes.txt`** — Replace the content of line 2 (`- the greeting message still says \"helo wrld\"`) with `hello world`.","requestedSchema":{"type":"object","title":"Plan review","properties":{"choice":{"type":"string","title":"Approve this plan and leave plan mode?","description":"Choose one option, or fill a custom answer below.","oneOf":[{"const":"Approve","title":"Approve: Leave plan mode; the plan is carried out from the next step."},{"const":"Keep planning","title":"Keep planning: Stay in plan mode; feedback goes back to the model."}]},"custom":{"type":"string","title":"Custom answer","description":"Optional free-form answer. Leave empty to use the selected option."}},"required":[]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_6RLxuiGtAFswvfLnWdt63143","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Plan approved — plan mode exited; carry out the plan starting with your next step."}}],"title":"Plan review"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"current_mode_update","currentModeId":"default"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" approved"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" apply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" one"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" change"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" of"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" notes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" say"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" world"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'ll"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" replace"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" current"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" content"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","title":"Edit notes.txt","kind":"edit","status":"in_progress","locations":[{"path":"notes.txt"}],"content":[{"type":"diff","path":"notes.txt","oldText":"- the greeting message still says \"helo wrld\"","newText":"hello world"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_eYuZ6fAuzqr8vtFd3oRg2452","status":"failed","content":[{"type":"content","content":{"type":"text","text":"Error: edit requires reading \"{{cwd}}/notes.txt\" first"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" before"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" editing"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" apply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_XG9RoTfylfw20IP0dmrV7315","title":"Read notes.txt","kind":"read","status":"in_progress","locations":[{"path":"notes.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_XG9RoTfylfw20IP0dmrV7315","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/notes.txt</path>\n<type>file</type>\n<content>\n1: project notes\n2: - the greeting message still says \"helo wrld\"\n\n(End of file - total 2 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" can"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" apply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","title":"Edit notes.txt","kind":"edit","status":"in_progress","locations":[{"path":"notes.txt"}],"content":[{"type":"diff","path":"notes.txt","oldText":"- the greeting message still says \"helo wrld\"","newText":"hello world"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_7H6VFdLjBqzzW9M5Z4OR8016","status":"completed","content":[{"type":"diff","path":"notes.txt","oldText":"project notes\n- the greeting message still says \"helo wrld\"","newText":"project notes\nhello world"}],"title":"Edit notes.txt"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" edit"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" was"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" applied"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" successfully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" of"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" notes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reads"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" world"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Done"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Done"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" Line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" of"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"notes"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"`"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" reads"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" `"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" world"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"`."}}}} -{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","title":"Read notes.txt","kind":"read","status":"in_progress","locations":[{"path":"notes.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_ET_5aWcvKPYl6cZ73MsPcV29873","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/notes.txt</path>\n<type>file</type>\n<content>\n1: project notes\n2: hello world\n\n(End of file - total 2 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" "}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" says"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" world"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","id":5,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/plan-mode/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/plan-mode/system-prompt.expected.md deleted file mode 100644 index a46e43ec2e..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode/system-prompt.expected.md +++ /dev/null @@ -1,70 +0,0 @@ -You are an AI agent powered by the DeepSeek Harness SDK. - -You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. - -Verify your work by running the code or tests. Keep answers brief and factual. - - -You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. - -Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery. - -The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed only to keep the request shape stable. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode. - -Resolve discoverable facts by inspection. Use ask_user_question only for user-owned choices or material ambiguity that inspection cannot answer. Do not ask the user where code lives or how current behavior works when you can find out. - -Make the plan decision-complete: state the goal and success criteria; group implementation changes by subsystem; identify public API, schema, and data-flow changes; cover edge cases, failure modes, tests, acceptance criteria, and explicit assumptions. Keep it concise enough to review but detailed enough that another engineer can implement it without making design decisions. - -When ready, call exit_plan_mode with the complete plan markdown, starting with a # title. Make exit_plan_mode the only and final tool call in that assistant response: it presents the plan for approval, and implementation begins only in a later step after approval. Do not paste the final plan as a plain reply or ask "should I proceed?" through prose or ask_user_question. If review rejects it, incorporate the feedback and present again. If the review channel is unavailable or aborted, stay in plan mode and ask the user to switch modes manually; do not proceed with implementation. - - -Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. - -Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes. - -Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session. - -Check the [exit code: N] marker on every bash result; investigate failures before moving on. - -Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. - -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - -Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. - -Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). -<!-- dsh-user-approval-policy:never --> - -Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. - -Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. - -<!-- request/header change 1 --> - -You are an AI agent powered by the DeepSeek Harness SDK. - -You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. - -Verify your work by running the code or tests. Keep answers brief and factual. - - -Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. - -Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes. - -Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session. - -Check the [exit code: N] marker on every bash result; investigate failures before moving on. - -Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. - -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - -Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. - -Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). -<!-- dsh-user-approval-policy:never --> - -Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. - -Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. diff --git a/examples/acp-agent/tests/snapshots/plan-mode/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/plan-mode/tool-schemas.expected.json deleted file mode 100644 index 8bfac915b0..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode/tool-schemas.expected.json +++ /dev/null @@ -1,1510 +0,0 @@ -{ - "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, - { - "name": "bash", - "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", - "parameters": { - "type": "object", - "properties": { - "command": { - "type": "string", - "description": "The bash command to execute." - }, - "description": { - "type": "string", - "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." - }, - "timeoutMs": { - "type": "number", - "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." - }, - "workdir": { - "type": "string", - "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." - }, - "run_in_background": { - "type": "boolean", - "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." - } - }, - "required": [ - "command", - "description" - ] - } - }, - { - "name": "create_goal", - "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The concrete completion objective inferred from the direct human request." - }, - "max_goal_rounds": { - "type": "number", - "description": "Optional positive safe-integer limit on automatic continuation rounds." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "edit", - "description": "Edit an existing UTF-8 text file by replacing literal text.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to edit, resolved by the filesystem backend." - }, - "old_string": { - "type": "string", - "description": "Literal text to replace. Must match exactly." - }, - "new_string": { - "type": "string", - "description": "Literal replacement text. Use an empty string to delete the match." - }, - "replace_all": { - "type": "boolean", - "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "old_string", - "new_string" - ] - } - }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, - { - "name": "get_goal", - "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "ralph", - "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The immutable completion objective for every fresh Ralph round." - }, - "maxRounds": { - "type": "number", - "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "read", - "description": "Read a UTF-8 text file and return line-numbered content.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to read, resolved by the filesystem backend." - }, - "offset": { - "type": "number", - "description": "1-based first line to return. Defaults to 1." - }, - "limit": { - "type": "number", - "description": "Maximum number of lines to return. Defaults to 2000." - } - }, - "required": [ - "file_path" - ] - } - }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, - { - "name": "skill", - "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", - "parameters": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The exact skill name from the available skills list." - } - }, - "required": [ - "name" - ] - } - }, - { - "name": "subagent", - "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "subagent_fork", - "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "task_kill", - "description": "Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "reason": { - "type": "string", - "description": "Optional short reason, recorded in the log and forwarded to the task." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "task_list", - "description": "List your background tasks (running and finished) with their ids, kinds, and statuses.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "task_output", - "description": "Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "wait": { - "type": "boolean", - "description": "Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive." - }, - "timeout_ms": { - "type": "number", - "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "todo_write", - "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", - "parameters": { - "type": "object", - "properties": { - "todos": { - "type": "array", - "description": "The COMPLETE task list, replacing any previous list.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "content": { - "type": "string", - "description": "What the task is — a short imperative line." - }, - "status": { - "type": "string", - "description": "pending (not started) | in_progress (now) | completed (done).", - "enum": [ - "pending", - "in_progress", - "completed" - ] - } - }, - "required": [ - "content", - "status" - ] - } - } - }, - "required": [ - "todos" - ] - } - }, - { - "name": "update_goal", - "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", - "parameters": { - "type": "object", - "properties": { - "goal_id": { - "type": "string", - "description": "Exact id returned by get_goal." - }, - "revision": { - "type": "number", - "description": "Exact positive revision returned by get_goal." - }, - "action": { - "type": "string", - "description": "edit | pause | resume | complete | blocked", - "enum": [ - "edit", - "pause", - "resume", - "complete", - "blocked" - ] - }, - "objective": { - "type": "string", - "description": "Replacement objective; valid only with action edit." - }, - "max_goal_rounds": { - "type": "number", - "description": "Replacement cap; valid only with action edit." - }, - "blocked_reason": { - "type": "string", - "description": "Concrete blocking condition; required only with action blocked." - } - }, - "required": [ - "goal_id", - "revision", - "action" - ] - } - }, - { - "name": "workflow", - "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return <value>` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", - "parameters": { - "type": "object", - "properties": { - "script": { - "type": "string", - "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)." - }, - "meta": { - "type": "object", - "description": "The workflow identity block (plain JSON — never code).", - "additionalProperties": true, - "properties": { - "name": { - "type": "string", - "description": "Short kebab-case workflow name." - }, - "description": { - "type": "string", - "description": "One-line description of what the workflow does." - }, - "whenToUse": { - "type": "string", - "description": "Optional guidance on when this workflow applies." - }, - "phases": { - "type": "array", - "description": "Optional phase declarations matched by phase() calls.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "title": { - "type": "string", - "description": "The phase title phase() calls match by exact string." - }, - "detail": { - "type": "string", - "description": "Optional one-line description of the phase." - }, - "provider": { - "type": "string", - "description": "Optional provider override this phase is expected to use." - }, - "model": { - "type": "string", - "description": "Optional model override this phase is expected to use." - } - }, - "required": [ - "title" - ] - } - } - }, - "required": [ - "name", - "description" - ] - }, - "args": { - "type": "object", - "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", - "additionalProperties": true - } - }, - "required": [ - "script", - "meta" - ] - } - }, - { - "name": "write", - "description": "Create or fully replace a UTF-8 text file.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to write, resolved by the filesystem backend." - }, - "content": { - "type": "string", - "description": "Full UTF-8 text content to write." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "content" - ] - } - } - ], - "changes": [ - [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, - { - "name": "bash", - "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", - "parameters": { - "type": "object", - "properties": { - "command": { - "type": "string", - "description": "The bash command to execute." - }, - "description": { - "type": "string", - "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." - }, - "timeoutMs": { - "type": "number", - "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." - }, - "workdir": { - "type": "string", - "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." - }, - "run_in_background": { - "type": "boolean", - "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." - } - }, - "required": [ - "command", - "description" - ] - } - }, - { - "name": "create_goal", - "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The concrete completion objective inferred from the direct human request." - }, - "max_goal_rounds": { - "type": "number", - "description": "Optional positive safe-integer limit on automatic continuation rounds." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "edit", - "description": "Edit an existing UTF-8 text file by replacing literal text.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to edit, resolved by the filesystem backend." - }, - "old_string": { - "type": "string", - "description": "Literal text to replace. Must match exactly." - }, - "new_string": { - "type": "string", - "description": "Literal replacement text. Use an empty string to delete the match." - }, - "replace_all": { - "type": "boolean", - "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "old_string", - "new_string" - ] - } - }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, - { - "name": "get_goal", - "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "ralph", - "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The immutable completion objective for every fresh Ralph round." - }, - "maxRounds": { - "type": "number", - "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "read", - "description": "Read a UTF-8 text file and return line-numbered content.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to read, resolved by the filesystem backend." - }, - "offset": { - "type": "number", - "description": "1-based first line to return. Defaults to 1." - }, - "limit": { - "type": "number", - "description": "Maximum number of lines to return. Defaults to 2000." - } - }, - "required": [ - "file_path" - ] - } - }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, - { - "name": "skill", - "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", - "parameters": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The exact skill name from the available skills list." - } - }, - "required": [ - "name" - ] - } - }, - { - "name": "subagent", - "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "subagent_fork", - "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." - }, - "prompt": { - "type": "string", - "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "task_kill", - "description": "Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "reason": { - "type": "string", - "description": "Optional short reason, recorded in the log and forwarded to the task." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "task_list", - "description": "List your background tasks (running and finished) with their ids, kinds, and statuses.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "task_output", - "description": "Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", - "parameters": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "Task id returned by the tool that started the background work." - }, - "wait": { - "type": "boolean", - "description": "Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive." - }, - "timeout_ms": { - "type": "number", - "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." - } - }, - "required": [ - "task_id" - ] - } - }, - { - "name": "todo_write", - "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", - "parameters": { - "type": "object", - "properties": { - "todos": { - "type": "array", - "description": "The COMPLETE task list, replacing any previous list.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "content": { - "type": "string", - "description": "What the task is — a short imperative line." - }, - "status": { - "type": "string", - "description": "pending (not started) | in_progress (now) | completed (done).", - "enum": [ - "pending", - "in_progress", - "completed" - ] - } - }, - "required": [ - "content", - "status" - ] - } - } - }, - "required": [ - "todos" - ] - } - }, - { - "name": "update_goal", - "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", - "parameters": { - "type": "object", - "properties": { - "goal_id": { - "type": "string", - "description": "Exact id returned by get_goal." - }, - "revision": { - "type": "number", - "description": "Exact positive revision returned by get_goal." - }, - "action": { - "type": "string", - "description": "edit | pause | resume | complete | blocked", - "enum": [ - "edit", - "pause", - "resume", - "complete", - "blocked" - ] - }, - "objective": { - "type": "string", - "description": "Replacement objective; valid only with action edit." - }, - "max_goal_rounds": { - "type": "number", - "description": "Replacement cap; valid only with action edit." - }, - "blocked_reason": { - "type": "string", - "description": "Concrete blocking condition; required only with action blocked." - } - }, - "required": [ - "goal_id", - "revision", - "action" - ] - } - }, - { - "name": "workflow", - "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return <value>` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", - "parameters": { - "type": "object", - "properties": { - "script": { - "type": "string", - "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)." - }, - "meta": { - "type": "object", - "description": "The workflow identity block (plain JSON — never code).", - "additionalProperties": true, - "properties": { - "name": { - "type": "string", - "description": "Short kebab-case workflow name." - }, - "description": { - "type": "string", - "description": "One-line description of what the workflow does." - }, - "whenToUse": { - "type": "string", - "description": "Optional guidance on when this workflow applies." - }, - "phases": { - "type": "array", - "description": "Optional phase declarations matched by phase() calls.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "title": { - "type": "string", - "description": "The phase title phase() calls match by exact string." - }, - "detail": { - "type": "string", - "description": "Optional one-line description of the phase." - }, - "provider": { - "type": "string", - "description": "Optional provider override this phase is expected to use." - }, - "model": { - "type": "string", - "description": "Optional model override this phase is expected to use." - } - }, - "required": [ - "title" - ] - } - } - }, - "required": [ - "name", - "description" - ] - }, - "args": { - "type": "object", - "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", - "additionalProperties": true - } - }, - "required": [ - "script", - "meta" - ] - } - }, - { - "name": "write", - "description": "Create or fully replace a UTF-8 text file.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to write, resolved by the filesystem backend." - }, - "content": { - "type": "string", - "description": "Full UTF-8 text content to write." - }, - "sandbox_permissions": { - "type": "string", - "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." - } - }, - "required": [ - "file_path", - "content" - ] - } - } - ] - ] -} diff --git a/examples/acp-agent/tests/snapshots/plan-mode/workspace/notes.txt b/examples/acp-agent/tests/snapshots/plan-mode/workspace/notes.txt deleted file mode 100644 index 0230df4b3b..0000000000 --- a/examples/acp-agent/tests/snapshots/plan-mode/workspace/notes.txt +++ /dev/null @@ -1,2 +0,0 @@ -project notes -- the greeting message still says "helo wrld" diff --git a/examples/acp-agent/tests/snapshots/pty-tools/input.json b/examples/acp-agent/tests/snapshots/pty-tools/input.json index abb800b56b..416dd24f4c 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/input.json +++ b/examples/acp-agent/tests/snapshots/pty-tools/input.json @@ -1,6 +1,6 @@ { "steps": [ - { "op": "initialize", "terminalOutput": true }, + { "op": "initialize" }, { "op": "newSession" }, { "op": "prompt", "text": "Exercise the six PTY tools in order, including one missing-session signal error, then reply DONE." } ] diff --git a/examples/acp-agent/tests/snapshots/pty-tools/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/pty-tools/stdout.expected.jsonl index b6ff0e64a1..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/pty-tools/stdout.expected.jsonl @@ -1,18 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-pro\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Exercise the six PTY tools","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"pty-spawn","title":"Open terminal main","kind":"execute","status":"in_progress"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"pty-spawn","status":"completed","content":[{"type":"content","content":{"type":"text","text":"started terminal session pty-1 (main) [type: shell]\ndsh> "}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"pty-send","title":"printf 'PTY_OK\\n'","kind":"execute","status":"in_progress","rawInput":"printf 'PTY_OK\\n'","content":[{"type":"content","content":{"type":"text","text":"Terminal pty-1"}},{"type":"terminal","terminalId":"pty-send"}],"_meta":{"terminal_info":{"terminal_id":"pty-send","cwd":"{{cwd}}"}}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"pty-send","status":"completed","_meta":{"terminal_output":{"terminal_id":"pty-send","data":"K\ndsh> \n[wait: stdin_read]\n[session: running]\n[output truncated]"}}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"pty-read","title":"Read terminal pty-1","kind":"read","status":"in_progress","rawInput":{"sessionId":"pty-1","offset":0,"count":20}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"pty-read","status":"completed","content":[{"type":"content","content":{"type":"text","text":"dsh> printf 'PTY_OK\\n'\nPTY_OK\ndsh> \n[lines: 0-3 of 3]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"pty-signal","title":"Signal terminal pty-missing","kind":"execute","status":"in_progress","rawInput":{"sessionId":"pty-missing","signal":"SIGINT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"pty-signal","status":"failed","content":[{"type":"content","content":{"type":"text","text":"Error: unknown PTY session pty-missing"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"pty-kill","title":"Close terminal pty-1","kind":"delete","status":"in_progress"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"pty-kill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"closed terminal session pty-1"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"pty-list","title":"List terminal sessions","kind":"read","status":"in_progress"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"pty-list","status":"completed","content":[{"type":"content","content":{"type":"text","text":"(no terminal sessions)"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json index 0748a0f153..d29602b97d 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json @@ -1,68 +1,5 @@ { "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, { "name": "bash", "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", @@ -170,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, { "name": "get_goal", "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", diff --git a/examples/acp-agent/tests/snapshots/reject-extra-dirs/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/reject-extra-dirs/stdout.expected.jsonl index b715cabc47..018593abb5 100644 --- a/examples/acp-agent/tests/snapshots/reject-extra-dirs/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/reject-extra-dirs/stdout.expected.jsonl @@ -1,2 +1,2 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"Invalid params: additionalDirectories is not supported in this MVP"}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"Invalid params: additionalDirectories is not supported"}} diff --git a/examples/acp-agent/tests/snapshots/repeat-tool-guard/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/repeat-tool-guard/stdout.expected.jsonl index e2bc1c699a..2f80460389 100644 --- a/examples/acp-agent/tests/snapshots/repeat-tool-guard/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/repeat-tool-guard/stdout.expected.jsonl @@ -1,21 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Write the todo list 'watch","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_1","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_1","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_2","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_2","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_3","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_3","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_4","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_4","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_5","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_5","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE."}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl index 0f4bee73ca..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl @@ -1,10 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Read request event 4 with","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_session_query_spill","title":"Read event 4","kind":"read","status":"in_progress","rawInput":{"seq":4}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_session_query_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Session {{sessionId}} — Read request event 4 with\nTarget event seq 4:\n```json\n{\n \"type\": \"request/header\",\n \"seq\": 4,\n \"time\": {{eventTime}},\n \"data\": {\n \"header\": {\n \"config\": {\n \"provider\": \"deepseek\",\n \"model\": \"deepseek-v4-flash\"\n },\n rmissions: one sentence for the user explaining why this exact file operation needs the wider access.\"\n }\n },\n \"required\": [\n \"file_path\",\n \"content\"\n ]\n }\n }\n ]\n },\n \"reason\": \"initial\"\n }\n}\n```\n\n(Omitted {{eventOmittedBytes}} bytes. Full formatted result stored at: {{spillLocator:session_event_read.txt}}. Use read with offset/limit, or grep this path to search within it.)"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_verify_session_query_spill","title":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \"$file\" && grep -q session_event_search \"$file\" && echo SPILL_CANONICAL_OK","kind":"execute","status":"in_progress","rawInput":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \"$file\" && grep -q session_event_search \"$file\" && echo SPILL_CANONICAL_OK","content":[{"type":"content","content":{"type":"text","text":"Verify complete session query spill"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_verify_session_query_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nSPILL_CANONICAL_OK\n```"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/session-sandbox-root/input.json b/examples/acp-agent/tests/snapshots/session-sandbox-root/input.json index 9cef40f51d..3d7f41167e 100644 --- a/examples/acp-agent/tests/snapshots/session-sandbox-root/input.json +++ b/examples/acp-agent/tests/snapshots/session-sandbox-root/input.json @@ -2,7 +2,6 @@ "steps": [ { "op": "initialize" }, { "op": "newSession" }, - { "op": "setConfigOption", "configId": "permission", "value": "workspace-write" }, { "op": "prompt", "text": "Use the write tool (NOT bash) to create session-root.txt in the current directory containing exactly: session root. Then reply with exactly the single word DONE." } ] } diff --git a/examples/acp-agent/tests/snapshots/session-sandbox-root/session.jsonl b/examples/acp-agent/tests/snapshots/session-sandbox-root/session.jsonl index e92adbafb9..488de0eebf 100644 --- a/examples/acp-agent/tests/snapshots/session-sandbox-root/session.jsonl +++ b/examples/acp-agent/tests/snapshots/session-sandbox-root/session.jsonl @@ -1,27 +1,24 @@ {"type":"session","version":0,"id":"00000000-0000-0000-0000-000000000000","createdAt":0,"cwd":"/Users/cty/acp-snap-cwd-MABAjO","delegationDepth":0} {"type":"turn/start","seq":0,"time":1784567324138,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"permission/preset","seq":1,"time":1784567324138,"data":{"preset":"workspace-write"}} -{"type":"sandbox/mode","seq":2,"time":1784567324138,"data":{"mode":"workspace-write"}} -{"type":"approval/policy","seq":3,"time":1784567324138,"data":{"policy":"ask"}} -{"type":"user/message","seq":4,"time":1784567324138,"data":{"content":[{"type":"text","text":"Use the write tool (NOT bash) to create session-root.txt in the current directory containing exactly: session root. Then reply with exactly the single word DONE."}],"source":{"kind":"user"}},"surfaceOp":"append"} -{"type":"session/title","seq":5,"time":1784567324138,"data":{"title":"Use the write tool (NOT","messageSeqs":[4],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":6,"time":1784567324142,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":7,"time":1784567324142,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"assistant/chunk","seq":8,"time":1784567324143,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":9,"time":1784567324143,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_session_root","name":"write","argumentsDelta":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}}} -{"type":"assistant/chunk","seq":10,"time":1784567324143,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_session_root","name":"write","arguments":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}}}} -{"type":"assistant/chunk","seq":11,"time":1784567324143,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} -{"type":"assistant/chunk","seq":12,"time":1784567324143,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":13,"time":1784567324144,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"call_session_root","name":"write","arguments":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[8,9,10,11,12],"surfaceOp":"append"} -{"type":"tool/call","seq":14,"time":1784567324145,"data":{"turn":1,"step":1,"callId":"call_session_root","name":"write","arguments":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}} -{"type":"tool/result","seq":15,"time":1784567324155,"data":{"turn":1,"step":1,"callId":"call_session_root","content":[{"type":"text","text":"<path>/Users/cty/acp-snap-cwd-MABAjO/session-root.txt</path>\n<type>file</type>\n<content>\nCreated file\n</content>"}],"isError":false,"meta":{"diffs":[]}},"sourceEventSeqs":[14],"surfaceOp":"append"} -{"type":"step/end","seq":16,"time":1784567324157,"data":{"turn":1,"step":1}} -{"type":"step/start","seq":17,"time":1784567324157,"data":{"turn":1,"step":2}} -{"type":"assistant/chunk","seq":18,"time":1784567324157,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} -{"type":"assistant/chunk","seq":19,"time":1784567324157,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":0,"text":"DONE"}}} -{"type":"assistant/chunk","seq":20,"time":1784567324158,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}}} -{"type":"assistant/chunk","seq":21,"time":1784567324158,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}}} -{"type":"assistant/chunk","seq":22,"time":1784567324158,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":23,"time":1784567324158,"data":{"turn":1,"step":2,"content":[{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":2}},"sourceEventSeqs":[18,19,20,21,22],"surfaceOp":"append"} -{"type":"step/end","seq":24,"time":1784567324158,"data":{"turn":1,"step":2}} -{"type":"turn/end","seq":25,"time":1784567324158,"data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"user/message","seq":1,"time":1784821266392,"data":{"content":[{"type":"text","text":"Use the write tool (NOT bash) to create session-root.txt in the current directory containing exactly: session root. Then reply with exactly the single word DONE."}],"source":{"kind":"user"}},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":1784821266392,"data":{"title":"Use the write tool (NOT","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":1784821266397,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":1784821266398,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"assistant/chunk","seq":5,"time":1784821266418,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":6,"time":1784821266418,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_session_root","name":"write","argumentsDelta":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}}} +{"type":"assistant/chunk","seq":7,"time":1784821266418,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_session_root","name":"write","arguments":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}}}} +{"type":"assistant/chunk","seq":8,"time":1784821266418,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":9,"time":1784567324143,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":10,"time":1784821266419,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"call_session_root","name":"write","arguments":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} +{"type":"tool/call","seq":11,"time":1784821266419,"data":{"turn":1,"step":1,"callId":"call_session_root","name":"write","arguments":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}} +{"type":"tool/result","seq":12,"time":1784821266431,"data":{"turn":1,"step":1,"callId":"call_session_root","content":[{"type":"text","text":"<path>/Users/cty/acp-snap-cwd-MABAjO/session-root.txt</path>\n<type>file</type>\n<content>\nCreated file\n</content>"}],"isError":false,"meta":{"diffs":[]}},"sourceEventSeqs":[11],"surfaceOp":"append"} +{"type":"step/end","seq":13,"time":1784821266436,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":14,"time":1784821266436,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":15,"time":1784821266442,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} +{"type":"assistant/chunk","seq":16,"time":1784821266442,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":0,"text":"DONE"}}} +{"type":"assistant/chunk","seq":17,"time":1784821266442,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}}} +{"type":"assistant/chunk","seq":18,"time":1784821266442,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}}} +{"type":"assistant/chunk","seq":19,"time":1784567324157,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":20,"time":1784821266442,"data":{"turn":1,"step":2,"content":[{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":2}},"sourceEventSeqs":[15,16,17,18,19],"surfaceOp":"append"} +{"type":"step/end","seq":21,"time":1784821266446,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":22,"time":1784821266446,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/session-sandbox-root/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/session-sandbox-root/stdout.expected.jsonl index 6ba40a0980..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/session-sandbox-root/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/session-sandbox-root/stdout.expected.jsonl @@ -1,9 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"workspace-write","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the write tool (NOT","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_session_root","title":"Write session-root.txt","kind":"edit","status":"in_progress","locations":[{"path":"session-root.txt"}],"content":[{"type":"diff","path":"session-root.txt","oldText":null,"newText":"session root"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_session_root","status":"completed","content":[{"type":"diff","path":"session-root.txt","oldText":null,"newText":"session root"}],"title":"Write session-root.txt"}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} -{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/skill-load/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/skill-load/stdout.expected.jsonl index 3f6f1dd3fe..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/skill-load/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/skill-load/stdout.expected.jsonl @@ -1,10 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Load the snapshot-skill skill with","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Load the requested skill."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_skill_load","title":"Load skill snapshot-skill","kind":"read","status":"in_progress","rawInput":"snapshot-skill"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_skill_load","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<skill_content name=\"snapshot-skill\">\n<skill_resources>\nBase directory for this skill: {{cwd}}/.dsh/skills/snapshot-skill\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n</skill_resources>\n\n<skill_instructions>\nFollow these snapshot-only instructions.\nResolve referenced resources relative to this skill directory.\n</skill_instructions>\n</skill_content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The skill is loaded."}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json index 02237f770b..dde0ba0d7a 100644 --- a/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json @@ -1,68 +1,5 @@ { "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, { "name": "bash", "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", @@ -170,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, { "name": "get_goal", "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", diff --git a/examples/acp-agent/tests/snapshots/subagent-depth-two-rejection/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/subagent-depth-two-rejection/stdout.expected.jsonl index 4e9be47961..c00054c284 100644 --- a/examples/acp-agent/tests/snapshots/subagent-depth-two-rejection/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/subagent-depth-two-rejection/stdout.expected.jsonl @@ -1,8 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Delegate through two child generations.","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_root_child","title":"subagent","kind":"other","status":"in_progress","rawInput":{"description":"Start depth one","prompt":"Call subagent once. Ask that child to attempt one further subagent call, then report the result."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_root_child","status":"completed","content":[{"type":"content","content":{"type":"text","text":"DEPTH_ONE_DONE"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ROOT_DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/subagent-fork/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/subagent-fork/stdout.expected.jsonl index 931b77892e..0350e89204 100644 --- a/examples/acp-agent/tests/snapshots/subagent-fork/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/subagent-fork/stdout.expected.jsonl @@ -1,120 +1,6 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Remember this fact for later:","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" remember"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cod"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ew"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ord"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"M"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ARM"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ADE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"OK"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_f"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ork"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" delegate"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" question"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" child"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" child"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" inher"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"its"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" conversation"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" be"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" able"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" answer"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" project"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cod"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ew"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ord"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" is"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" MAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"M"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ADE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" After"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returns"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_sAtKUseRzHRBvL4CF7XF1334","title":"subagent_fork","kind":"other","status":"in_progress","rawInput":{"description":"Recall project codeword","prompt":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_sAtKUseRzHRBvL4CF7XF1334","status":"completed","content":[{"type":"content","content":{"type":"text","text":"MARMALADE"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" for"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" child"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" correctly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"M"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ARM"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ADE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PARENT_DONE"}}}} {"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/subagent-mixed/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/subagent-mixed/stdout.expected.jsonl index 24eb9856a0..0350e89204 100644 --- a/examples/acp-agent/tests/snapshots/subagent-mixed/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/subagent-mixed/stdout.expected.jsonl @@ -1,171 +1,6 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Remember this fact for later:","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" remember"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cod"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ew"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ord"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"OK"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" do"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" these"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" two"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" deleg"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ations"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" one"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" at"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" time"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" requested"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"First"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'ll"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"fresh"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" child"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":")"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"P"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"HA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_YvHr2bGomk5HhpgDTvE81896","title":"subagent","kind":"other","status":"in_progress","rawInput":{"description":"Reply ALPHA only","prompt":"Reply with exactly the word ALPHA and nothing else."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_YvHr2bGomk5HhpgDTvE81896","status":"completed","content":[{"type":"content","content":{"type":"text","text":"ALPHA"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"P"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"HA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_f"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ork"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"fork"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" child"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" inher"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"its"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" conversation"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":")"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ask"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" about"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" project"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cod"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ew"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ord"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_JSr5rhREq23wSmwSkCP77184","title":"subagent_fork","kind":"other","status":"in_progress","rawInput":{"description":"Recall project codeword","prompt":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_JSr5rhREq23wSmwSkCP77184","status":"completed","content":[{"type":"content","content":{"type":"text","text":"SAFFRON"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Both"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agents"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" First"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"fresh"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" child"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"):"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"P"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"HA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Second"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"fork"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" child"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"):"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"SA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"FF"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"RON"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" -"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" correctly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" inherited"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" conversation"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" context"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" where"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" was"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" asked"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" remember"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cod"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ew"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ord"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"SA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"FF"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"RON"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instructed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PARENT_DONE"}}}} {"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/subagent-multi/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/subagent-multi/stdout.expected.jsonl index 9693ed051a..a460e019d4 100644 --- a/examples/acp-agent/tests/snapshots/subagent-multi/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/subagent-multi/stdout.expected.jsonl @@ -1,115 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the subagent tool TWICE,","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" twice"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sequentially"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"one"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" at"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" time"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":")."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" First"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"P"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"HA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" second"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"B"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ETA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" After"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" both"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" return"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_7zDCCjdsQgrk5LR2bAEQ1010","title":"subagent","kind":"other","status":"in_progress","rawInput":{"description":"Return ALPHA only","prompt":"Reply with exactly the word ALPHA and nothing else."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_7zDCCjdsQgrk5LR2bAEQ1010","status":"completed","content":[{"type":"content","content":{"type":"text","text":"ALPHA"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"First"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"P"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"HA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'ll"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" call"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" second"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" return"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"B"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ETA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_FudNKuJ0fchSptGy3Scw1411","title":"subagent","kind":"other","status":"in_progress","rawInput":{"description":"Return BETA only","prompt":"Reply with exactly the word BETA and nothing else."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_FudNKuJ0fchSptGy3Scw1411","status":"completed","content":[{"type":"content","content":{"type":"text","text":"BETA"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Both"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agents"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" have"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" first"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"AL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"P"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"HA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" second"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"B"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ETA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" should"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PARENT_DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/subagent-spawn/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/subagent-spawn/stdout.expected.jsonl index 37af99ca19..a460e019d4 100644 --- a/examples/acp-agent/tests/snapshots/subagent-spawn/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/subagent-spawn/stdout.expected.jsonl @@ -1,108 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the subagent tool exactly","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" once"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" delegate"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" task"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" CH"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ILD"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" nothing"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" else"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" After"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returns"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"3"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Do"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" do"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" this"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_gVbLWC12Qu8JheZpVRRz8749","title":"subagent","kind":"other","status":"in_progress","rawInput":{"description":"Reply with CHILD_OK","prompt":"Reply with exactly the word CHILD_OK and nothing else."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_gVbLWC12Qu8JheZpVRRz8749","status":"completed","content":[{"type":"content","content":{"type":"text","text":"CHILD_OK"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" sub"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"agent"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"CH"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ILD"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" expected"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PAR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ENT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PARENT_DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/text-turn/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/text-turn/stdout.expected.jsonl index 6bbcf7d91d..acfccdd778 100644 --- a/examples/acp-agent/tests/snapshots/text-turn/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/text-turn/stdout.expected.jsonl @@ -1,27 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Reply with exactly the word:","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"P"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONG"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" not"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" any"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tools"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"P"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONG"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PONG"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json index 02237f770b..dde0ba0d7a 100644 --- a/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json @@ -1,68 +1,5 @@ { "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, { "name": "bash", "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", @@ -170,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, { "name": "get_goal", "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", diff --git a/examples/acp-agent/tests/snapshots/todo-plan/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/todo-plan/stdout.expected.jsonl deleted file mode 100644 index d699c3de1c..0000000000 --- a/examples/acp-agent/tests/snapshots/todo-plan/stdout.expected.jsonl +++ /dev/null @@ -1,62 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the todo_write tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" todo"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_write"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" record"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" plan"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" three"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" todos"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" in"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" specified"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" status"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"es"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_fjAnBThbDjxepBtp3hDt3264","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"read the code","status":"in_progress"},{"content":"write the fix","status":"pending"},{"content":"run the tests","status":"pending"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"read the code","priority":"medium","status":"in_progress"},{"content":"write the fix","priority":"medium","status":"pending"},{"content":"run the tests","priority":"medium","status":"pending"}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_fjAnBThbDjxepBtp3hDt3264","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 2 pending, 1 in progress, 0 completed."}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" todos"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" have"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" been"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" written"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" successfully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" just"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/todo-plan/input.json b/examples/acp-agent/tests/snapshots/todo-write/input.json similarity index 100% rename from examples/acp-agent/tests/snapshots/todo-plan/input.json rename to examples/acp-agent/tests/snapshots/todo-write/input.json diff --git a/examples/acp-agent/tests/snapshots/todo-plan/session.jsonl b/examples/acp-agent/tests/snapshots/todo-write/session.jsonl similarity index 100% rename from examples/acp-agent/tests/snapshots/todo-plan/session.jsonl rename to examples/acp-agent/tests/snapshots/todo-write/session.jsonl diff --git a/examples/acp-agent/tests/snapshots/todo-write/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/todo-write/stdout.expected.jsonl new file mode 100644 index 0000000000..82ae8907ca --- /dev/null +++ b/examples/acp-agent/tests/snapshots/todo-write/stdout.expected.jsonl @@ -0,0 +1,4 @@ +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/tool-call-turn/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/tool-call-turn/stdout.expected.jsonl index a72dbc43ed..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/tool-call-turn/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/tool-call-turn/stdout.expected.jsonl @@ -1,51 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the bash tool to","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" run"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" specific"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" bash"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_Rn2Mz1y8uZN62ukEXiNO2077","title":"echo SNAPSHOT_OK","kind":"execute","status":"in_progress","rawInput":"echo SNAPSHOT_OK","content":[{"type":"content","content":{"type":"text","text":"Run echo SNAPSHOT_OK"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_Rn2Mz1y8uZN62ukEXiNO2077","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nSNAPSHOT_OK\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" command"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" executed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" successfully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" printed"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" S"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"NA"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"PS"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"H"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"OT"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" single"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/workflow-run/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/workflow-run/stdout.expected.jsonl index aa0cac2140..bdf91164ff 100644 --- a/examples/acp-agent/tests/snapshots/workflow-run/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/workflow-run/stdout.expected.jsonl @@ -1,130 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Use the workflow tool exactly","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" use"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" workflow"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" tool"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" once"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" specific"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" parameters"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" carefully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" follow"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" instructions"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" args"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" omitted"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ("}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"so"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" don"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"'t"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" include"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":")\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" meta"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ="}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" {"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"name"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"sn"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"apshot"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"-flow"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"description"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\":"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"one"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" child"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" for"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" snapshot"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" }\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"3"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" script"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" ="}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" given"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" verb"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"atim"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"4"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" After"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returns"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WORK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"FL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"OW"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" do"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" that"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_dD2BLuNeJCTh2iiYC1QR3449","title":"workflow: snapshot-flow","kind":"other","status":"in_progress","rawInput":"\nphase('Run')\nconst reply = await agent('Reply with exactly the word WF_CHILD_OK and nothing else.')\nreturn { reply }\n"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_dD2BLuNeJCTh2iiYC1QR3449","status":"completed","content":[{"type":"content","content":{"type":"text","text":"workflow \"snapshot-flow\" completed (1 agent).\nReturn value:\n{\n \"reply\": \"WF_CHILD_OK\"\n}"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" workflow"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" returned"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" successfully"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WF"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_CH"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ILD"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_OK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" exactly"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WORK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"FL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"OW"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" and"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" stop"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"WORK"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"FL"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"OW"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"_D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"WORKFLOW_DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/workspace-context/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/workspace-context/stdout.expected.jsonl index b19fa5bbac..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/workspace-context/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/workspace-context/stdout.expected.jsonl @@ -1,8 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Read nested/task.txt with the read","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_workspace_read","title":"Read nested/task.txt","kind":"read","status":"in_progress","locations":[{"path":"nested/task.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_workspace_read","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/nested/task.txt</path>\n<type>file</type>\n<content>\n1: snapshot task\n\n(End of file - total 1 lines)\n</content>"}}]}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json index 02237f770b..dde0ba0d7a 100644 --- a/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json @@ -1,68 +1,5 @@ { "initial": [ - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, { "name": "bash", "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", @@ -170,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, { "name": "get_goal", "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", diff --git a/examples/acp-agent/tests/snapshots/workspace-edit/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/workspace-edit/stdout.expected.jsonl index 1b2c49322e..82ae8907ca 100644 --- a/examples/acp-agent/tests/snapshots/workspace-edit/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/workspace-edit/stdout.expected.jsonl @@ -1,134 +1,4 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"A file named greeting.txt in","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" greeting"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Append"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" WORLD"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" second"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"3"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cat"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" confirm"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"4"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" start"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" see"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" its"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" contents"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_OjRFB4zvxu6UALDjytZD0978","title":"Read greeting.txt","kind":"read","status":"in_progress","locations":[{"path":"greeting.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_OjRFB4zvxu6UALDjytZD0978","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}/greeting.txt</path>\n<type>file</type>\n<content>\n1: hello\n\n(End of file - total 1 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" contains"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" on"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" one"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" append"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" second"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WOR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LD"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cat"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" confirm"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_IUUvbNiPcnwhVL8ErEFS4806","title":"printf '\\nWORLD' >> greeting.txt","kind":"execute","status":"in_progress","rawInput":"printf '\\nWORLD' >> greeting.txt","content":[{"type":"content","content":{"type":"text","text":"Append newline and WORLD to greeting.txt"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_IUUvbNiPcnwhVL8ErEFS4806","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\n(no output)\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Good"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cat"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_Wo4H7tFNheZJWKVDrAHK5851","title":"cat greeting.txt","kind":"execute","status":"in_progress","rawInput":"cat greeting.txt","content":[{"type":"content","content":{"type":"text","text":"Read greeting.txt to confirm"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_Wo4H7tFNheZJWKVDrAHK5851","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nhello\n\nWORLD\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" has"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" two"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" lines"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" WORLD"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" can"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/workspace-edit/stdout.expected.windows.jsonl b/examples/acp-agent/tests/snapshots/workspace-edit/stdout.expected.windows.jsonl deleted file mode 100644 index 97f673b81f..0000000000 --- a/examples/acp-agent/tests/snapshots/workspace-edit/stdout.expected.windows.jsonl +++ /dev/null @@ -1,134 +0,0 @@ -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"A file named greeting.txt in","updatedAt":"{{updatedAt}}"}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" user"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" wants"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" greeting"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":".txt"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Append"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" word"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" WORLD"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" as"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" second"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"3"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cat"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" confirm"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"4"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" start"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" by"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reading"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" see"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" its"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" contents"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_OjRFB4zvxu6UALDjytZD0978","title":"Read greeting.txt","kind":"read","status":"in_progress","locations":[{"path":"greeting.txt","line":1}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_OjRFB4zvxu6UALDjytZD0978","status":"completed","content":[{"type":"content","content":{"type":"text","text":"<path>{{cwd}}\\greeting.txt</path>\n<type>file</type>\n<content>\n1: hello\n\n(End of file - total 1 lines)\n</content>"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" contains"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" on"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" one"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" need"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" append"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" a"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" second"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" line"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" \""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"WOR"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"LD"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\""}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" Then"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cat"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" it"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" to"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" confirm"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_IUUvbNiPcnwhVL8ErEFS4806","title":"printf '\\nWORLD' >> greeting.txt","kind":"execute","status":"in_progress","rawInput":"printf '\\nWORLD' >> greeting.txt","content":[{"type":"content","content":{"type":"text","text":"Append newline and WORLD to greeting.txt"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_IUUvbNiPcnwhVL8ErEFS4806","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\n(no output)\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Good"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":","}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" let"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" me"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" read"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" the"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" back"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" cat"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_Wo4H7tFNheZJWKVDrAHK5851","title":"cat greeting.txt","kind":"execute","status":"in_progress","rawInput":"cat greeting.txt","content":[{"type":"content","content":{"type":"text","text":"Read greeting.txt to confirm"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_Wo4H7tFNheZJWKVDrAHK5851","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nhello\n\nWORLD\n```"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" file"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" now"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" has"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" two"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" lines"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":":\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"1"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" hello"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"2"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" WORLD"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"\n\n"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"I"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" can"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" reply"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" with"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":" D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"."}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"D"}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ONE"}}}} -{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/headless-agent/semantic-checkpoint.cordis.snapshot.yml b/examples/headless-agent/semantic-checkpoint.cordis.snapshot.yml new file mode 100644 index 0000000000..fc7959e25d --- /dev/null +++ b/examples/headless-agent/semantic-checkpoint.cordis.snapshot.yml @@ -0,0 +1,37 @@ +# Keyless real-Loader composition for the semantic-checkpoint recovery snapshot. +# The headless driver resumes the seeded interrupted session and emits its next +# turn over stream-json; the replay adapter supplies the deterministic response. + +- id: persistence + name: '@deepseek-ai/dsh-session-persistence-jsonl' + config: + root: './.sessions' + compression: none + +- id: checkpoint + name: '@deepseek-ai/dsh-session-checkpoint-policy' + +- id: replay + name: '@deepseek-ai/dsh-llm-replay' + config: + file: !!js process.env.DSH_SNAPSHOT_FILE + overrideFile: !!js process.env.DSH_SNAPSHOT_OVERRIDE + +- id: bash + name: '@deepseek-ai/dsh-bash-local' + config: + timeoutMs: 60000 + +- id: agent + name: '@deepseek-ai/dsh-agent-spine-demo' + config: + agents: [] + workspaceContext: false + skills: + enabled: false + toolTasks: false + goals: false + +# Await the persisted resume before the headless driver inspects root agents. +- id: resumed-agent + name: './tests/fixtures/semantic-checkpoint-agent.ts' diff --git a/examples/headless-agent/tests/fixtures/semantic-checkpoint-agent.ts b/examples/headless-agent/tests/fixtures/semantic-checkpoint-agent.ts new file mode 100644 index 0000000000..58a1bedee9 --- /dev/null +++ b/examples/headless-agent/tests/fixtures/semantic-checkpoint-agent.ts @@ -0,0 +1,25 @@ +/** + * Loader fixture that publishes the semantic-checkpoint session before CLI dispatch. + * @module semantic-checkpoint-agent + */ + +import type { Context } from 'cordis' +import type { SessionId } from '@deepseek-ai/dsh-session' + +/** Fixture plugin name. */ +export const name = 'semantic-checkpoint-agent' +/** Services that must exist before the fixture resumes its agent. */ +export const inject = ['agents', 'agentLoop', 'sessionPersistence'] + +/** + * Resume the seeded session and bind its exact handle to this fixture's lifetime. + * @param ctx - settled agent and persistence services from the Loader tree. + * @returns after the resumed agent is published. + */ +export async function apply(ctx: Context): Promise<void> { + const handle = await ctx.agents.resume({ + resumeSessionId: 'semantic-checkpoint-unknown-outcome' as SessionId, + agentOptions: { provider: 'deepseek', model: 'deepseek-v4-flash' }, + }) + ctx.effect(() => () => handle.dispose(), 'semantic-checkpoint-agent.handle') +} diff --git a/examples/acp-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/replay.jsonl b/examples/headless-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/replay.jsonl similarity index 100% rename from examples/acp-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/replay.jsonl rename to examples/headless-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/replay.jsonl diff --git a/examples/acp-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/replay.override.json b/examples/headless-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/replay.override.json similarity index 100% rename from examples/acp-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/replay.override.json rename to examples/headless-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/replay.override.json diff --git a/examples/acp-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/session.expected.jsonl b/examples/headless-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/session.expected.jsonl similarity index 100% rename from examples/acp-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/session.expected.jsonl rename to examples/headless-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/session.expected.jsonl diff --git a/examples/headless-agent/tests/semantic-checkpoint.snapshot.ts b/examples/headless-agent/tests/semantic-checkpoint.snapshot.ts new file mode 100644 index 0000000000..519541117d --- /dev/null +++ b/examples/headless-agent/tests/semantic-checkpoint.snapshot.ts @@ -0,0 +1,113 @@ +import { readFile, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { Context } from 'cordis' +import { normalizeSessionLog, scrubRequestHeaders, type NormalizeContext } from '@deepseek-ai/dsh-acp-snapshot' +import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' +import { CallId } from '@deepseek-ai/dsh-llm' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session' +import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' +import { describe, expect, it } from 'vitest' + +const fixtureDir = join(dirname(fileURLToPath(import.meta.url)), 'semantic-checkpoint-snapshots/tool-outcome-unknown') +const replayFixture = join(fixtureDir, 'replay.jsonl') +const replayOverride = join(fixtureDir, 'replay.override.json') +const sessionExpected = join(fixtureDir, 'session.expected.jsonl') +const configPath = fileURLToPath(new URL('../semantic-checkpoint.cordis.snapshot.yml', import.meta.url)) +const binScript = fileURLToPath(new URL('../../../packages/examples/cli-demo/src/bin.ts', import.meta.url)) +const tsconfigPath = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)) +const sessionId = SessionId('semantic-checkpoint-unknown-outcome') +const refreshing = process.env.DSH_SNAPSHOT === 'refresh' +const task = 'Continue safely from the interrupted operation.' + +async function seedInterruptedSession(root: string, cwd: string): Promise<string> { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionPersistenceJsonl, { root, compression: 'none' }) + const meta: SessionHeader = { + version: SESSION_FORMAT_VERSION, + id: sessionId, + createdAt: 1, + cwd, + delegationDepth: 0, + } + const events: SessionEvent[] = [ + { type: 'turn/start', seq: 0, time: 10, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }, + { type: 'user/message', seq: 1, time: 11, data: { content: [{ type: 'text', text: 'Perform one side-effecting remote mutation.' }], source: { kind: 'user' } }, surfaceOp: 'append' }, + { type: 'step/start', seq: 2, time: 12, data: { turn: 1, step: 1 } }, + { + type: 'assistant/message', + seq: 3, + time: 13, + data: { + turn: 1, + step: 1, + content: [{ type: 'tool-call', id: CallId('unknown-outcome-call'), name: 'write_remote', arguments: '{"value":1}' }], + provenance: { provider: 'deepseek', model: 'deepseek-v4-flash' }, + }, + surfaceOp: 'append', + }, + { + type: 'tool/call', + seq: 4, + time: 14, + data: { + turn: 1, + step: 1, + callId: CallId('unknown-outcome-call'), + name: 'write_remote', + arguments: '{"value":1}', + }, + }, + ] + try { + await ctx.sessionPersistence.create(meta) + await ctx.sessionPersistence.append(sessionId, events) + const location = ctx.sessionPersistence.locate(meta) + if (location === undefined) throw new Error('JSONL backend did not locate the seeded session') + return location.path + } finally { + await ctx.fiber.dispose() + } +} + +describe('semantic checkpoint recovery snapshot', () => { + it('resumes an unknown tool outcome through the headless stream-json app', async () => { + let cwd = '' + let sessionPath = '' + const result = await runLoaderSmoke({ + label: 'semantic checkpoint headless stream-json snapshot', + tempDirPrefix: 'dsh-semantic-snapshot-', + binScript, + configPath, + binArgs: ['--config', configPath, '--output-format', 'stream-json', task], + tsconfigPath, + env: { + DSH_SNAPSHOT_FILE: replayFixture, + DSH_SNAPSHOT_OVERRIDE: replayOverride, + }, + prepare: async (runCwd) => { + cwd = runCwd + sessionPath = await seedInterruptedSession(join(runCwd, '.sessions'), runCwd) + }, + inspect: async () => { + const normalization: NormalizeContext = { sessionIds: [sessionId], cwd } + const session = scrubRequestHeaders(normalizeSessionLog(await readFile(sessionPath, 'utf8'), normalization)) + if (refreshing) await writeFile(sessionExpected, session) + expect(session).toBe(await readFile(sessionExpected, 'utf8')) + expect(session).toContain('TOOL_OUTCOME_UNKNOWN') + expect(session).toContain('Do not retry blindly.') + }, + }) + + expect(result.stderr).toBe('') + const records = result.stdout.trimEnd().split('\n').map(line => JSON.parse(line) as Record<string, unknown>) + expect(records.at(-1)).toMatchObject({ + type: 'result', + success: true, + sessionId, + result: 'I will verify the external state before deciding whether to retry the side-effecting operation.', + reason: { kind: 'completed' }, + }) + }, LOADER_SMOKE_TEST_TIMEOUT_MS) +}) diff --git a/examples/headless-agent/tests/snapshots/pty-tools/session.jsonl b/examples/headless-agent/tests/snapshots/pty-tools/session.jsonl index d91782e1e2..99eaf6e4ee 100644 --- a/examples/headless-agent/tests/snapshots/pty-tools/session.jsonl +++ b/examples/headless-agent/tests/snapshots/pty-tools/session.jsonl @@ -3,7 +3,7 @@ {"type":"user/message","seq":1,"time":0,"data":{"content":[{"type":"text","text":"Exercise the six PTY tools in order, including one missing-session signal error, then reply DONE."}],"source":{"kind":"user"}},"surfaceOp":"append"} {"type":"session/title","seq":2,"time":0,"data":{"title":"Exercise the six PTY tools","messageSeqs":[1],"source":{"kind":"fallback"}}} {"type":"step/start","seq":3,"time":0,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":4,"time":0,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou are headless-agent, a coding assistant powered by the deepseek-v4-flash model.\n\nVerify your work by running the code or tests. Keep answers brief and\nfactual.\n\n\nUse the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files.\n\nUse the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes.\n\nUse the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session.\n\nCheck the [exit code: N] marker on every bash result; investigate failures before moving on.\n\nUse a terminal session only when work needs persistent terminal state or interactive stdin; prefer bash/read/write/edit for bounded one-shot operations. Track every terminal session id and close sessions that no longer matter. An inferred_idle or timeout result does not prove the foreground command exited.\n\nTrack every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering.\n\nUse the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.\n\nUse the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.","tools":[{"name":"bash","description":"Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`.","parameters":{"type":"object","properties":{"command":{"type":"string","description":"The bash command to execute."},"description":{"type":"string","description":"Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"."},"timeoutMs":{"type":"number","description":"Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry."},"workdir":{"type":"string","description":"Working directory for this command. Defaults to the session workspace; a relative path is resolved against it."},"run_in_background":{"type":"boolean","description":"Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies."}},"required":["command","description"]}},{"name":"edit","description":"Edit an existing UTF-8 text file by replacing literal text.","parameters":{"type":"object","properties":{"file_path":{"type":"string","description":"Path to edit, resolved by the filesystem backend."},"old_string":{"type":"string","description":"Literal text to replace. Must match exactly."},"new_string":{"type":"string","description":"Literal replacement text. Use an empty string to delete the match."},"replace_all":{"type":"boolean","description":"Replace all matches. Defaults to false; when false, old_string must appear exactly once."}},"required":["file_path","old_string","new_string"]}},{"name":"ralph","description":"Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.","parameters":{"type":"object","properties":{"objective":{"type":"string","description":"The immutable completion objective for every fresh Ralph round."},"maxRounds":{"type":"number","description":"Optional positive safe-integer round cap, bounded by the deployment ceiling."}},"required":["objective"]}},{"name":"read","description":"Read a UTF-8 text file and return line-numbered content.","parameters":{"type":"object","properties":{"file_path":{"type":"string","description":"Path to read, resolved by the filesystem backend."},"offset":{"type":"number","description":"1-based first line to return. Defaults to 1."},"limit":{"type":"number","description":"Maximum number of lines to return. Defaults to 2000."}},"required":["file_path"]}},{"name":"skill","description":"Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.","parameters":{"type":"object","properties":{"name":{"type":"string","description":"The exact skill name from the available skills list."}},"required":["name"]}},{"name":"subagent","description":"Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.","parameters":{"type":"object","properties":{"description":{"type":"string","description":"A short (3-5 word) description of the delegated task, for display."},"prompt":{"type":"string","description":"The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs."},"run_in_background":{"type":"boolean","description":"Run as a background task and return its id; collect with task_output or stop with task_kill."}},"required":["description","prompt"]}},{"name":"subagent_fork","description":"Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.","parameters":{"type":"object","properties":{"description":{"type":"string","description":"A short (3-5 word) description of the delegated task, for display."},"prompt":{"type":"string","description":"The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new."},"run_in_background":{"type":"boolean","description":"Run as a background task and return its id; collect with task_output or stop with task_kill."}},"required":["description","prompt"]}},{"name":"task_kill","description":"Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.","parameters":{"type":"object","properties":{"task_id":{"type":"string","description":"Task id returned by the tool that started the background work."},"reason":{"type":"string","description":"Optional short reason, recorded in the log and forwarded to the task."}},"required":["task_id"]}},{"name":"task_list","description":"List your background tasks (running and finished) with their ids, kinds, and statuses.","parameters":{"type":"object","properties":{}}},{"name":"task_output","description":"Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.","parameters":{"type":"object","properties":{"task_id":{"type":"string","description":"Task id returned by the tool that started the background work."},"wait":{"type":"boolean","description":"Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive."},"timeout_ms":{"type":"number","description":"Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum."}},"required":["task_id"]}},{"name":"terminal_close","description":"Close one persistent terminal and wait until its captured owned process tree is gone.","parameters":{"type":"object","properties":{"sessionId":{"type":"string","description":"Terminal session id."}},"required":["sessionId"]}},{"name":"terminal_list","description":"List persistent terminal sessions owned by the current agent.","parameters":{"type":"object","properties":{}}},{"name":"terminal_open","description":"Create a persistent, owner-isolated terminal session from a registered backend type. Use this for shell or REPL state that must survive across tool calls.","parameters":{"type":"object","properties":{"type":{"type":"string","description":"Registered terminal backend type, usually \"shell\"."},"name":{"type":"string","description":"Optional owner-local display name such as \"main\" or \"gdb\"."},"cwd":{"type":"string","description":"Initial working directory. Defaults to the deployment workspace root."}},"required":["type"]}},{"name":"terminal_read","description":"Read a bounded page of retained output from a persistent terminal without sending input.","parameters":{"type":"object","properties":{"sessionId":{"type":"string","description":"Terminal session id."},"offset":{"type":"number","description":"Newest-relative line offset (default 0)."},"count":{"type":"number","description":"Requested line count (default 500; backend caps apply)."}},"required":["sessionId"]}},{"name":"terminal_send","description":"Send text to a persistent terminal. By default Enter is submitted and the call waits for a prompt, stdin wait, output silence, timeout, or session exit. Background mode returns a task id for task_output/task_kill.","parameters":{"type":"object","properties":{"sessionId":{"type":"string","description":"Terminal session id returned by terminal_open or terminal_list."},"text":{"type":"string","description":"UTF-8 text to write to the terminal."},"submit":{"type":"boolean","description":"Submit Enter after text (default true). Set false for control characters or incomplete REPL input."},"run_in_background":{"type":"boolean","description":"Return a task id immediately; collect with task_output or stop with task_kill."}},"required":["sessionId","text"]}},{"name":"terminal_signal","description":"Send an allowed signal to the current foreground process group of a persistent terminal.","parameters":{"type":"object","properties":{"sessionId":{"type":"string","description":"Terminal session id."},"signal":{"type":"string","description":"Signal to deliver. Shell-targeted SIGKILL is rejected; use terminal_close.","enum":["SIGINT","SIGTERM","SIGKILL","SIGTSTP","SIGHUP"]}},"required":["sessionId","signal"]}},{"name":"todo_write","description":"Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).","parameters":{"type":"object","properties":{"todos":{"type":"array","description":"The COMPLETE task list, replacing any previous list.","items":{"type":"object","properties":{"content":{"type":"string","description":"What the task is — a short imperative line."},"status":{"type":"string","description":"pending (not started) | in_progress (now) | completed (done).","enum":["pending","in_progress","completed"]}},"required":["content","status"]}}},"required":["todos"]}},{"name":"workflow","description":"Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return <value>` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const — no oneOf/pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.","parameters":{"type":"object","properties":{"script":{"type":"string","description":"The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)."},"meta":{"type":"object","description":"The workflow identity block (plain JSON — never code).","properties":{"name":{"type":"string","description":"Short kebab-case workflow name."},"description":{"type":"string","description":"One-line description of what the workflow does."},"whenToUse":{"type":"string","description":"Optional guidance on when this workflow applies."},"phases":{"type":"array","description":"Optional phase declarations matched by phase() calls.","items":{"type":"object","properties":{"title":{"type":"string","description":"The phase title phase() calls match by exact string."},"detail":{"type":"string","description":"Optional one-line description of the phase."},"provider":{"type":"string","description":"Optional provider override this phase is expected to use."},"model":{"type":"string","description":"Optional model override this phase is expected to use."}},"required":["title"]}}},"required":["name","description"]},"args":{"type":"object","description":"Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]})."}},"required":["script","meta"]}},{"name":"write","description":"Create or fully replace a UTF-8 text file.","parameters":{"type":"object","properties":{"file_path":{"type":"string","description":"Path to write, resolved by the filesystem backend."},"content":{"type":"string","description":"Full UTF-8 text content to write."}},"required":["file_path","content"]}}]},"reason":"initial"}} +{"type":"request/header","seq":4,"time":0,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou are headless-agent, a coding assistant powered by the deepseek-v4-flash model.\n\nVerify your work by running the code or tests. Keep answers brief and\nfactual.\n\n\nUse the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files.\n\nUse the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes.\n\nUse the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session.\n\nCheck the [exit code: N] marker on every bash result; investigate failures before moving on.\n\nUse a terminal session only when work needs persistent terminal state or interactive stdin; prefer bash/read/write/edit for bounded one-shot operations. Track every terminal session id and close sessions that no longer matter. An inferred_idle or timeout result does not prove the foreground command exited.\n\nTrack every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering.\n\nUse the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.\n\nUse the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.","tools":[{"name":"bash","description":"Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`.","parameters":{"type":"object","properties":{"command":{"type":"string","description":"The bash command to execute."},"description":{"type":"string","description":"Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"."},"timeoutMs":{"type":"number","description":"Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry."},"workdir":{"type":"string","description":"Working directory for this command. Defaults to the session workspace; a relative path is resolved against it."},"run_in_background":{"type":"boolean","description":"Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies."}},"required":["command","description"]}},{"name":"edit","description":"Edit an existing UTF-8 text file by replacing literal text.","parameters":{"type":"object","properties":{"file_path":{"type":"string","description":"Path to edit, resolved by the filesystem backend."},"old_string":{"type":"string","description":"Literal text to replace. Must match exactly."},"new_string":{"type":"string","description":"Literal replacement text. Use an empty string to delete the match."},"replace_all":{"type":"boolean","description":"Replace all matches. Defaults to false; when false, old_string must appear exactly once."}},"required":["file_path","old_string","new_string"]}},{"name":"ralph","description":"Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.","parameters":{"type":"object","properties":{"objective":{"type":"string","description":"The immutable completion objective for every fresh Ralph round."},"maxRounds":{"type":"number","description":"Optional positive safe-integer round cap, bounded by the deployment ceiling."}},"required":["objective"]}},{"name":"read","description":"Read a UTF-8 text file and return line-numbered content.","parameters":{"type":"object","properties":{"file_path":{"type":"string","description":"Path to read, resolved by the filesystem backend."},"offset":{"type":"number","description":"1-based first line to return. Defaults to 1."},"limit":{"type":"number","description":"Maximum number of lines to return. Defaults to 2000."}},"required":["file_path"]}},{"name":"skill","description":"Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.","parameters":{"type":"object","properties":{"name":{"type":"string","description":"The exact skill name from the available skills list."}},"required":["name"]}},{"name":"subagent","description":"Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.","parameters":{"type":"object","properties":{"description":{"type":"string","description":"A short (3-5 word) description of the delegated task, for display."},"prompt":{"type":"string","description":"The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs."},"run_in_background":{"type":"boolean","description":"Run as a background task and return its id; collect with task_output or stop with task_kill."}},"required":["description","prompt"]}},{"name":"subagent_fork","description":"Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.","parameters":{"type":"object","properties":{"description":{"type":"string","description":"A short (3-5 word) description of the delegated task, for display."},"prompt":{"type":"string","description":"The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new."},"run_in_background":{"type":"boolean","description":"Run as a background task and return its id; collect with task_output or stop with task_kill."}},"required":["description","prompt"]}},{"name":"task_kill","description":"Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.","parameters":{"type":"object","properties":{"task_id":{"type":"string","description":"Task id returned by the tool that started the background work."},"reason":{"type":"string","description":"Optional short reason, recorded in the log and forwarded to the task."}},"required":["task_id"]}},{"name":"task_list","description":"List your background tasks (running and finished) with their ids, kinds, and statuses.","parameters":{"type":"object","properties":{}}},{"name":"task_output","description":"Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.","parameters":{"type":"object","properties":{"task_id":{"type":"string","description":"Task id returned by the tool that started the background work."},"wait":{"type":"boolean","description":"Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive."},"timeout_ms":{"type":"number","description":"Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum."}},"required":["task_id"]}},{"name":"terminal_close","description":"Close one persistent terminal and wait until its captured owned process tree is gone.","parameters":{"type":"object","properties":{"sessionId":{"type":"string","description":"Terminal session id."}},"required":["sessionId"]}},{"name":"terminal_list","description":"List persistent terminal sessions owned by the current agent.","parameters":{"type":"object","properties":{}}},{"name":"terminal_open","description":"Create a persistent, owner-isolated terminal session from a registered backend type. Use this for shell or REPL state that must survive across tool calls.","parameters":{"type":"object","properties":{"type":{"type":"string","description":"Registered terminal backend type, usually \"shell\"."},"name":{"type":"string","description":"Optional owner-local display name such as \"main\" or \"gdb\"."},"cwd":{"type":"string","description":"Initial working directory. Defaults to the deployment workspace root."}},"required":["type"]}},{"name":"terminal_read","description":"Read a bounded page of retained output from a persistent terminal without sending input.","parameters":{"type":"object","properties":{"sessionId":{"type":"string","description":"Terminal session id."},"offset":{"type":"number","description":"Newest-relative line offset (default 0)."},"count":{"type":"number","description":"Requested line count (default 500; backend caps apply)."}},"required":["sessionId"]}},{"name":"terminal_send","description":"Send text to a persistent terminal. By default Enter is submitted and the call waits for a prompt, stdin wait, output silence, timeout, or session exit. Background mode returns a task id for task_output/task_kill.","parameters":{"type":"object","properties":{"sessionId":{"type":"string","description":"Terminal session id returned by terminal_open or terminal_list."},"text":{"type":"string","description":"UTF-8 text to write to the terminal."},"submit":{"type":"boolean","description":"Submit Enter after text (default true). Set false for control characters or incomplete REPL input."},"run_in_background":{"type":"boolean","description":"Return a task id immediately; collect with task_output or stop with task_kill."}},"required":["sessionId","text"]}},{"name":"terminal_signal","description":"Send an allowed signal to the current foreground process group of a persistent terminal.","parameters":{"type":"object","properties":{"sessionId":{"type":"string","description":"Terminal session id."},"signal":{"type":"string","description":"Signal to deliver. Shell-targeted SIGKILL is rejected; use terminal_close.","enum":["SIGINT","SIGTERM","SIGKILL","SIGTSTP","SIGHUP"]}},"required":["sessionId","signal"]}},{"name":"todo_write","description":"Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).","parameters":{"type":"object","properties":{"todos":{"type":"array","description":"The COMPLETE task list, replacing any previous list.","items":{"type":"object","additionalProperties":true,"properties":{"content":{"type":"string","description":"What the task is — a short imperative line."},"status":{"type":"string","description":"pending (not started) | in_progress (now) | completed (done).","enum":["pending","in_progress","completed"]}},"required":["content","status"]}}},"required":["todos"]}},{"name":"workflow","description":"Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return <value>` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.","parameters":{"type":"object","properties":{"script":{"type":"string","description":"The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)."},"meta":{"type":"object","description":"The workflow identity block (plain JSON — never code).","additionalProperties":true,"properties":{"name":{"type":"string","description":"Short kebab-case workflow name."},"description":{"type":"string","description":"One-line description of what the workflow does."},"whenToUse":{"type":"string","description":"Optional guidance on when this workflow applies."},"phases":{"type":"array","description":"Optional phase declarations matched by phase() calls.","items":{"type":"object","additionalProperties":true,"properties":{"title":{"type":"string","description":"The phase title phase() calls match by exact string."},"detail":{"type":"string","description":"Optional one-line description of the phase."},"provider":{"type":"string","description":"Optional provider override this phase is expected to use."},"model":{"type":"string","description":"Optional model override this phase is expected to use."}},"required":["title"]}}},"required":["name","description"]},"args":{"type":"object","description":"Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).","additionalProperties":true}},"required":["script","meta"]}},{"name":"write","description":"Create or fully replace a UTF-8 text file.","parameters":{"type":"object","properties":{"file_path":{"type":"string","description":"Path to write, resolved by the filesystem backend."},"content":{"type":"string","description":"Full UTF-8 text content to write."}},"required":["file_path","content"]}}]},"reason":"initial"}} {"type":"assistant/chunk","seq":5,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","seq":6,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"pty-spawn","name":"terminal_open","argumentsDelta":"{\"type\":\"shell\",\"name\":\"main\"}"}}} {"type":"assistant/chunk","seq":7,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"pty-spawn","name":"terminal_open","arguments":"{\"type\":\"shell\",\"name\":\"main\"}"}}}} diff --git a/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts b/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts index efbe11099f..43ac327d8b 100644 --- a/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts +++ b/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts @@ -1,4 +1,5 @@ -import { mkdir, readdir, readFile, realpath, writeFile } from 'node:fs/promises' +import { realpathSync } from 'node:fs' +import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -48,7 +49,7 @@ function seedWorkspace( /** Seed one real plaintext JSONL session for the `/resume` selector and host handoff smoke. */ async function seedResumeSession(cwd: string): Promise<void> { - const sessionCwd = await realpath(cwd) + const sessionCwd = realpathSync.native(cwd) const id = SessionId('resume-target') const meta: SessionHeader = { version: 0, id, createdAt: 1_700_000_000_000, cwd: sessionCwd } const events: SessionEvent[] = [ diff --git a/knip.json b/knip.json index 59658e1df6..b6a1fb63d7 100644 --- a/knip.json +++ b/knip.json @@ -28,6 +28,7 @@ "examples": { "entry": [ "headless-agent/tests/fixtures/cli-mock-llm.ts", + "headless-agent/tests/fixtures/semantic-checkpoint-agent.ts", "headless-agent/tests/fixtures/goal-domain/seed-goal.ts", "headless-agent/tests/fixtures/time-context-driver.ts", "headless-agent/tests/fixtures/time-context-mock-llm.ts", @@ -56,12 +57,8 @@ ] }, "packages/host/webserver": { - "entry": [ - "tests/**/*.spec.ts" - ], "project": [ - "src/**/*.ts", - "tests/**/*.ts" + "src/**/*.ts" ] }, "packages/host/runtime": { @@ -579,7 +576,8 @@ "src/**/*.ts" ], "ignoreDependencies": [ - "@deepseek-ai/dsh-client-.+" + "@deepseek-ai/.+", + "@cordisjs/.+" ] }, "packages/client/modules": { diff --git a/missions/tasks/20260724-storage-workspace/dev-plan.md b/missions/tasks/20260724-storage-workspace/dev-plan.md new file mode 100644 index 0000000000..da621897ba --- /dev/null +++ b/missions/tasks/20260724-storage-workspace/dev-plan.md @@ -0,0 +1,179 @@ +# Storage + Workspace 工程开发文档 + +> 施工范围:5 个新包,session 侧零 diff。规范正典:[Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md)——本文只写工程拆解(目录/文件、class 落位、teammate 分工、并行依赖),接口语义以 Note 为准,冲突时改这里不改 Note(除非经用户拍板)。 +> 门禁口径:GUI 免门禁期同款——不随手写测试门禁,跑 typecheck/build 保证编译;测试文件按仓库惯例落位(包级 `tests/`、`.spec.ts`),红绿在 PR 窗口收口。 + +## 0. 总览 + +``` +packages/storage/ + storage/ dsh-storage 枢纽:Storage service + BackendRegistry + StorageForms + storage-json/ dsh-storage-json JsonStorageBackend(kv facet) + storage-sqlite/ dsh-storage-sqlite SqliteStorageBackend(kv facet) + storage-domain/ dsh-storage-domain DomainFacility + Domain + KvTable + domain/changed +packages/workspace/ + workspace/ dsh-workspace WorkspaceRegistry + WorkspaceEntity + workspaceDomainSpec +``` + +依赖与并行关系(→ = 依赖): + +``` +W1 storage(枢纽) ──→ W2a storage-json ──┐ + └──→ W2b storage-sqlite ─┼──→ 集成冒烟(W4 兼) + └──→ W3 domain ──────────┘ + └──→ W4 workspace +``` + +- W1 先行(接口包是所有人的编译依赖),完成后 W2a/W2b/W3 **三线并行**;W4 依赖 W3 的接口定型(不必等 json/sqlite 完工,可对着 W3 的类型先写,用内存假 backend 跑测试)。 +- 每包的 package.json/tsconfig/README/invariant 伴生由该包 owner 自己配齐(模板照抄 `packages/session-persistence/session-persistence-sqlite/` 的形状)。 + +## 1. W1:`dsh-storage`(枢纽)——主线程自做 + +量小且是全组编译根,主线程直接写,不派 teammate。 + +``` +packages/storage/storage/ + package.json # 无运行时依赖;cordis peerDep + dev + tsconfig.json + src/index.ts # Storage service + apply + 全部导出 + src/registry.ts # BackendRegistry + src/backend.ts # StorageBackend/KvFacet/KvUnitDescriptor/KvUnit 类型 + src/error.ts # StorageError + code 联合 + src/invariant.ts # 见下 + tests/registry.spec.ts # registry/mount 套件 + README.md +``` + +class/接口逐条(签名以 Note 为准,此处列实现要点): + +| 成员 | 实现要点 | +| --- | --- | +| `class Storage extends Service` | `super(ctx, 'storage')`;`readonly backend = new BackendRegistry()`;`mount(form, facility)` 存入私有 `Map<keyof StorageForms, unknown>`,重复 → `StorageError('duplicate-mount')`,返回删除闭包;`get domain()` 从 map 取,缺 → `StorageError('form-not-mounted')` | +| `class BackendRegistry` | 私有 `Map<string, StorageBackend>`;`register` 重名 → `duplicate-backend`,返回 `() => map.delete(name)`;`get` 缺名 → `backend-not-found`;`names()` 返回数组拷贝 | +| `interface StorageForms {}` | 空接口 + JSDoc(merge-extensible,键 = 数据形式名) | +| `interface StorageBackend / KvFacet / KvUnitDescriptor / KvUnit` | 纯类型 + 契约 JSDoc(七条契约写在 KvUnit 各方法 JSDoc 上——这是 backend 实现者的规范文本) | +| `class StorageError extends Error` | `constructor(code, message?, cause?)`;`name = 'StorageError'` | +| `const UNIT_NAME_RE = /^[a-z][a-z0-9_]*$/` | 导出;descriptor 校验用(backend open 时验,fail loud) | +| invariant | 枢纽自身无运行时不变量(纯注册表,无事件流/可变盘面),写"explained empty"(措辞照抄 sqlite 后端 invariant.ts 的 "No runtime invariant:" 模板) | + +事件面:本包**无**事件(`domain/changed` 归 dsh-storage-domain)。 + +## 2. W2a:`dsh-storage-json` —— teammate **json-backend** + +``` +packages/storage/storage-json/ + src/index.ts # Config + apply + JsonStorageBackend + src/unit.ts # JsonKvUnit + src/atomic.ts # temp+fsync+rename 原子写(含 win32 分支) + src/format.ts # 文件格式 parse/serialize + malformed 检查 + src/invariant.ts + tests/json-backend.spec.ts # 挂共享契约套件(见 §5)+ json 特有(文件肉眼格式、malformed) +``` + +| class | 要点 | +| --- | --- | +| `Config` | schemastery,`root: z.string().required()`(JSDoc 说明为何无默认:防 cwd 散落,参照 session-persistence 措辞) | +| `class JsonStorageBackend implements StorageBackend` | `name='json'`;`kv = { open }`;持 `Map<unitName, JsonKvUnit>`(同名重复 open → 复用还是报错:**报错**,unit 生命周期归调用方,double-open 是 bug);`close()` 逐 unit close,幂等 | +| `class JsonKvUnit implements KvUnit` | 内存态 `{ version, global, tables: Map<string, Map<string, unknown>> }` 为权威;构造时读盘:文件缺失 = 空单元(不落盘),存在则 parse + 版本比对;每个写原语 = 改内存 → `writeAtomic(serialize())`;**写不排队**(契约第 4 条:串行是调用方的事),但单次 writeAtomic 内部完整(temp/fsync/rename);close 后操作 → `closed` | +| `atomic.ts` | `writeAtomic(path, data)`:同目录 temp 文件 + fsync + rename;win32 分支照抄 `session-persistence-jsonl/src/win32.ts` 的替换语义(先照抄,`log` facet 迁移期再提共享——Note 已记)| +| `format.ts` | `serialize(unit): string`(`JSON.stringify(…, null, 2)` + 尾换行);`parse(text): ParsedUnit`,缺 `unit` 头/结构不符 → `malformed-medium` | +| apply | `ctx.effect(() => { const d = ctx.storage.backend.register('json', backend); return async () => { d(); await backend.close() } })`;inject: `['storage']` | +| invariant | 断言候选:rename 发布后盘上文件必可 parse 回等价内存态(写后读回校验,仅测试态开启);若判断无运行时可断言关系则 explained empty | + +## 3. W2b:`dsh-storage-sqlite` —— teammate **sqlite-backend** + +``` +packages/storage/storage-sqlite/ + src/index.ts # Config + apply + SqliteStorageBackend + src/unit.ts # SqliteKvUnit + src/schema.ts # SCHEMA_VERSION + openDatabase + DDL + src/invariant.ts + tests/sqlite-backend.spec.ts +``` + +| class | 要点 | +| --- | --- | +| `Config` | `path: z.string().required()`(`:memory:` 允许)+ `journalMode` 枚举 default 'wal' | +| `schema.ts` | `STORAGE_SQLITE_SCHEMA_VERSION = 1`;`openDatabase(config)` 照抄 session-persistence-sqlite 的序列(mkdir 0o700 → wx 0o600 建文件 → PRAGMA foreign_keys → journal_mode → user_version 检查盖章/拒绝 → 建 `units`/`unit_globals`);**先照抄不提共享 helper**(Note 已记:提取放迁移期) | +| `class SqliteStorageBackend` | `name='sqlite'`;单 `DatabaseSync` 连接;`kv.open(descriptor)`:校验名字字符集 → `units` 行版本比对(无行则 INSERT 盖章)→ 按 descriptor.tables 逐张 `CREATE TABLE IF NOT EXISTS "u_<unit>_<table>"` → 返回 unit;`close()` 关连接 | +| `class SqliteKvUnit` | 预编译语句(每表 upsert/delete/select-all + global upsert);`loadAll` 全表 SELECT 组装;`putRecord` = `INSERT … ON CONFLICT(key) DO UPDATE`;单语句原子,无显式事务;value `JSON.stringify`/parse | +| invariant | 断言候选:STRICT 表 + user_version 与常量一致(open 后检);或 explained empty | + +## 4. W3:`dsh-storage-domain` —— teammate **domain-layer** + +``` +packages/storage/storage-domain/ + src/index.ts # Config + apply + DomainFacility + src/spec.ts # DomainSpec/defineDomain/domainTable + descriptorOf + src/domain.ts # DomainImpl + KvTableImpl + 写链 + src/events.ts # domain/changed declaration merging + src/error.ts # DomainError + src/invariant.ts + tests/domain.spec.ts # 用内存假 backend(tests/helpers/memory-backend.ts) +``` + +| class | 要点 | +| --- | --- | +| `Config` | `backend: z.string().required()` + `routes: z.dict(z.string()).default({})` | +| `spec.ts` | `defineDomain` 恒等函数(编译期收窄)+ 名字/表名正则校验(违规 throw,misconfiguration fails loud);`descriptorOf(spec)` 投影 | +| `class DomainFacility` | 持 `Map<domainName, DomainImpl>`(already-open 检查);`open(spec)` 按 Note 六步实现;zod 依赖在此包(dependencies,不是 peer) | +| `class DomainImpl` | 写链 `chain: Promise<void>`(`enqueue<T>(job): Promise<T>` 私有方法,所有写走它);内存态 `Map<table, Map<key, value>>` + global;每写:链上 → 改内存 → unit 原语 await → `ctx.emit('domain/changed', …)`;dispose:`enqueue(noop)` 排空 → `unit.close()` | +| `class KvTableImpl<K,V>` | 读同步走内存;`update` fn 同步纯(类型上 `(current: V) => V`),缺 key → `missing-key`;`delete` 返回是否存在 | +| `events.ts` | 按 Note 全文(`@mode emit` + `@param`);`DomainChanged` 接口导出 | +| invariant | 断言候选(真不变量,建议做):**每次 `domain/changed` 事件的 value 必等于内存态当前值**(事件流 vs 可变数据的 owned relationship,正合仓库 invariant 规范)| +| tests/helpers/memory-backend.ts | `MemoryStorageBackend`:Map 实现 KvUnit,宣称版本可注入——共享给 W4 用 | + +## 5. 共享 backend 契约套件 —— domain-layer 兼写(或主线程) + +``` +packages/storage/storage/tests/contract.ts # export function runKvBackendContract(factory) +``` + +- 仿 `runPersistenceContract` 形状:`factory: () => Promise<{ backend, reopen(): Promise<StorageBackend> }>`,两后端 spec 文件各自 import 调用。 +- 覆盖 Note 七条契约 + 版本拒绝 + close 幂等;"崩溃再 open"用 `reopen()`(新实例指向同一介质)模拟。 +- 落在接口包 tests/ 下(不进 src,不发布),json/sqlite 的 devDependencies 指向 workspace 接口包即可复用。 + +## 6. W4:`dsh-workspace` —— teammate **workspace-domain** + +``` +packages/workspace/workspace/ + src/index.ts # apply + WorkspaceRegistry(service 挂 ctx.workspace) + src/types.ts # WorkspaceId brand + Workspace 接口 + src/spec.ts # workspaceRecord zod + workspaceDomainSpec + src/entity.ts # WorkspaceEntity(不出包:index.ts 不 re-export) + src/paths.ts # realpathNormalize(path) + src/invariant.ts + tests/workspace.spec.ts # MemoryStorageBackend + 假 sessionPersistence stub +``` + +(删除入口本期不存在:registry 无 delete、entity 无关联清理——整套删除语义在 Agent Note 的 future work 节。) + +| class | 要点 | +| --- | --- | +| `types.ts` | `WorkspaceId` brand + 工厂;`Workspace` 接口(Note 签名照录,JSDoc 齐全——这是对外契约) | +| `spec.ts` | `workspaceRecord`(path/title/sessionIds/createdAt/updatedAt)+ `workspaceDomainSpec = defineDomain({ name: 'workspace', version: 1, tables: { workspaces: … } })` | +| `paths.ts` | `realpathNormalize(p): Promise<string>`——`fs.realpath`;ENOENT 原样抛(create 的 reject 路径) | +| `class WorkspaceRegistry extends Service` | `super(ctx, 'workspace')`;inject `['storage', 'sessionPersistence']`(sessionPersistence optional:`ctx.get()` 取,缺席时 attach 拒绝);`start()`:`ctx.storage.domain.open(workspaceDomainSpec)` + 重建 `Map<WorkspaceId, WorkspaceEntity>`;`create`:realpath → resolveByPath 撞 → reject;否则 `WorkspaceId(randomUUID())` + `table.put` + 建实体入缓存;`list()` 快照数组(过滤无效 sessionId 的投影在实体 getter 做);**无 delete 方法**(future work,与 session 级联一体落地) | +| `class WorkspaceEntity implements Workspace` | 构造持 registry/id/record;getter 投影;`mutate(fn)` 私有:`table.update(id, r => stampUpdatedAt(fn(r)))` 后原地换 record;`attachSession`:读 `sessionPersistence.list()` 找 header(或 inspect),cwd realpath ≠ path → reject;幂等(已在账 → no-op);`detachSession` 摘账(不动 session 文件);`status()`:`fs.access(path)` | +| 一致性口径 | ①账指向的 session 查无:**投影过滤**(getter 层)+ 下次 mutate 摘除;③双重账 load 检出 → throw;④missing-dir 只反映在 status() | +| invariant | 断言候选:缓存实体集合与 domain 表 key 集合一致(owned relationship:registry 缓存 vs 权威盘面)| + +## 7. Teammate 编成与节奏 + +| teammate | 包 | 开工条件 | 预估节奏 | +| --- | --- | --- | --- | +| (主线程) | W1 storage 枢纽 + §5 契约套件骨架 | 立即 | 首批落盘,随后进入 review/dispatcher 角色 | +| json-backend | W2a | W1 类型可编译即开工 | 分批落盘:atomic/format 先行,unit 次之,契约套件接入收尾 | +| sqlite-backend | W2b | 同上 | schema.ts 先行(照抄源已指明),unit 次之 | +| domain-layer | W3 + memory-backend helper | 同上 | spec/error 先行 → DomainImpl 写链 → 事件 → 契约套件(若主线程未完成则兼) | +| workspace-domain | W4 | W3 的 src 类型定型(不等其测试) | types/spec/paths 先行 → registry/entity → 测试 | + +协作规矩(照 conventions):分批落盘每批几分钟内、每批一句话回执;产出零落盘超 5 分钟报告;不混 commit 别人的在途文件;代码注释一律英文且只写非显然契约;干完不 kill 保持待命。commit 纪律:`--no-verify`,按包分刀(W1 一刀 → W2a/W2b/W3 各一刀 → W4 一刀 → 测试/文档尾刀),文档(本文件 + Agent Note 增量)住顶刀。 + +## 8. 主线程验收清单(每包合入前) + +- [ ] `pnpm run typecheck` 过(本期唯一硬门禁) +- [ ] 包结构齐:package.json(`@deepseek-ai/dsh-*`、ESM、cordis peerDep)、README、invariant 伴生(真断言或 explained empty) +- [ ] 接口与 Agent Note 一致;发现实现逼着改接口 → 停下来报主线程裁决(不擅改 Note) +- [ ] 测试文件落位正确(包级 tests/、`.spec.ts`),能跑多少跑多少,红的记台账不追修 +- [ ] session-persistence 包零 diff(`git status` 检查线) diff --git a/package.json b/package.json index 3ff149b80a..a925ea3ec9 100644 --- a/package.json +++ b/package.json @@ -89,6 +89,7 @@ "constraints": "tsx scripts/check-workspace-constraints.ts", "doc-sync": "tsx scripts/run-gates.ts doc-sync", "hygiene": "pnpm run knip && pnpm run publint && pnpm run constraints && pnpm run verify-package-invariants && pnpm run verify-built-package-invariants && pnpm run verify-cordis-config && pnpm run verify-node-next-types && pnpm run verify-runtime-closure", + "dsh": "node --import tsx apps/cli/src/bin.ts", "demo:headless": "node --import tsx packages/examples/cli-demo/src/bin.ts --config examples/headless-agent/cordis.yml", "demo:tui": "node --import tsx apps/cli/src/bin.ts", "demo:code-mode": "node scripts/demo-code-mode.mjs", diff --git a/packages/README.md b/packages/README.md index 4e18d7b5f8..cffc4a0554 100644 --- a/packages/README.md +++ b/packages/README.md @@ -34,9 +34,12 @@ Packages live at `packages/<group>/<pkg>/`; groups are containers, while names r | [`session-persistence/`](session-persistence/README.md) | Persistence capability family: the seam + JSONL/SQLite backends | Product — stable surface | | [`session-query/`](session-query/README.md) | Session retrieval family: logical corpus, bounded reads, lineage, event relationships, semantic filtering, and SQLite full-text search | Product — stable surface | | [`session-title/`](session-title/README.md) | Log-backed session titles: fallback service, shared LLM policy, and opt-in providers | Product — stable surface | +| [`storage/`](storage/README.md) | Non-session storage hub + backends + domain form | Product — stable surface | +| [`workspace/`](workspace/README.md) | Workspace entity | Product — stable surface | | [`sdk/`](sdk/README.md) | Project SDK tooling | Product — stable surface | -| [`ui/`](ui/README.md) | Editor/client integration surfaces: ACP bridge, JSON-RPC SDK server, user-approval/user-interaction seams, ask-user tool | Product — stable surface | -| [`examples/`](examples/README.md) | Demo bundles (agent-spine + TUI/one-shot CLI/ACP/JSON-RPC bins) the leaves load | Support — example infra | +| [`acp/`](acp/README.md) | Automation-only Agent Client Protocol server | Product — stable surface | +| [`ui/`](ui/README.md) | Human/client integrations: TUI and JSON-RPC, approval/interaction seams, ask-user tool | Product — stable surface | +| [`examples/`](examples/README.md) | Demo bundles (agent-spine + TUI/CLI/ACP/JSON-RPC bins) leaves load | Support — example infra | | [`support/`](support/README.md) | Support infrastructure (testkits, invariants, replay, Loader smokes) | Support — lower compatibility expectations | | [`util/`](util/README.md) | Low-level zero-dependency utilities shared across groups (`Branded<B>`, Harness home/path helpers, timeout, retention) | Support — small, stable, harness-dep-free | diff --git a/packages/acp/README.md b/packages/acp/README.md new file mode 100644 index 0000000000..480b15726d --- /dev/null +++ b/packages/acp/README.md @@ -0,0 +1,9 @@ +# acp/ — Agent Client Protocol automation + +The ACP group exposes harness agents to programmatic clients. It is an interoperability transport, not a presentation or human-interaction layer. + +| Package | Role | +|---|---| +| [`acp/`](acp/README.md) | Automation-only ACP server: fresh text sessions, committed assistant output, machine permission policy, cancellation, and connection-owned teardown. | + +The matching out-of-process subagent client remains in [`subagent/subagent-acp`](../subagent/subagent-acp/README.md) because it implements the subagent provider interface; arbitrary ACP clients may drive the same server contract. diff --git a/packages/acp/acp/README.md b/packages/acp/acp/README.md new file mode 100644 index 0000000000..20b1ecbefe --- /dev/null +++ b/packages/acp/acp/README.md @@ -0,0 +1,77 @@ +# @deepseek-ai/dsh-acp + +Automation-only [Agent Client Protocol](https://agentclientprotocol.com) server over JSON-RPC stdio. Programmatic clients create fresh harness agents, send text prompts, collect committed assistant text, resolve one-shot permission requests by policy, and cancel work. The primary in-repository client is [`dsh-subagent-acp`](../../subagent/subagent-acp/README.md). + +This package is a transport adapter, not a UI integration or a capability seam. It does not expose editor navigation, transcript replay, commands, modes, configuration pickers, elicitation, reasoning, plans, titles, or tool presentation. Interactive rendering and human questions belong to the web and TUI modules. + +## Plugin + +`apply(ctx, config)` opens an `AgentSideConnection` on stdin/stdout and drives `ctx.agents`. Stdout is reserved for protocol frames. + +| Config | Default | Meaning | +|---|---|---| +| `provider` | — | Initial provider route for every created agent. | +| `model` | — | Initial model for every created agent. | + +Both fields are optional so another agent/request listener may supply the target. The runnable ACP composition requires both. + +## Protocol contract + +| Method | Behavior | +|---|---| +| `initialize` | Negotiates the supported version and advertises baseline-only prompts (no image, audio, or embedded-context capability). No session, editor, terminal, filesystem, or MCP capability is advertised. | +| `authenticate` | No-op because the server advertises no authentication methods. | +| `session/new` | Creates a fresh agent with an absolute primary `cwd`; empty `additionalDirectories` and `mcpServers` are accepted, non-empty values reject. | +| `session/prompt` | Concatenates text blocks, renders baseline resource links as bracketed textual references, rejects empty or beyond-baseline input, permits one in-flight request per session, and settles from that request's owning durable `turn/end`. | +| `session/cancel` | Cancels only the addressed agent and settles its pending prompt as `cancelled`; unknown ids are no-ops. | +| `session/update` | Emits one `agent_message_chunk` per non-empty text block in a committed `assistant/message`. Raw deltas and non-message events are omitted. | +| `session/request_permission` | Offers one-shot allow/reject choices for bridge-owned approval requests carrying a tool call id. Clients may answer automatically. | + +One connection may own several sessions. The bridge keys records by branded session id and checks exact agent identity before routing events or permission requests. Each session has an independent prompt slot, workspace, cancellation path, and disposer. + +Committed-message output intentionally trades token-by-token latency for a clean automation result. Uncommitted provider chunks and retry attempts cannot leak partial text; reasoning and tool activity remain in the session log for observability through other interfaces. + +## Lifecycle + +Client disconnect and Cordis disposal share one memoized teardown. The bridge first rejects new sessions and prompts, settles pending prompts, then disposes all owned agent handles in parallel and awaits their loop/session cleanup. An ACP-only plugin reload therefore leaves no orphan agent. + +## Running + +`pnpm --dir /path/to/deepseek-harness run demo:acp` boots the repository's automation server composition. A parent harness can spawn it through [`@deepseek-ai/dsh-subagent-acp`](../../subagent/subagent-acp/README.md); other ACP clients need only the core methods above. + +## Model Experience + +### Prompt text + +#### What the model sees + +`session/prompt` text blocks are concatenated verbatim into one user message; a baseline resource link appears in that message as a bracketed `[resource_link name=… uri=…]` reference the model may open with its own tools. Protocol metadata, client capabilities, permission choices, and session ids never enter the model request. + +#### Token effect + +Prompt tokens are data-dependent and remain in that session's history until compaction. Concurrent ACP sessions retain independent contexts. + +#### KV Cache effect + +Append-only; the new user message follows the reusable request prefix and does not invalidate prior cache entries. + +### Permission decisions + +#### What the model sees + +Nothing directly. The owning tool records its allowed, rejected, cancelled, or unavailable outcome through the normal tool-result path. + +#### Token effect + +Only the owning tool result contributes tokens. + +#### KV Cache effect + +Append-only through the owning tool result. + +## Known Limitations and Deferred Work + +- **Fresh sessions only** — load, list, resume, delete, and fork are unsupported. +- **Baseline prompts and one workspace only** — images, audio, embedded resources, non-empty additional directories, and MCP servers reject; resource links flatten to textual references rather than fetched content. +- **Committed answers only** — live progress, reasoning, tool activity, plans, titles, and usage stay off the wire. +- **Connection-owned lifetime** — one connection releases all of its sessions; per-session close is not implemented. diff --git a/packages/acp/acp/package.json b/packages/acp/acp/package.json new file mode 100644 index 0000000000..6ef2f4def5 --- /dev/null +++ b/packages/acp/acp/package.json @@ -0,0 +1,51 @@ +{ + "name": "@deepseek-ai/dsh-acp", + "description": "Automation-only Agent Client Protocol server for driving DeepSeek Harness agents over JSON-RPC stdio", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "dependencies": { + "@agentclientprotocol/sdk": "0.25.1", + "schemastery": "^3.17.0" + }, + "peerDependencies": { + "@deepseek-ai/dsh-agent": "^0.0.1", + "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-session": "^0.0.1", + "@deepseek-ai/dsh-user-approval": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "@deepseek-ai/dsh-user-approval": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/acp/acp/src/codec.ts b/packages/acp/acp/src/codec.ts new file mode 100644 index 0000000000..2a88af1184 --- /dev/null +++ b/packages/acp/acp/src/codec.ts @@ -0,0 +1,63 @@ +/** + * Pure translation between the harness lifecycle and the automation-only ACP wire. + * @module @deepseek-ai/dsh-acp/codec + */ + +import type { ContentBlock as AcpContentBlock, StopReason } from '@agentclientprotocol/sdk' +import type { TurnEndReason } from '@deepseek-ai/dsh-session' + +/** + * Map a harness turn ending to ACP's terminal reason vocabulary. + * @param reason - harness turn outcome. + * @returns the closest legal ACP stop reason. + */ +export function turnEndToStopReason(reason: TurnEndReason): StopReason { + switch (reason.kind) { + case 'completed': + return 'end_turn' + case 'max-tokens': + return 'max_tokens' + case 'aborted': + case 'disposed': + case 'rejected': + case 'interrupted': + return 'cancelled' + case 'error': + return 'end_turn' + // TurnEndReason is merge-extensible; future variants still need a legal wire value. + default: + return 'end_turn' + } +} + +/** + * Flatten an ACP prompt's baseline blocks to text. Text blocks concatenate + * verbatim; resource links become explicit textual references so a baseline + * client can point at files without the bridge silently dropping that context. + * @param prompt - supported ACP prompt blocks. + * @returns text in wire order, with resource links rendered as bracketed references. + */ +export function acpPromptToText(prompt: readonly AcpContentBlock[]): string { + return prompt.flatMap((block): string[] => { + switch (block.type) { + case 'text': + return [block.text] + case 'resource_link': + return [`\n[resource_link name=${JSON.stringify(block.name)} uri=${JSON.stringify(block.uri)}]\n`] + default: + return [] + } + }).join('') +} + +/** + * Whether a prompt carries content beyond the ACP baseline. The spec requires + * every agent to accept `text` and `resource_link`; richer inline payloads + * (image, audio, embedded resource) are optional capabilities this bridge does + * not advertise, so they are rejected rather than silently dropped. + * @param prompt - ACP prompt blocks to inspect. + * @returns `true` when any block is neither `text` nor `resource_link`. + */ +export function promptHasUnsupportedContent(prompt: readonly AcpContentBlock[]): boolean { + return prompt.some(block => block.type !== 'text' && block.type !== 'resource_link') +} diff --git a/packages/acp/acp/src/index.ts b/packages/acp/acp/src/index.ts new file mode 100644 index 0000000000..3ca4767c67 --- /dev/null +++ b/packages/acp/acp/src/index.ts @@ -0,0 +1,330 @@ +/** + * Automation-only Agent Client Protocol server over JSON-RPC stdio. + * + * The bridge exposes fresh harness sessions to trusted programmatic clients. It + * carries prompt text, committed assistant text, cancellation, and one-shot + * permission decisions; presentation and human-interaction features stay with + * the harness's UI modules. + * + * @module @deepseek-ai/dsh-acp + */ + +import type { Context } from 'cordis' +import { randomUUID } from 'node:crypto' +import { isAbsolute } from 'node:path' +import { Readable, Writable } from 'node:stream' +import Schema from 'schemastery' +import { + AgentSideConnection, + ndJsonStream, + PROTOCOL_VERSION, + RequestError, + type Agent as AcpAgent, + type AuthenticateRequest, + type CancelNotification, + type InitializeRequest, + type InitializeResponse, + type NewSessionRequest, + type NewSessionResponse, + type PromptRequest, + type PromptResponse, + type SessionNotification, + type StopReason, + type Stream, +} from '@agentclientprotocol/sdk' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { SessionId, type SessionEvent, type TurnEndReason } from '@deepseek-ai/dsh-session' +// Side-effect type import: declaration-merges the approval waterfall answered below. +import type {} from '@deepseek-ai/dsh-user-approval' +import { acpPromptToText, promptHasUnsupportedContent, turnEndToStopReason } from './codec.ts' + +export const name = 'acp' +/** The bridge creates and owns agents; every other concern is carried by the agent composition. */ +export const inject = ['agents'] + +/** Preserve invalid-parameter detail in the SDK wire error message. */ +function invalidParams(detail: string): RequestError { + return RequestError.invalidParams(undefined, detail) +} + +/** Preserve failed-turn detail; plain handler errors become a generic wire internal error. */ +function internalError(detail: string): RequestError { + return RequestError.internalError(undefined, detail) +} + +/** Plugin config: the provider/model target used for each ACP-created agent. */ +export interface AcpConfig { + /** Provider route for created agents. */ + provider?: string + /** Model name for created agents. */ + model?: string + /** Runtime-only transport override; production uses stdio. */ + stream?: Stream +} + +export const Config: Schema<AcpConfig> = Schema.object({ + provider: Schema.string(), + model: Schema.string(), +}) + +/** Per-session protocol state. */ +interface SessionRecord { + agent: Agent + /** Exact owned-agent disposer; resolves after registry, loop, and session teardown. */ + dispose: () => Promise<void> + /** In-flight prompt and its captured turn number for exact settlement. */ + inflight: { + resolve: (reason: StopReason) => void + reject: (error: Error) => void + turn: number | undefined + } | undefined +} + +/** + * Mount the automation-only ACP server. + * @param ctx - Cordis context carrying the agent factory and session events. + * @param config - Initial provider/model target and optional test transport. + */ +export function apply(ctx: Context, config: AcpConfig): void { + // ACP handlers execute outside this plugin's injection scope, so capture the + // injected service during apply rather than reading it lazily in a callback. + const agents = ctx.agents + const logger = ctx.logger + const sessions = new Map<SessionId, SessionRecord>() + let closed = false + let conn: AgentSideConnection + + /** Return the bridge-owned record for an agent, rejecting same-id impostors. */ + const ownedRecord = (agent: Agent): SessionRecord | undefined => { + const record = sessions.get(agent.session.id) + return record?.agent === agent ? record : undefined + } + + const assertOpen = (): void => { + if (closed) throw internalError('the ACP bridge has been disposed') + } + + const requireSession = (sessionId: SessionId): SessionRecord => { + const record = sessions.get(sessionId) + if (record === undefined) throw invalidParams(`unknown session: ${sessionId}`) + return record + } + + /** Send a protocol update without letting a disconnected client fail an agent turn. */ + const notify = (notification: SessionNotification): void => { + /* v8 ignore next 3 -- only a transport write failure reaches this guard. */ + void conn.sessionUpdate(notification).catch((error: unknown) => { + logger.warn(`acp: session/update failed: ${String(error)}`) + }) + } + + const settlePrompt = (record: SessionRecord, reason: StopReason): void => { + const inflight = record.inflight + if (inflight === undefined) return + record.inflight = undefined + inflight.resolve(reason) + } + + const settleFromTurnEnd = ( + inflight: NonNullable<SessionRecord['inflight']>, + reason: TurnEndReason, + ): void => { + if (reason.kind === 'error') { + inflight.reject(internalError(`turn failed: ${'failure' in reason ? reason.failure.message : reason.message}`)) + return + } + inflight.resolve(turnEndToStopReason(reason)) + } + + // Emit only committed assistant text. Raw chunks, reasoning, tools, plans, + // titles, and retry markers are presentation or trace data and stay off the + // automation wire. + ctx.on('session/event', (session, event: SessionEvent) => { + const record = sessions.get(session.header.id) + if (record === undefined || record.agent.session !== session) return + try { + if (event.type === 'assistant/message') { + for (const block of event.data.content) { + if (block.type === 'text' && block.text.length > 0) { + notify({ + sessionId: record.agent.session.id, + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: block.text }, + }, + }) + } + } + } + } finally { + const inflight = record.inflight + if (inflight !== undefined && event.type === 'turn/start') { + if (inflight.turn === undefined && event.data.trigger.kind === 'message' + && event.data.trigger.source.kind === 'user') { + inflight.turn = event.data.turn + } + } else if (inflight !== undefined && event.type === 'turn/end' && inflight.turn === event.data.turn) { + record.inflight = undefined + settleFromTurnEnd(inflight, event.data.reason) + } + } + }) + + // Permission requests are a machine policy channel for ACP clients such as + // dsh-subagent-acp. The bridge offers one-shot choices only and never infers a + // durable grant from an unknown client response. + ctx.on('approval/request', (request, next) => { + const record = ownedRecord(request.agent) + if (record === undefined || request.callId === undefined) return next() + return conn.requestPermission({ + sessionId: record.agent.session.id, + toolCall: { toolCallId: request.callId }, + options: [ + { optionId: 'allow-once', name: 'Allow once', kind: 'allow_once' }, + { optionId: 'reject-once', name: 'Reject', kind: 'reject_once' }, + ], + }).then(({ outcome }) => { + if (outcome.outcome === 'cancelled') return 'cancelled' + return outcome.optionId === 'allow-once' ? 'allowed-once' : 'rejected' + }) + }) + + const makeAgent = (connection: AgentSideConnection): AcpAgent => { + conn = connection + return { + initialize(_params: InitializeRequest): Promise<InitializeResponse> { + // Single-version agent: the spec's "same version if supported, else + // the latest supported" both resolve to this server's one version. + return Promise.resolve({ + protocolVersion: PROTOCOL_VERSION, + agentInfo: { name: 'deepseek-harness-acp', version: '0.0.1' }, + agentCapabilities: { + promptCapabilities: { image: false, audio: false, embeddedContext: false }, + }, + authMethods: [], + }) + }, + + authenticate(_params: AuthenticateRequest): Promise<void> { + return Promise.resolve() + }, + + async newSession(params: NewSessionRequest): Promise<NewSessionResponse> { + assertOpen() + validateSessionParams(params) + const sessionId = SessionId(randomUUID()) + const handle = await agents.create({ + sessionId, + meta: { cwd: params.cwd }, + agentOptions: agentOptions(config), + }) + /* v8 ignore next 4 -- a real stdio close can race an in-flight create. */ + if (closed) { + await handle.dispose() + throw internalError('connection closed during session/new') + } + sessions.set(sessionId, { + agent: handle.agent, + dispose: () => handle.dispose(), + inflight: undefined, + }) + return { sessionId } + }, + + async prompt(params: PromptRequest): Promise<PromptResponse> { + assertOpen() + const record = requireSession(SessionId(params.sessionId)) + if (record.inflight !== undefined) { + throw invalidParams('a prompt is already in flight for this session') + } + if (promptHasUnsupportedContent(params.prompt)) { + throw invalidParams('only text and resource_link prompt content is supported') + } + const text = acpPromptToText(params.prompt) + if (text.trim().length === 0) throw invalidParams('empty prompt') + + const stopReason = await new Promise<StopReason>((resolve, reject) => { + // Arm the slot before followup() so a listener-driven synchronous + // turn cannot slip past correlation; a synchronous followup() + // failure (an agent disposed outside the bridge, e.g. an + // agent-loop-only reload) must free the slot again or the session + // would reject every later prompt as already in flight. + record.inflight = { resolve, reject, turn: undefined } + try { + record.agent.followup([{ type: 'text', text }]) + } catch (error: unknown) { + record.inflight = undefined + // followup() throws only Errors (disposed agent / invalid input); + // the String arm is a defensive fallback for a non-Error throw. + /* v8 ignore next */ + const detail = error instanceof Error ? error.message : String(error) + throw internalError(`prompt was not queued: ${detail}`) + } + }) + return { stopReason } + }, + + cancel(params: CancelNotification): Promise<void> { + const record = sessions.get(SessionId(params.sessionId)) + if (record === undefined) return Promise.resolve() + record.agent.cancel({ kind: 'user' }) + settlePrompt(record, 'cancelled') + return Promise.resolve() + }, + } + } + + /* v8 ignore next 4 -- production stdio wiring; tests inject config.stream. */ + const stream: Stream = config.stream ?? ndJsonStream( + Writable.toWeb(process.stdout) as WritableStream<Uint8Array>, + Readable.toWeb(process.stdin) as ReadableStream<Uint8Array>, + ) + conn = new AgentSideConnection(makeAgent, stream) + + let quiescing: Promise<void> | undefined + const quiesce = (): Promise<void> => { + if (quiescing !== undefined) return quiescing + closed = true + const records = [...sessions.values()] + sessions.clear() + quiescing = Promise.all(records.map(async (record) => { + settlePrompt(record, 'cancelled') + await record.dispose() + })).then(() => {}) + return quiescing + } + + /* v8 ignore start -- production transport rejection and teardown failure. */ + void conn.closed + .catch((error: unknown) => { + logger.warn(`acp: connection closed with an error: ${String(error)}`) + }) + .then(quiesce) + .catch((error: unknown) => { + logger.warn(`acp: connection-close teardown failed: ${String(error)}`) + }) + /* v8 ignore stop */ + + ctx.effect(() => quiesce, 'acp.connection') +} + +/** + * Build per-agent options from plugin config without assigning absent optional fields. + * @param config - ACP provider/model configuration. + * @returns the configured fields only. + */ +function agentOptions(config: AcpConfig): { provider?: string; model?: string } { + return { + ...config.provider !== undefined ? { provider: config.provider } : {}, + ...config.model !== undefined ? { model: config.model } : {}, + } +} + +/** Reject session features outside the automation contract. */ +function validateSessionParams(params: NewSessionRequest): void { + if (!isAbsolute(params.cwd)) throw invalidParams(`cwd must be an absolute path: ${params.cwd}`) + if (params.additionalDirectories !== undefined && params.additionalDirectories.length > 0) { + throw invalidParams('additionalDirectories is not supported') + } + if (params.mcpServers.length > 0) throw invalidParams('mcpServers is not supported') +} diff --git a/packages/ui/acp/src/invariant.ts b/packages/acp/acp/src/invariant.ts similarity index 85% rename from packages/ui/acp/src/invariant.ts rename to packages/acp/acp/src/invariant.ts index fdefcf291e..9d5b769872 100644 --- a/packages/ui/acp/src/invariant.ts +++ b/packages/acp/acp/src/invariant.ts @@ -15,8 +15,8 @@ export const name = 'acp-invariant' export const inject = ['invariants'] /** - * No runtime invariant: this presentation adapter owns no durable package-local event stream; - * boundary and replay tests cover its protocol mapping. + * No runtime invariant: this transport owns no durable package-local event stream; + * protocol and lifecycle tests cover its mapping. */ const install: InvariantInstaller = () => {} diff --git a/packages/acp/acp/tests/approval.spec.ts b/packages/acp/acp/tests/approval.spec.ts new file mode 100644 index 0000000000..01bcd83249 --- /dev/null +++ b/packages/acp/acp/tests/approval.spec.ts @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' +import { CallId } from '@deepseek-ai/dsh-llm' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { SessionId } from '@deepseek-ai/dsh-session' +import ApprovalService, { type ApprovalRequest } from '@deepseek-ai/dsh-user-approval' +import { makeBridgeHarness, type BridgeHarness } from './harness.ts' + +describe('ACP machine permission policy', () => { + let harness: BridgeHarness | undefined + + afterEach(async () => { + await harness?.dispose() + harness = undefined + }) + + async function ownedRequest(overrides: Partial<ApprovalRequest> = {}): Promise<ApprovalRequest> { + if (harness === undefined) throw new Error('missing harness') + await harness.ctx.plugin(ApprovalService) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(SessionId(sessionId))! + agent.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + return { agent, toolName: 'bash', callId: CallId('call-9'), ...overrides } + } + + it('maps the two advertised one-shot choices', async () => { + harness = await makeBridgeHarness() + harness.onPermission = () => ({ outcome: { outcome: 'selected', optionId: 'allow-once' } }) + const request = await ownedRequest() + await expect(harness.ctx.approval.request(request)).resolves.toBe('allowed-once') + expect(harness.permissionRequests[0]).toMatchObject({ + sessionId: request.agent.session.id, + toolCall: { toolCallId: 'call-9' }, + options: [ + { optionId: 'allow-once', kind: 'allow_once' }, + { optionId: 'reject-once', kind: 'reject_once' }, + ], + }) + + harness.onPermission = () => ({ outcome: { outcome: 'selected', optionId: 'reject-once' } }) + await expect(harness.ctx.approval.request(request)).resolves.toBe('rejected') + }) + + it('maps cancellation and unknown choices without granting access', async () => { + harness = await makeBridgeHarness() + const request = await ownedRequest() + await expect(harness.ctx.approval.request(request)).resolves.toBe('cancelled') + harness.onPermission = () => ({ outcome: { outcome: 'selected', optionId: 'unknown-grant' } }) + await expect(harness.ctx.approval.request(request)).resolves.toBe('rejected') + }) + + it('fails closed when the client errors the permission request', async () => { + harness = await makeBridgeHarness() + const request = await ownedRequest() + harness.onPermission = () => { throw new Error('client gone') } + await expect(harness.ctx.approval.request(request)).resolves.toBe('unavailable') + }) + + it('delegates a same-id foreign agent', async () => { + harness = await makeBridgeHarness() + const request = await ownedRequest() + const foreign = { + session: { id: request.agent.session.id, events: [{ type: 'turn/start' }], append: () => ({}) }, + } as unknown as Agent + await expect(harness.ctx.approval.request({ agent: foreign, toolName: 'bash', callId: CallId('call') })) + .resolves.toBe('unavailable') + expect(harness.permissionRequests).toHaveLength(0) + }) + + it('delegates requests that have no protocol tool-call identity', async () => { + harness = await makeBridgeHarness() + const request = await ownedRequest() + await expect(harness.ctx.approval.request({ agent: request.agent, toolName: request.toolName })) + .resolves.toBe('unavailable') + expect(harness.permissionRequests).toHaveLength(0) + }) +}) diff --git a/packages/acp/acp/tests/bridge.spec.ts b/packages/acp/acp/tests/bridge.spec.ts new file mode 100644 index 0000000000..619a628ea1 --- /dev/null +++ b/packages/acp/acp/tests/bridge.spec.ts @@ -0,0 +1,148 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' +import { SessionId } from '@deepseek-ai/dsh-session' +import { makeBridgeHarness, textResponse, type BridgeHarness } from './harness.ts' + +describe('automation-only ACP bridge', () => { + let harness: BridgeHarness | undefined + + afterEach(async () => { + await harness?.dispose() + harness = undefined + }) + + it('advertises only fresh text sessions', async () => { + harness = await makeBridgeHarness() + const response = await harness.client.initialize({ + protocolVersion: PROTOCOL_VERSION, + clientCapabilities: { _meta: { terminal_output: true } }, + }) + + expect(response).toEqual({ + protocolVersion: PROTOCOL_VERSION, + agentInfo: { name: 'deepseek-harness-acp', version: '0.0.1' }, + agentCapabilities: { + promptCapabilities: { image: false, audio: false, embeddedContext: false }, + }, + authMethods: [], + }) + }) + + it('negotiates an unsupported version and accepts the required no-op authentication call', async () => { + harness = await makeBridgeHarness() + const response = await harness.client.initialize({ protocolVersion: 0, clientCapabilities: {} }) + expect(response.protocolVersion).toBe(PROTOCOL_VERSION) + await expect(harness.client.authenticate({ methodId: 'unused' })).resolves.toEqual({}) + }) + + it('creates a session, emits one committed answer, and settles the prompt', async () => { + harness = await makeBridgeHarness({ script: [textResponse('hello there')] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const result = await harness.client.prompt({ + sessionId, + prompt: [{ type: 'text', text: 'say hello' }], + }) + + expect(result.stopReason).toBe('end_turn') + await vi.waitFor(() => { expect(harness!.updates).toHaveLength(1) }) + expect(harness.updates).toEqual([{ + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'hello there' }, + }]) + expect(harness.ctx.agents.get(SessionId(sessionId))?.session.header.cwd).toBe(process.cwd()) + expect(harness.adapter.requests[0]?.messages.at(-1)?.content).toEqual([{ type: 'text', text: 'say hello' }]) + }) + + it('leaves absent agent targets for request listeners to supply', async () => { + harness = await makeBridgeHarness({ config: { provider: undefined, model: undefined } }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + + expect(harness.ctx.agents.get(SessionId(sessionId))?.options).toEqual({}) + }) + + it('concatenates text blocks without exposing protocol framing to the model', async () => { + harness = await makeBridgeHarness({ script: [textResponse('done')] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + await harness.client.prompt({ + sessionId, + prompt: [ + { type: 'text', text: 'first' }, + { type: 'text', text: ' second' }, + ], + }) + + expect(harness.adapter.requests[0]?.messages.at(-1)?.content).toEqual([{ type: 'text', text: 'first second' }]) + }) + + it('renders the deployment persona for an ACP-created agent', async () => { + harness = await makeBridgeHarness({ persona: 'Automation persona for {{model}} in {{cwd}}.', script: [textResponse('ok')] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) + expect(harness.adapter.requests[0]?.system).toContain(`Automation persona for mock in ${process.cwd()}.`) + }) + + it('requires one absolute workspace and no MCP servers', async () => { + harness = await makeBridgeHarness() + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + + await expect(harness.client.newSession({ cwd: 'relative', mcpServers: [] })).rejects.toThrow(/absolute path/) + await expect(harness.client.newSession({ + cwd: process.cwd(), + mcpServers: [], + additionalDirectories: ['/tmp/other'], + })).rejects.toThrow(/additionalDirectories/) + await expect(harness.client.newSession({ + cwd: process.cwd(), + mcpServers: [{ name: 'fs', command: 'node', args: [], env: [] }], + })).rejects.toThrow(/mcpServers/) + + await expect(harness.client.newSession({ + cwd: process.cwd(), + mcpServers: [], + additionalDirectories: [], + })).resolves.toHaveProperty('sessionId') + }) + + it('rejects empty and beyond-baseline prompts before a turn starts', async () => { + harness = await makeBridgeHarness() + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: ' ' }] })) + .rejects.toThrow(/empty prompt/) + await expect(harness.client.prompt({ + sessionId, + prompt: [{ type: 'image', data: '', mimeType: 'image/png' }], + })).rejects.toThrow(/only text and resource_link/) + expect(harness.ctx.agents.get(SessionId(sessionId))?.session.events.some(event => event.type === 'turn/start')).toBe(false) + }) + + it('renders baseline resource links as textual references in the user message', async () => { + harness = await makeBridgeHarness({ script: [textResponse('done')] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + await harness.client.prompt({ + sessionId, + prompt: [ + { type: 'text', text: 'summarize' }, + { type: 'resource_link', name: 'notes.txt', uri: 'file:///tmp/notes.txt' }, + ], + }) + expect(harness.adapter.requests[0]?.messages.at(-1)?.content).toEqual([{ + type: 'text', + text: 'summarize\n[resource_link name="notes.txt" uri="file:///tmp/notes.txt"]\n', + }]) + }) + + it('rejects prompts for unknown sessions and ignores unknown cancellation', async () => { + harness = await makeBridgeHarness() + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + await expect(harness.client.prompt({ sessionId: 'missing', prompt: [{ type: 'text', text: 'go' }] })) + .rejects.toThrow(/unknown session/) + await expect(harness.client.cancel({ sessionId: 'missing' })).resolves.toBeUndefined() + }) +}) diff --git a/packages/acp/acp/tests/codec.spec.ts b/packages/acp/acp/tests/codec.spec.ts new file mode 100644 index 0000000000..2fdf544500 --- /dev/null +++ b/packages/acp/acp/tests/codec.spec.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import type { TurnEndReason } from '@deepseek-ai/dsh-session' +import { acpPromptToText, promptHasUnsupportedContent, turnEndToStopReason } from '../src/codec.ts' + +describe('ACP automation codec', () => { + it('maps every known turn outcome to a legal stop reason', () => { + const cases: [TurnEndReason, string][] = [ + [{ kind: 'completed' }, 'end_turn'], + [{ kind: 'max-tokens' }, 'max_tokens'], + [{ kind: 'aborted' }, 'cancelled'], + [{ kind: 'disposed' }, 'cancelled'], + [{ kind: 'rejected', reason: 'blocked' }, 'cancelled'], + [{ kind: 'interrupted' }, 'cancelled'], + [{ kind: 'error', step: 1, message: 'boom' }, 'end_turn'], + ] + for (const [reason, expected] of cases) expect(turnEndToStopReason(reason)).toBe(expected) + }) + + it('uses a legal fallback for merge-extensible future outcomes', () => { + expect(turnEndToStopReason({ kind: 'future' } as unknown as TurnEndReason)).toBe('end_turn') + }) + + it('flattens baseline blocks and rejects everything richer', () => { + expect(acpPromptToText([{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }])).toBe('ab') + expect(acpPromptToText([ + { type: 'text', text: 'see' }, + { type: 'resource_link', name: 'x', uri: 'file:///x' }, + ])).toBe('see\n[resource_link name="x" uri="file:///x"]\n') + expect(acpPromptToText([{ type: 'image', data: '', mimeType: 'image/png' }])).toBe('') + expect(promptHasUnsupportedContent([ + { type: 'text', text: 'ok' }, + { type: 'resource_link', name: 'x', uri: 'file:///x' }, + ])).toBe(false) + expect(promptHasUnsupportedContent([ + { type: 'image', data: '', mimeType: 'image/png' }, + ])).toBe(true) + }) +}) diff --git a/packages/acp/acp/tests/dispose.spec.ts b/packages/acp/acp/tests/dispose.spec.ts new file mode 100644 index 0000000000..1303cde0b2 --- /dev/null +++ b/packages/acp/acp/tests/dispose.spec.ts @@ -0,0 +1,85 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' +import { SessionId } from '@deepseek-ai/dsh-session' +import { makeBridgeHarness, type BridgeHarness } from './harness.ts' + +describe('ACP connection ownership', () => { + let harness: BridgeHarness | undefined + + afterEach(async () => { + await harness?.dispose() + harness = undefined + }) + + it('disposal cancels a running prompt and awaits agent teardown', async () => { + harness = await makeBridgeHarness({ script: ['hang'] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(SessionId(sessionId))! + const prompt = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) + await vi.waitFor(() => { expect(agent.status).toBe('running') }) + + await harness.acpFiber.dispose() + await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' }) + expect(agent.status).toBe('disposed') + expect(harness.ctx.agents.get(SessionId(sessionId))).toBeUndefined() + }) + + it('an ACP-only reload rejects new sessions before creating an orphan', async () => { + harness = await makeBridgeHarness() + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + await harness.acpFiber.dispose() + await expect(harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })) + .rejects.toThrow(/disposed/) + expect(harness.ctx.agents.list()).toHaveLength(0) + }) + + it('a client disconnect disposes every owned session without root-context disposal', async () => { + harness = await makeBridgeHarness({ script: ['hang'] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(SessionId(sessionId))! + void harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }).catch(() => {}) + await vi.waitFor(() => { expect(agent.status).toBe('running') }) + + await harness.closeClientTransport() + await harness.acpFiber.dispose() + expect(agent.status).toBe('disposed') + expect(harness.ctx.agents.get(SessionId(sessionId))).toBeUndefined() + expect(harness.ctx.sessions.get(SessionId(sessionId))).toBeUndefined() + }) + + it('a failed client transport still disposes every owned session', async () => { + harness = await makeBridgeHarness({ script: ['hang'] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(SessionId(sessionId))! + void harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }).catch(() => {}) + await vi.waitFor(() => { expect(agent.status).toBe('running') }) + + await harness.abortClientTransport() + await vi.waitFor(() => { expect(agent.status).toBe('disposed') }) + await vi.waitFor(() => { + expect(harness!.ctx.agents.get(SessionId(sessionId)) === undefined).toBe(true) + }) + }) + + it('disconnect and plugin disposal share one quiescence boundary', async () => { + harness = await makeBridgeHarness({ script: ['hang'] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(SessionId(sessionId))! + void harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }).catch(() => {}) + await vi.waitFor(() => { expect(agent.status).toBe('running') }) + + await Promise.all([harness.closeClientTransport(), harness.acpFiber.dispose()]) + expect(agent.status).toBe('disposed') + expect(harness.ctx.agents.get(SessionId(sessionId))).toBeUndefined() + }) + + it('disposing a session-less bridge is idempotent', async () => { + harness = await makeBridgeHarness() + await Promise.all([harness.acpFiber.dispose(), harness.acpFiber.dispose()]) + expect(harness.ctx.agents.list()).toHaveLength(0) + }) +}) diff --git a/packages/acp/acp/tests/edges.spec.ts b/packages/acp/acp/tests/edges.spec.ts new file mode 100644 index 0000000000..1a16647d01 --- /dev/null +++ b/packages/acp/acp/tests/edges.spec.ts @@ -0,0 +1,69 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' +import { CallId, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' +import { makeBridgeHarness, textResponse, type BridgeHarness } from './harness.ts' + +function toolCallResponse(): StreamChunk[] { + return [ + { type: 'block-start', index: 0, blockType: 'tool-call' }, + { type: 'tool-call-delta', index: 0, id: CallId('call-1'), name: 'echo', argumentsDelta: '{}' }, + { type: 'block-end', index: 0, block: { type: 'tool-call', id: CallId('call-1'), name: 'echo', arguments: '{}' } }, + { type: 'finish', reason: { kind: 'tool-calls' } }, + ] +} + +describe('ACP automation output boundary', () => { + let harness: BridgeHarness | undefined + + afterEach(async () => { + await harness?.dispose() + harness = undefined + }) + + it('does not emit tool, terminal, plan, title, or reasoning presentation updates', async () => { + harness = await makeBridgeHarness({ script: [toolCallResponse(), textResponse('done')] }) + harness.ctx.tools.register(defineContentToolFixture({ + name: 'echo', + description: 'Return a deterministic result.', + parameters: {}, + execute: () => Promise.resolve([{ type: 'text', text: 'tool result' }]), + })) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) + + await vi.waitFor(() => { expect(harness!.updates).toHaveLength(1) }) + expect(harness.updates).toEqual([{ + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'done' }, + }]) + }) + + it('ignores events from agents the bridge does not own', async () => { + harness = await makeBridgeHarness({ script: [textResponse('foreign')] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const { agent } = await harness.ctx.agents.create({ + sessionId: SessionId('foreign'), + agentOptions: { provider: 'mock', model: 'mock' }, + }) + agent.followup([{ type: 'text', text: 'go' }]) + await agent.whenIdle() + expect(harness.updates).toHaveLength(0) + }) + + // `session/update` is a JSON-RPC notification, so a client-side handler + // failure never reaches the bridge; this pins that the prompt still settles + // normally with such a client. The bridge's own write-failure guard is + // transport-level and documented untestable at `notify`. + it('settles the prompt normally when the client rejects update notifications', async () => { + harness = await makeBridgeHarness({ script: [textResponse('answer')] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + harness.onSessionUpdateError = () => {} + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })) + .resolves.toEqual({ stopReason: 'end_turn' }) + }) +}) diff --git a/packages/acp/acp/tests/harness.ts b/packages/acp/acp/tests/harness.ts new file mode 100644 index 0000000000..aa3564ea8a --- /dev/null +++ b/packages/acp/acp/tests/harness.ts @@ -0,0 +1,174 @@ +/** In-memory ACP transport fixture over the real agent factory and loop. */ + +import { Context } from 'cordis' +import { + ClientSideConnection, + ndJsonStream, + type Agent as AcpAgent, + type Client, + type RequestPermissionRequest, + type RequestPermissionResponse, + type SessionNotification, + type Stream, +} from '@agentclientprotocol/sdk' +import { type GenerateOptions, LlmAdapter, type StreamChunk } from '@deepseek-ai/dsh-llm' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import * as AcpPlugin from '../src/index.ts' +import type { AcpConfig } from '../src/index.ts' + +/** Scripted adapter for protocol tests. */ +class MockAdapter extends LlmAdapter { + readonly requests: GenerateOptions[] = [] + + constructor(private readonly script: (StreamChunk[] | 'hang')[]) { + super() + } + + override providerInfo(provider: string) { + if (provider !== 'mock') throw new Error(`MockAdapter: unknown provider ${provider}`) + return { id: 'mock', name: 'Mock' } + } + + override listModels(provider: string) { + return Promise.resolve(provider === 'mock' ? [{ provider: 'mock', id: 'mock', name: 'Mock' }] : []) + } + + async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> { + this.requests.push(options) + const entry = this.script.shift() + if (entry === undefined) throw new Error('MockAdapter: script exhausted') + if (entry === 'hang') { + yield { type: 'block-start', index: 0, blockType: 'text' } + yield { type: 'text-delta', index: 0, text: 'partial' } + await new Promise<void>((_resolve, reject) => { + if (options.signal?.aborted) { + reject(new Error('aborted')) + return + } + options.signal?.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true }) + }) + return + } + for (const chunk of entry) { + if (options.signal?.aborted) throw new Error('aborted') + yield chunk + } + } +} + +/** Scripted text response ending in a clean stop. */ +export function textResponse(text: string): StreamChunk[] { + return [ + { type: 'block-start', index: 0, blockType: 'text' }, + ...Array.from(text, (char): StreamChunk => ({ type: 'text-delta', index: 0, text: char })), + { type: 'block-end', index: 0, block: { type: 'text', text } }, + { type: 'usage', usage: { inputTokens: 5, outputTokens: text.length } }, + { type: 'finish', reason: { kind: 'stop' } }, + ] +} + +/** Scripted response ending at the output-token ceiling. */ +export function maxTokensResponse(text: string): StreamChunk[] { + return [ + { type: 'block-start', index: 0, blockType: 'text' }, + ...Array.from(text, (char): StreamChunk => ({ type: 'text-delta', index: 0, text: char })), + { type: 'block-end', index: 0, block: { type: 'text', text } }, + { type: 'finish', reason: { kind: 'max-tokens' } }, + ] +} + +/** Scripted response that fails after publishing an uncommitted partial chunk. */ +export function errorResponse(message: string): StreamChunk[] { + return [ + { type: 'block-start', index: 0, blockType: 'text' }, + { type: 'text-delta', index: 0, text: 'partial' }, + { type: 'finish', reason: { kind: 'error', failure: { message, code: 'PROVIDER_ERROR' } } }, + ] +} + +export type CapturedUpdate = SessionNotification['update'] + +export interface BridgeHarness { + ctx: Context + client: ClientSideConnection + adapter: MockAdapter + updates: CapturedUpdate[] + sessionUpdates: { sessionId: string; update: CapturedUpdate }[] + permissionRequests: RequestPermissionRequest[] + onPermission: (request: RequestPermissionRequest) => RequestPermissionResponse + onSessionUpdateError: (() => void) | undefined + closeClientTransport: () => Promise<void> + abortClientTransport: () => Promise<void> + acpFiber: Awaited<ReturnType<Context['plugin']>> + /** The AgentLoop fiber, so a test can reload the loop out from under the bridge. */ + loopFiber: Awaited<ReturnType<Context['plugin']>> + dispose: () => Promise<void> +} + +type AcpConfigOverrides = { [K in keyof AcpConfig]?: AcpConfig[K] | undefined } + +/** Build the bridge and a connected SDK client over cross-wired byte streams. */ +export async function makeBridgeHarness(options: { + script?: (StreamChunk[] | 'hang')[] + config?: AcpConfigOverrides + persona?: string +} = {}): Promise<BridgeHarness> { + const adapter = new MockAdapter(options.script ?? []) + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx, { systemPrompt: { persona: options.persona ?? '' } }) + const loopFiber = await ctx.plugin(AgentLoop, { agents: [] }) + ctx.llm.registerAdapter(['mock'], adapter) + + const agentToClient = new TransformStream<Uint8Array, Uint8Array>() + const clientToAgent = new TransformStream<Uint8Array, Uint8Array>() + const clientToAgentWriter = clientToAgent.writable.getWriter() + const clientOutput = new WritableStream<Uint8Array>({ + write: chunk => clientToAgentWriter.write(chunk), + }) + const agentStream: Stream = ndJsonStream(agentToClient.writable, clientToAgent.readable) + const clientStream: Stream = ndJsonStream(clientOutput, agentToClient.readable) + + const updates: CapturedUpdate[] = [] + const sessionUpdates: { sessionId: string; update: CapturedUpdate }[] = [] + const permissionRequests: RequestPermissionRequest[] = [] + const harness: BridgeHarness = { + ctx, + adapter, + updates, + sessionUpdates, + permissionRequests, + onPermission: () => ({ outcome: { outcome: 'cancelled' } }), + onSessionUpdateError: undefined, + client: undefined as unknown as ClientSideConnection, + acpFiber: undefined as unknown as BridgeHarness['acpFiber'], + loopFiber, + closeClientTransport: async () => { await clientToAgentWriter.close() }, + abortClientTransport: async () => { await clientToAgentWriter.abort(new Error('client transport failed')) }, + dispose: async () => { await ctx.fiber.dispose() }, + } + + const makeClient = (_agent: AcpAgent): Client => ({ + sessionUpdate(params: SessionNotification): Promise<void> { + updates.push(params.update) + sessionUpdates.push({ sessionId: params.sessionId, update: params.update }) + if (harness.onSessionUpdateError !== undefined) return Promise.reject(new Error('client update rejected')) + return Promise.resolve() + }, + requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse> { + permissionRequests.push(params) + return Promise.resolve(harness.onPermission(params)) + }, + }) + + const config = { stream: agentStream, ...options.config } as AcpConfig + if (!(options.config && 'provider' in options.config)) config.provider = 'mock' + if (!(options.config && 'model' in options.config)) config.model = 'mock' + harness.acpFiber = await ctx.plugin({ + name: 'acp-test', + inject: [...AcpPlugin.inject], + apply: (inner: Context) => { AcpPlugin.apply(inner, config) }, + }) + harness.client = new ClientSideConnection(makeClient, clientStream) + return harness +} diff --git a/packages/acp/acp/tests/multi-session.spec.ts b/packages/acp/acp/tests/multi-session.spec.ts new file mode 100644 index 0000000000..7619ec3b69 --- /dev/null +++ b/packages/acp/acp/tests/multi-session.spec.ts @@ -0,0 +1,95 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' +import { SessionId } from '@deepseek-ai/dsh-session' +import { makeBridgeHarness, textResponse, type BridgeHarness, type CapturedUpdate } from './harness.ts' + +function messageTextFor( + updates: { sessionId: string; update: CapturedUpdate }[], + sessionId: string, +): string { + return updates.flatMap(({ sessionId: owner, update }) => ( + owner === sessionId && update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text' + ? [update.content.text] + : [] + )).join('') +} + +describe('ACP multi-session isolation', () => { + let harness: BridgeHarness | undefined + + afterEach(async () => { + await harness?.dispose() + harness = undefined + }) + + it('demultiplexes concurrent answers by session id', async () => { + harness = await makeBridgeHarness({ script: [textResponse('answer-A'), textResponse('answer-B')] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId + const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId + + const [resultA, resultB] = await Promise.all([ + harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'go A' }] }), + harness.client.prompt({ sessionId: b, prompt: [{ type: 'text', text: 'go B' }] }), + ]) + expect(resultA.stopReason).toBe('end_turn') + expect(resultB.stopReason).toBe('end_turn') + await vi.waitFor(() => { + expect(messageTextFor(harness!.sessionUpdates, a)).toBe('answer-A') + expect(messageTextFor(harness!.sessionUpdates, b)).toBe('answer-B') + }) + }) + + it('cancels one session without affecting another', async () => { + harness = await makeBridgeHarness({ script: ['hang', textResponse('B done')] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId + const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId + + const pendingA = harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'hang A' }] }) + await vi.waitFor(() => { expect(harness!.ctx.agents.get(SessionId(a))?.status).toBe('running') }) + await harness.client.cancel({ sessionId: a }) + await expect(pendingA).resolves.toEqual({ stopReason: 'cancelled' }) + await expect(harness.client.prompt({ sessionId: b, prompt: [{ type: 'text', text: 'go B' }] })) + .resolves.toEqual({ stopReason: 'end_turn' }) + await vi.waitFor(() => { expect(messageTextFor(harness!.sessionUpdates, b)).toBe('B done') }) + }) + + it('enforces one in-flight prompt independently for each session', async () => { + harness = await makeBridgeHarness({ script: ['hang', 'hang'] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId + const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId + const pendingA = harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'A' }] }) + const pendingB = harness.client.prompt({ sessionId: b, prompt: [{ type: 'text', text: 'B' }] }) + await vi.waitFor(() => { + expect(harness!.ctx.agents.get(SessionId(a))?.status).toBe('running') + expect(harness!.ctx.agents.get(SessionId(b))?.status).toBe('running') + }) + + await expect(harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'again' }] })) + .rejects.toThrow(/already in flight/) + await Promise.all([harness.client.cancel({ sessionId: a }), harness.client.cancel({ sessionId: b })]) + await expect(pendingA).resolves.toEqual({ stopReason: 'cancelled' }) + await expect(pendingB).resolves.toEqual({ stopReason: 'cancelled' }) + }) + + it('drains every live session on bridge disposal', async () => { + harness = await makeBridgeHarness({ script: ['hang', 'hang'] }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId + const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId + const agentA = harness.ctx.agents.get(SessionId(a))! + const agentB = harness.ctx.agents.get(SessionId(b))! + void harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'A' }] }).catch(() => {}) + void harness.client.prompt({ sessionId: b, prompt: [{ type: 'text', text: 'B' }] }).catch(() => {}) + await vi.waitFor(() => { + expect(agentA.status).toBe('running') + expect(agentB.status).toBe('running') + }) + + await harness.acpFiber.dispose() + expect(harness.ctx.agents.get(SessionId(a))).toBeUndefined() + expect(harness.ctx.agents.get(SessionId(b))).toBeUndefined() + }) +}) diff --git a/packages/acp/acp/tests/turns.spec.ts b/packages/acp/acp/tests/turns.spec.ts new file mode 100644 index 0000000000..cf081d1f2a --- /dev/null +++ b/packages/acp/acp/tests/turns.spec.ts @@ -0,0 +1,169 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' +import { SessionId } from '@deepseek-ai/dsh-session' +import { + errorResponse, + makeBridgeHarness, + maxTokensResponse, + textResponse, + type BridgeHarness, +} from './harness.ts' + +async function newSession(harness: BridgeHarness): Promise<string> { + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + return (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId +} + +function messageText(harness: BridgeHarness): string { + return harness.updates.flatMap(update => ( + update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text' + ? [update.content.text] + : [] + )).join('') +} + +describe('ACP prompt lifecycle', () => { + let harness: BridgeHarness | undefined + + afterEach(async () => { + await harness?.dispose() + harness = undefined + }) + + it('maps a max-token turn without losing its committed text', async () => { + harness = await makeBridgeHarness({ script: [maxTokensResponse('cut off')] }) + const sessionId = await newSession(harness) + const result = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) + expect(result.stopReason).toBe('max_tokens') + await vi.waitFor(() => { expect(messageText(harness!)).toBe('cut off') }) + }) + + it('rejects a failed turn and never publishes its partial chunks', async () => { + harness = await makeBridgeHarness({ script: [errorResponse('provider boom')] }) + const sessionId = await newSession(harness) + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })) + .rejects.toThrow(/turn failed: provider boom/) + expect(messageText(harness)).toBe('') + }) + + it('rejects an ordinary plugin failure through the same prompt boundary', async () => { + harness = await makeBridgeHarness({ script: [textResponse('must not run')] }) + harness.ctx.on('agent/pre-step', () => { throw new Error('plugin pre-step failed') }) + const sessionId = await newSession(harness) + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })) + .rejects.toThrow(/turn failed: plugin pre-step failed/) + }) + + it('settles even when an earlier turn observer throws', async () => { + harness = await makeBridgeHarness({ script: [textResponse('answer')] }) + harness.ctx.on('session/event', (_session, event) => { + if (event.type === 'turn/start' || event.type === 'turn/end') throw new Error('peer listener boom') + }, { prepend: true }) + const sessionId = await newSession(harness) + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })) + .resolves.toEqual({ stopReason: 'end_turn' }) + }) + + it('ignores an injection turn while correlating the owning message turn', async () => { + harness = await makeBridgeHarness({ script: [textResponse('real answer')] }) + const sessionId = await newSession(harness) + const agent = harness.ctx.agents.get(SessionId(sessionId))! + let injected = false + harness.ctx.on('agent/inbox/enqueue', (subject) => { + if (subject === agent && !injected) { + injected = true + agent.inject([{ type: 'text', text: 'context' }], { source: { kind: 'plugin', plugin: 'test' } }) + } + }) + + const result = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) + expect(result.stopReason).toBe('end_turn') + await vi.waitFor(() => { expect(messageText(harness!)).toBe('real answer') }) + }) + + it('ignores an autonomous message turn while correlating the client turn', async () => { + harness = await makeBridgeHarness({ script: ['hang'] }) + const sessionId = await newSession(harness) + const agent = harness.ctx.agents.get(SessionId(sessionId))! + let inserted = false + harness.ctx.on('agent/inbox/enqueue', (subject, message) => { + if (subject !== agent || message.source.kind !== 'user' || inserted) return + inserted = true + const source = { kind: 'plugin', plugin: 'test' } as const + agent.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source } }) + agent.session.append('user/message', { + content: [{ type: 'text', text: 'autonomous work' }], + source, + }, { surfaceOp: 'append' }) + agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + }) + + let settled = false + const prompt = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) + .finally(() => { settled = true }) + await vi.waitFor(() => { + expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2) + }) + expect(settled).toBe(false) + await harness.client.cancel({ sessionId }) + await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' }) + }) + + it('frees the prompt slot when the agent rejects the send synchronously', async () => { + harness = await makeBridgeHarness({ script: [] }) + const sessionId = await newSession(harness) + // Reload the loop out from under the bridge: its agents dispose while the + // bridge record survives, so the next send() throws synchronously. + await harness.loopFiber.dispose() + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'one' }] })) + .rejects.toThrow(/prompt was not queued/) + // The failed prompt must not wedge the session's single prompt slot. + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'two' }] })) + .rejects.toThrow(/prompt was not queued/) + }) + + it('permits only one in-flight prompt per session', async () => { + harness = await makeBridgeHarness({ script: ['hang'] }) + const sessionId = await newSession(harness) + const first = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'one' }] }) + await vi.waitFor(() => { expect(harness!.ctx.agents.get(SessionId(sessionId))?.status).toBe('running') }) + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'two' }] })) + .rejects.toThrow(/already in flight/) + await harness.client.cancel({ sessionId }) + await expect(first).resolves.toEqual({ stopReason: 'cancelled' }) + }) + + it('cancels a running turn and records the aborted outcome', async () => { + harness = await makeBridgeHarness({ script: ['hang'] }) + const sessionId = await newSession(harness) + const prompt = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) + const agent = harness.ctx.agents.get(SessionId(sessionId))! + await vi.waitFor(() => { expect(agent.status).toBe('running') }) + await harness.client.cancel({ sessionId }) + await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' }) + await agent.whenIdle() + expect(agent.session.events.findLast(event => event.type === 'turn/end')?.data.reason).toEqual({ kind: 'aborted' }) + }) + + it('an idle cancel does not affect the following prompt', async () => { + harness = await makeBridgeHarness({ script: [textResponse('answer')] }) + const sessionId = await newSession(harness) + await harness.client.cancel({ sessionId }) + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })) + .resolves.toEqual({ stopReason: 'end_turn' }) + await vi.waitFor(() => { expect(messageText(harness!)).toBe('answer') }) + }) + + it('a late end from a cancelled turn cannot settle the next prompt', async () => { + harness = await makeBridgeHarness({ script: ['hang', textResponse('next')] }) + const sessionId = await newSession(harness) + const first = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'one' }] }) + await vi.waitFor(() => { expect(harness!.ctx.agents.get(SessionId(sessionId))?.status).toBe('running') }) + await harness.client.cancel({ sessionId }) + await expect(first).resolves.toEqual({ stopReason: 'cancelled' }) + + await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'two' }] })) + .resolves.toEqual({ stopReason: 'end_turn' }) + await vi.waitFor(() => { expect(messageText(harness!)).toBe('next') }) + }) +}) diff --git a/packages/acp/acp/tsconfig.json b/packages/acp/acp/tsconfig.json new file mode 100644 index 0000000000..3109e0eea8 --- /dev/null +++ b/packages/acp/acp/tsconfig.json @@ -0,0 +1,33 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/session" + }, + { + "path": "../../core/agent" + }, + { + "path": "../../ui/user-approval" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/client/connection/package.json b/packages/client/connection/package.json index 778b431b71..c26cafb143 100644 --- a/packages/client/connection/package.json +++ b/packages/client/connection/package.json @@ -43,10 +43,12 @@ "src" ], "peerDependencies": { + "@deepseek-ai/dsh-host-webserver": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", "cordis": "^4.0.0-rc.7" }, "devDependencies": { + "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "cordis": "^4.0.0-rc.7" } diff --git a/packages/client/connection/src/api-path.ts b/packages/client/connection/src/api-path.ts new file mode 100644 index 0000000000..30e91522a2 --- /dev/null +++ b/packages/client/connection/src/api-path.ts @@ -0,0 +1,8 @@ +/** + * The /api URL prefix — single source for both halves of the web transport. + * The node half registers this prefix on the web server; browser-side path + * literals currently live in the apiproxy client layer (out of scope here). + */ + +/** Route prefix owning every api request (`/api` and `/api/<anything>`). */ +export const API_PATH = '/api' diff --git a/packages/client/connection/src/http-bridge.ts b/packages/client/connection/src/http-bridge.ts new file mode 100644 index 0000000000..319d3e0b0b --- /dev/null +++ b/packages/client/connection/src/http-bridge.ts @@ -0,0 +1,59 @@ +/** + * node:http ↔ WHATWG fetch bridge for the /api transport (host side of the + * web carrier; the fetch-shaped handler itself is transport-agnostic). + */ + +import type { IncomingMessage, ServerResponse } from 'node:http' + +/** + * Bridge one node:http request to the fetch-shaped handler (client close + * aborts; SSE bodies stream out chunk by chunk). + * @param req - incoming node:http request (fully read before dispatch). + * @param res - node:http response the bridge writes and owns to completion. + * @param apiHandler - fetch-shaped API carrier the request is dispatched to. + */ +export async function bridge(req: IncomingMessage, res: ServerResponse, apiHandler: { fetch: typeof fetch }): Promise<void> { + const abort = new AbortController() + // Client-disconnect detection MUST hang off the response, not the request: + // since Node 16, IncomingMessage 'close' fires as soon as the request body is + // fully consumed (immediately for a bodyless GET), which would abort every SSE + // stream right after open. ServerResponse 'close' fires on connection teardown; + // writableEnded distinguishes a normal end() from the client going away. + res.on('close', () => { + if (!res.writableEnded) abort.abort() + }) + const chunks: Buffer[] = [] + for await (const chunk of req) chunks.push(chunk as Buffer) + /* v8 ignore next 3 -- `??` arms: node:http always sets url/method on server + requests; the fields are only optional on the client-side IncomingMessage type */ + const request = new Request(new URL(req.url ?? '/', 'http://dsh.internal'), { + method: req.method ?? 'GET', + headers: Object.fromEntries(Object.entries(req.headers).filter(([, v]) => typeof v === 'string') as [string, string][]), + ...chunks.length > 0 ? { body: Buffer.concat(chunks) } : {}, + signal: abort.signal, + }) + const response = await apiHandler.fetch(request) + res.writeHead(response.status, Object.fromEntries(response.headers.entries())) + if (response.body === null) { + res.end() + return + } + for await (const chunk of response.body) { + // Backpressure: a false return means the socket buffer is full — wait for drain + // instead of buffering unboundedly (slow/suspended SSE consumers). 'close' also + // resolves so a mid-wait disconnect can't park this loop forever; the close + // handler above aborts the handler stream, which then ends the iteration. + if (!res.write(chunk)) { + await new Promise<void>((resolve) => { + const done = (): void => { + res.off('drain', done) + res.off('close', done) + resolve() + } + res.once('drain', done) + res.once('close', done) + }) + } + } + res.end() +} diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index 313db07225..61d718b618 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -1,10 +1,36 @@ /** - * Connection plugin, node half. The package IS a dshClient plugin: the wire - * consumer layer lives in its client half in full (src/client/ — contract: - * api-contracts v3 section 3, inventory §3.2); consumers import the /client - * subpath. The empty apply exists so the plugin appears in the host Loader - * (lifecycle governance + dshClient discovery). + * Connection plugin, node half: the host end of the web transport. Registers + * the /api prefix route on the web server and bridges node:http requests to + * the transport-agnostic fetch-shaped api handler. The wire consumer layer + * lives in the client half (src/client/ — contract: api-contracts v3 + * section 3); consumers import the /client subpath. */ +import type { Context } from 'cordis' +// Type-only route import; it also carries the httpServer Context merge. +import type { WebRoute } from '@deepseek-ai/dsh-host-webserver' +import { toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy' +import { API_PATH } from './api-path.ts' +import { bridge } from './http-bridge.ts' -/** Host plugin body — no host-side behavior for the connection plugin. */ -export function apply(_ctx: unknown): void {} +export { API_PATH } from './api-path.ts' + +/** Cordis plugin name. */ +export const name = 'client-connection' + +/** Required services: the route registry and the api gateway. */ +export const inject = ['httpServer', 'apiProxy'] + +/** + * Mount the /api transport: wrap the api gateway into a fetch handler and + * serve it under the /api prefix. + * @param ctx - host plugin context carrying httpServer and apiProxy. + */ +export function apply(ctx: Context): void { + const apiHandler = toFetchHandler(ctx.apiProxy) + const route: WebRoute = { + kind: 'prefix', + path: API_PATH, + handler: (req, res) => bridge(req, res, apiHandler), + } + ctx.effect(() => ctx.httpServer.register(route), 'client-connection: /api route') +} diff --git a/packages/client/connection/src/invariant.ts b/packages/client/connection/src/invariant.ts index df16e00fd4..1112a4e638 100644 --- a/packages/client/connection/src/invariant.ts +++ b/packages/client/connection/src/invariant.ts @@ -15,10 +15,11 @@ export const name = 'client-connection-invariant' export const inject = ['invariants'] /** - * No runtime invariant: the pure wire layer emits no cordis events and owns no + * No runtime invariant: the wire layer emits no cordis events and owns no * mutable cross-plugin relation — stream/reconnect sequencing is exercised - * directly by its behavior specs, and rpcId round-trip discipline is owned by - * the apiproxy contract layer. + * directly by its behavior specs, rpcId round-trip discipline is owned by the + * apiproxy contract layer, and the node half's single route registration's + * register/dispose symmetry is audited by the webserver package's invariant. */ const install: InvariantInstaller = () => {} diff --git a/packages/client/connection/tests/node-half.spec.ts b/packages/client/connection/tests/node-half.spec.ts index efba1b0445..e9e880cfb4 100644 --- a/packages/client/connection/tests/node-half.spec.ts +++ b/packages/client/connection/tests/node-half.spec.ts @@ -1,10 +1,33 @@ -/** Node half: the empty host apply (Loader governance + dshClient discovery placeholder). */ +/** Node half: registers the /api prefix route bridging to the api gateway. */ +import { Context } from 'cordis' import { describe, expect, it } from 'vitest' -import { apply } from '../src/index.ts' +import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api' +import type { HttpServerService, WebRoute } from '@deepseek-ai/dsh-host-webserver' +import { API_PATH, apply, inject } from '../src/index.ts' -describe('node half', () => { - it('apply is a no-op host placeholder', () => { - apply(undefined) - expect(true).toBe(true) // reaching here without throw is the contract +describe('connection node half', () => { + it('registers the /api prefix route and removes it with the fiber', async () => { + const ctx = new Context() + const routes: WebRoute[] = [] + // Structural fake: the plugin only touches register(); the service class + // carries private state a literal cannot (and need not) reproduce. + const httpServer: Pick<HttpServerService, 'register' | 'tapIndex' | 'port'> = { + register(route) { + routes.push(route) + return () => { routes.splice(routes.indexOf(route), 1) } + }, + tapIndex: () => () => {}, + port: 0, + } + ctx.provide('httpServer', httpServer as HttpServerService) + ctx.provide('apiProxy', {} as unknown as ApiProxy) + + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(routes).toHaveLength(1) + expect(routes[0]).toMatchObject({ kind: 'prefix', path: API_PATH }) + + await fiber.dispose() + expect(routes).toHaveLength(0) }) }) diff --git a/packages/client/connection/tsconfig.json b/packages/client/connection/tsconfig.json index 8b0357cf97..97d020dc53 100644 --- a/packages/client/connection/tsconfig.json +++ b/packages/client/connection/tsconfig.json @@ -2,7 +2,8 @@ "extends": "../../../tsconfig.base.client.json", "compilerOptions": { "rootDir": "src", - "outDir": "lib/types" + "outDir": "lib/types", + "types": ["node"] }, "include": [ "src" @@ -20,6 +21,9 @@ { "path": "../../host/apiproxy" }, + { + "path": "../../host/webserver" + }, { "path": "../../ui/user-approval" }, diff --git a/packages/client/hmr/README.md b/packages/client/hmr/README.md index f6fcd44dba..fc262bb086 100644 --- a/packages/client/hmr/README.md +++ b/packages/client/hmr/README.md @@ -2,7 +2,7 @@ Hot reload for fetch-arrival client plugins. A static-arrival entry composed only into `--dev` graphs (`dsh web --dev`); production graphs omit the row, so the shell-bundled code stays inert. -The plugin subscribes to the webserver's system SSE channel (`GET /plugins/events`) and reloads one plugin per `rebuilt` frame, serialized through a queue (the bundle handoff slot is single). The sequence per frame — `prefetch` (fetch the new bundle before touching anything), `invalidate`, `registry.delete` (before the fiber: a bare fiber dispose trips the vendored Loader's self-dispose branch, which would mark the entry disabled), drain the old fiber, delete `entry.fiber`, remove owned `<style data-plugin>` tags, `entry.refresh()` re-imports and remounts, `fiber.await()` rethrows startup failures loud. Dependents reload through cordis itself: a fiber's activation epoch strings its service providers' uids, so replacing a provider's fiber cascades every dependent with zero client-side graph analysis. Rebuild detection lives on the webserver: in dev mode it stat-polls each plugin's built `lib/client.js` (`fs.watchFile`) and broadcasts the `rebuilt` frame when the bundle's rev changes, so any tsdown watch process producing the bundle triggers HMR with no builder→host channel. +The browser half subscribes to the system SSE channel (`GET /plugins/events`) and reloads one plugin per `rebuilt` frame, serialized through a queue (the bundle handoff slot is single). The sequence per frame — `prefetch` (fetch the new bundle before touching anything), `invalidate`, `registry.delete` (before the fiber: a bare fiber dispose trips the vendored Loader's self-dispose branch, which would mark the entry disabled), drain the old fiber, delete `entry.fiber`, remove owned `<style data-plugin>` tags, `entry.refresh()` re-imports and remounts, `fiber.await()` rethrows startup failures loud. Dependents reload through cordis itself: a fiber's activation epoch strings its service providers' uids, so replacing a provider's fiber cascades every dependent with zero client-side graph analysis. The node half detects rebuilds with one interval that stat-polls each graph bundle from a synchronous baseline, immediately re-hashes after adding a row, retains missing rows as dirty, and broadcasts only real rev changes; any tsdown watch process producing the bundle therefore triggers HMR with no builder→host channel. ## Model Experience diff --git a/packages/client/hmr/package.json b/packages/client/hmr/package.json index 129a7e879a..0773a1fce5 100644 --- a/packages/client/hmr/package.json +++ b/packages/client/hmr/package.json @@ -28,15 +28,20 @@ "immediately": true }, "license": "BSD-3-Clause", + "dependencies": { + "schemastery": "^3.18.0" + }, "peerDependencies": { "@cordisjs/plugin-loader": "^1.0.0-rc.5", "@deepseek-ai/dsh-client-modules": "^0.0.1", + "@deepseek-ai/dsh-host-webserver": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", "cordis": "^4.0.0-rc.7" }, "devDependencies": { "@cordisjs/plugin-loader": "workspace:^", "@deepseek-ai/dsh-client-modules": "workspace:^", + "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "cordis": "^4.0.0-rc.7" }, diff --git a/packages/client/hmr/src/client/index.ts b/packages/client/hmr/src/client/index.ts index 21df48b561..eae29e8db3 100644 --- a/packages/client/hmr/src/client/index.ts +++ b/packages/client/hmr/src/client/index.ts @@ -64,20 +64,11 @@ */ import type { Context } from 'cordis' import type { Entry, Loader } from '@cordisjs/plugin-loader' -import type { WebBootGraph } from '@deepseek-ai/dsh-client-modules' +import type { PluginsEventFrame } from '../events.ts' +import { EVENTS_ENDPOINT } from '../events.ts' -/** - * Frames on the `GET /plugins/events` system SSE channel (owned host-side by - * dsh-host-webserver's PluginEventFrame). Mirrored here because this is a - * wire boundary: frames arrive as JSON text and are validated at the parse - * point, not shared as a same-process typed seam. - */ -export type PluginsEventFrame = - | { type: 'graph'; graph: WebBootGraph } - | { type: 'rebuilt'; id: string; rev: string } - -/** System SSE endpoint pushing graph/rebuilt frames (wire protocol constant). */ -export const EVENTS_ENDPOINT = '/plugins/events' +export type { PluginsEventFrame } from '../events.ts' +export { EVENTS_ENDPOINT } from '../events.ts' /** Cordis plugin name. */ export const name = 'client-hmr' diff --git a/packages/client/hmr/src/events.ts b/packages/client/hmr/src/events.ts new file mode 100644 index 0000000000..756bd24074 --- /dev/null +++ b/packages/client/hmr/src/events.ts @@ -0,0 +1,16 @@ +/** + * Wire protocol of the `/plugins/events` dev SSE channel — single source for + * both halves of this package. Frames still cross a wire boundary: the + * browser half validates them at its JSON parse point; sharing the type keeps + * the two ends from drifting, not from parsing. + */ + +import type { WebBootGraph } from '@deepseek-ai/dsh-client-modules' + +/** One SSE frame: the full graph on connect, or one rebuilt bundle notice. */ +export type PluginsEventFrame = + | { type: 'graph'; graph: WebBootGraph } + | { type: 'rebuilt'; id: string; rev: string } + +/** System SSE endpoint pushing graph/rebuilt frames (wire protocol constant). */ +export const EVENTS_ENDPOINT = '/plugins/events' diff --git a/packages/client/hmr/src/index.ts b/packages/client/hmr/src/index.ts index cca3c0ddac..848b546b13 100644 --- a/packages/client/hmr/src/index.ts +++ b/packages/client/hmr/src/index.ts @@ -1,9 +1,189 @@ /** - * HMR plugin, node half. The package IS a dshClient plugin (dev-only row in - * the host graph): the reload driver lives in its client half in full - * (src/client/); the empty apply exists so the plugin appears in the host - * Loader (lifecycle governance + dshClient discovery). + * HMR plugin, node half: the host end of the dev reload chain. One interval + * stat-polls every graph row's client bundle (polling by design: network + * mounts deliver no inotify events), reports content changes through + * `clientModuleHost.rebuilt(id)`, and serves the `/plugins/events` SSE channel + * broadcasting graph/rebuilt frames to the browser half (src/client/). + * Dev-only row: prod compositions never mount this plugin. */ +import { statSync } from 'node:fs' +import type { ServerResponse } from 'node:http' +import type { Context } from 'cordis' +import z from 'schemastery' +// Empty type imports carry the clientModuleHost/httpServer Context merges. +import type {} from '@deepseek-ai/dsh-client-modules' +import type {} from '@deepseek-ai/dsh-host-webserver' +import type { PluginsEventFrame } from './events.ts' +import { EVENTS_ENDPOINT } from './events.ts' -/** Host plugin body — no host-side behavior for the HMR plugin. */ -export function apply(): void {} +export type { PluginsEventFrame } from './events.ts' +export { EVENTS_ENDPOINT } from './events.ts' + +/** Cordis plugin name. */ +export const name = 'client-hmr' + +/** Required services: the web plugin table and the route registry. */ +export const inject = ['clientModuleHost', 'httpServer'] + +/** Plugin config, validated by the same-named schemastery schema. */ +export interface Config { + /** Bundle stat-poll interval in milliseconds (default 500, the build-side watcher's polling default). */ + pollIntervalMs?: number +} + +export const Config: z<Config> = z.object({ + pollIntervalMs: z.number().step(1).min(1).default(500), +}) + +/** Serialize one frame as an SSE data line. */ +function sseData(frame: PluginsEventFrame): string { + return `data: ${JSON.stringify(frame)}\n\n` +} + +interface WatchedBundle { + path: string + mtimeMs: number + size: number + dirty: boolean +} + +/** + * Mount the dev chain: bundle watches, rebuilt reporting, and the SSE channel. + * @param ctx - host plugin context carrying clientModuleHost and httpServer. + * @param config - validated {@link Config}. + */ +export function apply(ctx: Context, config: Config): void { + // schemastery's .default() guarantees the field is set after validation. + const pollIntervalMs = config.pollIntervalMs as number + + // --- bundle watch: one HMR-owned stat poll ------------------------------ + const watched = new Map<string, WatchedBundle>() + + const rehash = (id: string, watch: WatchedBundle, current: { mtimeMs: number; size: number }): void => { + try { + // rebuilt() re-hashes; an unchanged hash stays silent (clientModuleHost + // fires onRebuilt only on a real rev change). + ctx.clientModuleHost.rebuilt(id) + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code === 'ENOENT') { + watch.dirty = true + return + } + ctx.logger.warn(error) + } + watch.mtimeMs = current.mtimeMs + watch.size = current.size + watch.dirty = false + } + + const watchRow = (id: string, path: string): void => { + let baseline: { mtimeMs: number; size: number } + try { + baseline = statSync(path) + } catch (error) { + watched.set(id, { path, mtimeMs: 0, size: 0, dirty: true }) + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') ctx.logger.warn(error) + return + } + const watch = { path, mtimeMs: baseline.mtimeMs, size: baseline.size, dirty: false } + watched.set(id, watch) + // The module host hashed before publishing the graph. Re-hash immediately + // after capturing this baseline so a write in between cannot become an + // already-current baseline paired with a stale graph rev. + rehash(id, watch, baseline) + } + + const pollWatches = (): void => { + for (const [id, watch] of watched) { + let current: { mtimeMs: number; size: number } + try { + current = statSync(watch.path) + } catch (error) { + watch.dirty = true + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') ctx.logger.warn(error) + continue + } + if (!watch.dirty && current.mtimeMs === watch.mtimeMs && current.size === watch.size) continue + // Stat-before-hash preserves a detectable older baseline for writes that + // land during hashing. Repeated stat changes heal a torn read. + rehash(id, watch, current) + } + } + + // Diff the watch set against the current graph: drop watches for removed + // rows (or rows whose bundle path moved), add watches for new rows. + const syncWatches = (): void => { + const rows = new Map<string, string>() + for (const row of ctx.clientModuleHost.graph().entries) { + const path = ctx.clientModuleHost.clientPath(row.id) + if (path !== undefined) rows.set(row.id, path) + } + for (const [id, watch] of watched) { + if (rows.get(id) === watch.path) continue + watched.delete(id) + } + for (const [id, path] of rows) { + if (!watched.has(id)) watchRow(id, path) + } + } + + ctx.effect(() => { + // Initial sync covers rows already in the graph; the subscription covers + // rows arriving later (boot-window activations, including this plugin's + // own row — no self-exemption, a modules/hmr rebuild rides the same chain). + syncWatches() + const unsubscribe = ctx.clientModuleHost.onGraphChanged(syncWatches) + const timer = setInterval(pollWatches, pollIntervalMs) + timer.unref() + return () => { + unsubscribe() + clearInterval(timer) + watched.clear() + } + }, 'client-hmr: bundle watches') + + // --- /plugins/events SSE channel ---------------------------------------- + const connections = new Set<ServerResponse>() + + const connect = (res: ServerResponse): void => { + res.writeHead(200, { + 'content-type': 'text/event-stream', + 'cache-control': 'no-cache', + 'connection': 'keep-alive', + }) + // Comment line on open so clients/proxies see a live channel even when + // no rebuild ever happens; EventSource frame parsing skips it naturally. + res.write(': connected\n\n') + res.write(sseData({ type: 'graph', graph: ctx.clientModuleHost.graph() })) + connections.add(res) + res.on('close', () => { connections.delete(res) }) + } + + ctx.effect(() => { + const disposeRoute = ctx.httpServer.register({ + kind: 'exact', + path: EVENTS_ENDPOINT, + handler: (req, res) => { + // Named routes match ahead of the carrier's method gate; keep the old + // global 405 semantics for non-GET hits on this endpoint. + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405) + res.end() + return + } + connect(res) + }, + }) + const unsubscribe = ctx.clientModuleHost.onRebuilt((id, rev) => { + const line = sseData({ type: 'rebuilt', id, rev }) + for (const res of connections) res.write(line) + }) + return () => { + unsubscribe() + disposeRoute() + for (const res of connections) res.destroy() + connections.clear() + } + }, 'client-hmr: /plugins/events channel') +} diff --git a/packages/client/hmr/src/invariant.ts b/packages/client/hmr/src/invariant.ts index a4c546c991..6eb962efb9 100644 --- a/packages/client/hmr/src/invariant.ts +++ b/packages/client/hmr/src/invariant.ts @@ -3,8 +3,7 @@ * @module @deepseek-ai/dsh-client-hmr/invariant */ -/* jscpd:ignore-start */ -import type { Context } from 'cordis' +import type { Context, Fiber } from 'cordis' import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' const PACKAGE_NAME = '@deepseek-ai/dsh-client-hmr' @@ -14,14 +13,42 @@ export const name = 'client-hmr-invariant' /** Service required before the companion can reserve package ownership. */ export const inject = ['invariants'] +/** Live fs.watchFile pollers (this package is the composition's only stat-poll user). */ +function statWatchers(): number { + return process.getActiveResourcesInfo().filter(kind => kind === 'StatWatcher').length +} + /** - * No runtime invariant: a dev-only reload driver — it consumes the loader - * entry tree and module cache but owns no events and no cross-plugin mutable - * state; reload correctness (dispose → style removal → re-execute ordering) - * is observable only through the assembled browser runtime, not a host-side - * event relation. + * Owned relation: every bundle stat watcher the node half starts must die + * with its fiber — a surviving poller would keep re-hashing bundles for a + * torn-down dev chain forever. Checked as a baseline delta: the StatWatcher + * count observed at fiber creation must be restored once disposal has drained + * the fiber's effects (`internal/plugin` fires at dispose start; the microtask + * hop lets the disposer queue its unload before `fiber.await()` joins it). + * SSE-connection and listener teardown live inside the same ctx.effect + * disposers, so the watcher count is the relation's observable proxy. */ -const install: InvariantInstaller = () => {} +const install: InvariantInstaller = (ctx, fail) => { + const baselines = new WeakMap<Fiber, number>() + // Async listener by design: emitPluginDisposed awaits-and-logs returned + // promises, so a violation surfaces loudly instead of unhandled. + // eslint-disable-next-line @typescript-eslint/no-misused-promises + ctx.on('internal/plugin', async (fiber) => { + if (fiber.name !== 'client-hmr') return + if (fiber.uid !== null) { + baselines.set(fiber, statWatchers()) + return + } + const baseline = baselines.get(fiber) + if (baseline === undefined) return + await Promise.resolve() + await fiber.await() + const remaining = statWatchers() + if (remaining > baseline) { + fail(`client-hmr fiber disposed but ${remaining - baseline} bundle stat watcher(s) survived teardown`) + } + }, { global: true }) +} /** * Register this package's invariant companion. @@ -30,4 +57,3 @@ const install: InvariantInstaller = () => {} */ export const apply = (ctx: Context): Promise<() => void> => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) -/* jscpd:ignore-end */ diff --git a/packages/client/hmr/tests/node-half.spec.ts b/packages/client/hmr/tests/node-half.spec.ts index e340263b7a..5224061e61 100644 --- a/packages/client/hmr/tests/node-half.spec.ts +++ b/packages/client/hmr/tests/node-half.spec.ts @@ -1,14 +1,204 @@ /** - * Node half of the HMR plugin: an empty apply placeholder (the reload driver - * lives in the client half) whose only contract is mounting and disposing - * cleanly in the host Loader. + * Node half of the HMR plugin: bundle watches follow the graph, stat changes + * report through clientModuleHost.rebuilt, and everything dies with the fiber. */ -import { describe, expect, it } from 'vitest' -import { apply } from '@deepseek-ai/dsh-client-hmr' +import { mkdtempSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from 'cordis' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { WebBootGraph, ClientModuleHostService } from '@deepseek-ai/dsh-client-modules' +import type { WebRoute, HttpServerService } from '@deepseek-ai/dsh-host-webserver' +import { apply, Config, EVENTS_ENDPOINT, inject } from '../src/index.ts' + +const POLL_MS = 20 + +let dir: string + +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'dsh-hmr-')) }) +afterEach(() => { rmSync(dir, { recursive: true, force: true }) }) + +/** + * Controllable clientModuleHost fake over a mutable id → bundle-path table. + * Structural (Pick+cast): the plugin only touches the read/notify surface; + * the service class carries private scan state a literal need not reproduce. + */ +type FakeHost = ClientModuleHostService & { rebuiltCalls: string[]; fireGraphChanged(): void } +interface FakeHostOptions { + beforeGraphRead?: () => void + rebuilt?: (id: string) => string | undefined +} + +function fakeClientModuleHost(rows: Map<string, string>, options: FakeHostOptions = {}): FakeHost { + const graphListeners = new Set<() => void>() + const rebuiltCalls: string[] = [] + const fake: Pick<FakeHost, 'graph' | 'clientPath' | 'rebuilt' | 'onRebuilt' | 'onGraphChanged' | 'rebuiltCalls' | 'fireGraphChanged'> = { + rebuiltCalls, + fireGraphChanged: () => { for (const l of graphListeners) l() }, + graph: (): WebBootGraph => { + options.beforeGraphRead?.() + return { + rev: 'r', + entries: [...rows.keys()].map(id => ({ id, url: `/plugins/${id}/client.js?rev=r`, rev: 'r' })), + } + }, + clientPath: id => rows.get(id), + rebuilt: (id) => { + rebuiltCalls.push(id) + return options.rebuilt?.(id) ?? 'r2' + }, + onRebuilt: () => () => {}, + onGraphChanged: (listener) => { + graphListeners.add(listener) + return () => { graphListeners.delete(listener) } + }, + } + return fake as FakeHost +} + +// Structural fake: the plugin only touches register(); the service class +// carries private state a literal cannot (and need not) reproduce. +function fakeHttpServer(routes: WebRoute[]): HttpServerService { + const fake: Pick<HttpServerService, 'register' | 'tapIndex' | 'port'> = { + register(route) { + routes.push(route) + return () => { routes.splice(routes.indexOf(route), 1) } + }, + tapIndex: () => () => {}, + port: 0, + } + return fake as HttpServerService +} + +async function mount(clientModuleHost: FakeHost, httpServer: HttpServerService) { + const ctx = new Context() + ctx.provide('clientModuleHost', clientModuleHost) + ctx.provide('httpServer', httpServer) + const fiber = ctx.plugin( + { inject: [...inject], Config, apply }, + { pollIntervalMs: POLL_MS }, + ) + await fiber.await() + return fiber +} describe('hmr node half', () => { - it('apply is a no-op host placeholder', () => { - apply() - expect(true).toBe(true) // reaching here without throw is the contract + it('watches graph bundles, reports stat changes, and unwatches on dispose', async () => { + const bundle = join(dir, 'a.js') + writeFileSync(bundle, 'v1') + const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]])) + const routes: WebRoute[] = [] + const fiber = await mount(clientModuleHost, fakeHttpServer(routes)) + + expect(routes).toHaveLength(1) + expect(routes[0]).toMatchObject({ kind: 'exact', path: EVENTS_ENDPOINT }) + expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a']) + clientModuleHost.rebuiltCalls.length = 0 + + // Nudge mtime past stat granularity so the poller sees a content signal. + await new Promise(resolve => setTimeout(resolve, POLL_MS * 2)) + writeFileSync(bundle, 'v2-longer') + await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toContain('pkg-a') }, { timeout: 3_000 }) + + await fiber.dispose() + expect(routes).toHaveLength(0) + // Watcher gone: further file changes report nothing. + clientModuleHost.rebuiltCalls.length = 0 + writeFileSync(bundle, 'v3-even-longer') + await new Promise(resolve => setTimeout(resolve, POLL_MS * 4)) + expect(clientModuleHost.rebuiltCalls).toHaveLength(0) + }) + + it('follows graph changes: rows added after activation get watched', async () => { + const early = join(dir, 'early.js') + const late = join(dir, 'late.js') + writeFileSync(early, 'v1') + const rows = new Map([['pkg-early', early]]) + const clientModuleHost = fakeClientModuleHost(rows) + const fiber = await mount(clientModuleHost, fakeHttpServer([])) + clientModuleHost.rebuiltCalls.length = 0 + + writeFileSync(late, 'v1') + rows.set('pkg-late', late) + clientModuleHost.fireGraphChanged() + expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-late']) + clientModuleHost.rebuiltCalls.length = 0 + + await new Promise(resolve => setTimeout(resolve, POLL_MS * 2)) + writeFileSync(late, 'v2-longer') + await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toContain('pkg-late') }, { timeout: 3_000 }) + + rows.delete('pkg-late') + clientModuleHost.fireGraphChanged() + clientModuleHost.rebuiltCalls.length = 0 + writeFileSync(late, 'v3-even-longer') + await new Promise(resolve => setTimeout(resolve, POLL_MS * 3)) + expect(clientModuleHost.rebuiltCalls).toHaveLength(0) + await fiber.dispose() + }) + + it('rehashes after baseline capture so a construction-window write cannot become the baseline', async () => { + const bundle = join(dir, 'construction.js') + writeFileSync(bundle, 'v1') + let rewrite = true + const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]]), { + beforeGraphRead: () => { + if (!rewrite) return + rewrite = false + // The graph carries the hash from before this write. The old + // fs.watchFile registration asynchronously captured the new file as + // its first baseline and never requested a re-hash. + writeFileSync(bundle, 'v2-written-during-watch-construction') + }, + }) + + const fiber = await mount(clientModuleHost, fakeHttpServer([])) + + expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a']) + clientModuleHost.rebuiltCalls.length = 0 + await new Promise(resolve => setTimeout(resolve, POLL_MS * 3)) + expect(clientModuleHost.rebuiltCalls).toHaveLength(0) + await fiber.dispose() + }) + + it('marks a vanished bundle dirty so identical metadata still re-hashes after it reappears', async () => { + const bundle = join(dir, 'replace.js') + writeFileSync(bundle, 'seed') + const fixedTime = new Date(1_600_000_000_000) + utimesSync(bundle, fixedTime, fixedTime) + const baseline = statSync(bundle) + const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]])) + const fiber = await mount(clientModuleHost, fakeHttpServer([])) + clientModuleHost.rebuiltCalls.length = 0 + + unlinkSync(bundle) + await new Promise(resolve => setTimeout(resolve, POLL_MS * 2)) + writeFileSync(bundle, 'x'.repeat(baseline.size)) + utimesSync(bundle, fixedTime, fixedTime) + const restored = statSync(bundle) + expect({ mtimeMs: restored.mtimeMs, size: restored.size }).toEqual({ + mtimeMs: baseline.mtimeMs, + size: baseline.size, + }) + await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a']) }, { timeout: 3_000 }) + await fiber.dispose() + }) + + it('retains a dirty baseline when the immediate re-hash races a rename', async () => { + const bundle = join(dir, 'rename.js') + writeFileSync(bundle, 'v1') + let first = true + const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]]), { + rebuilt: () => { + if (!first) return 'r2' + first = false + throw Object.assign(new Error('bundle renamed'), { code: 'ENOENT' }) + }, + }) + + const fiber = await mount(clientModuleHost, fakeHttpServer([])) + + await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a', 'pkg-a']) }, { timeout: 3_000 }) + await fiber.dispose() }) }) diff --git a/packages/client/hmr/tsconfig.json b/packages/client/hmr/tsconfig.json index 764741c9cb..9ad1837558 100644 --- a/packages/client/hmr/tsconfig.json +++ b/packages/client/hmr/tsconfig.json @@ -8,7 +8,7 @@ "DOM", "DOM.Iterable" ], - "types": [] + "types": ["node"] }, "include": [ "src" @@ -23,6 +23,12 @@ { "path": "../modules" }, + { + "path": "../../host/webserver" + }, + { + "path": "../../../vendor/schemastery" + }, { "path": "../../support/invariants" } diff --git a/packages/client/modules/package.json b/packages/client/modules/package.json index ad2fb78ab1..468ffdf0bc 100644 --- a/packages/client/modules/package.json +++ b/packages/client/modules/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-modules", - "description": "Client module loader: the browser peer of Node's internal ESM loader, consumed by the vendored cordis Loader as its internal seam (resolve/import/loadCache/invalidate over seed table, static registry and fetch bundles)", + "description": "Client module system, dual-face: node half composes the __DSH_BOOT__ entry graph (incremental dshClient scan, bundle route, index tap, webPlugins service); browser half is the lazy-CJS module table the vendored cordis Loader consumes as its internal seam", "version": "0.0.1", "private": true, "type": "module", @@ -11,6 +11,10 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, "./invariant": { "types": "./lib/types/invariant.d.ts", "default": "./lib/invariant.js" @@ -18,14 +22,26 @@ "./src/*": "./src/*", "./package.json": "./package.json" }, + "dshClient": { + "platform": "web", + "inject": [], + "immediately": true + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, "license": "BSD-3-Clause", "devDependencies": { + "@cordisjs/plugin-loader": "workspace:^", + "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "cordis": "^4.0.0-rc.7" }, "files": [ "lib/index.js", "lib/invariant.js", + "lib/client.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "src" diff --git a/packages/client/modules/src/client/index.ts b/packages/client/modules/src/client/index.ts new file mode 100644 index 0000000000..c734ffb8f7 --- /dev/null +++ b/packages/client/modules/src/client/index.ts @@ -0,0 +1,34 @@ +/** + * Browser half (the standard `./client` export): the module-system class and + * wire contract, plus the enrollment plugin face. The module system itself is + * built by the shell kernel BEFORE cordis exists (the bootstrap exception, + * design §4.7 — the mechanism that loads plugins cannot arrive through + * itself); the plugin face only enrolls that pre-existing instance by + * providing it as `ctx.modules`. The kernel statically registers this module, + * so the graph row for this package never triggers a real fetch — arrival is + * a no-op against the already-registered entry. + * @module @deepseek-ai/dsh-client-modules/client + */ +import type { Context } from 'cordis' +import type { DshWindow } from './manifest.ts' + +export { ClientModuleSystem } from './system.ts' +export { parseBootManifest } from './manifest.ts' +export type { + BootManifest, BootModuleRow, BootPluginRow, ClientModuleLoader, ClientModuleRecord, + ClientModuleSystemOptions, ClientPluginHandoff, DshWindow, WebBootEntry, WebBootGraph, +} from './manifest.ts' + +/** + * Enroll the kernel-built module system as `ctx.modules`. + * @param ctx - client root context. + */ +export function apply(ctx: Context): void { + const modules = (globalThis as DshWindow).__DSH_MODULES__ + // The kernel writes the slot right after constructing the instance, before + // any cordis entry exists — a missing slot means the kernel sequencing broke. + if (modules === undefined) { + throw new Error('client-modules: window.__DSH_MODULES__ missing — the shell kernel must construct the module system before plugin boot') + } + ctx.reflect.provide('modules', modules) +} diff --git a/packages/client/modules/src/client/manifest.ts b/packages/client/modules/src/client/manifest.ts new file mode 100644 index 0000000000..6b8ff35548 --- /dev/null +++ b/packages/client/modules/src/client/manifest.ts @@ -0,0 +1,243 @@ +/** + * Client module system: the browser peer of Node's internal ESM loader, built + * as a lazy CJS table. The vendored cordis Loader consumes this object + * through its `internal` seam (the only call site is `EntryTree.import` → + * `internal.import`), which keeps entry governance (fiber lifecycle, inject + * waiting, update/refresh) entirely on the vendored side while this package + * owns code arrival. + * + * Lazy CJS model (web2 §0): executing a plugin bundle only REGISTERS its + * factory (`window.__ModuleLoader__.load({id, factory})`); every module body + * side effect — including CSS injection — lives inside the factory closure + * and runs at materialization, not at script execution. Materialization + * (factory(require) → export surface) happens on first import/require and is + * memoized in {@link ClientModuleLoader.loadCache}; a factory that requires + * another registered-but-unmaterialized module materializes it recursively, + * so load order needs no external sequencing. + * + * Resolution branch order (import): seed word → shell instance; memoized + * record → surface; static registry (shell-own modules, e.g. app-shell) → + * module; registered factory → materialize; graph row → fetch + execute + + * materialize; anything else → throw (loud — the runtime mirror of the + * build-time bundle purity gate). The synchronous `require` handed to + * factories walks the same order minus the fetch branch: fetching is async, + * so only already-executed bundles can be required — and cross-plugin value + * imports are a build error anyway. + * + * This file is the browser-safe contract face (zero node imports): the + * `__DSH_BOOT__` wire types, the boot-manifest parser, and the seams around + * {@link ClientModuleSystem}. The package root is the host-side service that + * composes the wire. + */ + +import type {} from 'cordis' +import type { ClientModuleSystem } from './system.ts' + +declare module 'cordis' { + interface Context { + /** The client module system the web shell builds at boot (contract C5; provided by the `./client` wrapper plugin). */ + modules: ClientModuleLoader + } +} + +/** + * One composed client entry pushed by the host (web2 §0 graph row). Wire + * single source: the host node half (package root) produces this same shape. + * `immediately` marks stage-one prefetch; `inject` is informational graph + * metadata (the authoritative edges live in each package's dshClient + * declaration and reach fibers through entry creation). + */ +export interface WebBootEntry { + /** Entry name == package name. */ + id: string + /** Bundle endpoint, '/plugins/<id>/client.js?rev=<rev>'. */ + url: string + /** Bundle content hash (cache-busting consistency anchor). */ + rev: string + /** Package-name dependency edges, informational (preflight display / HMR diffing). */ + inject?: string[] + /** Stage-one prefetch mark: fetch + execute (factory registration) during module-face boot. */ + immediately?: boolean +} + +/** The composed client entry graph the host injects as `window.__DSH_BOOT__`. */ +export interface WebBootGraph { + /** Consistency anchor over the whole graph (content + bundle hashes). */ + rev: string + /** Composed entries; order carries no semantics (activation order is fiber inject waiting). */ + entries: WebBootEntry[] +} + +/** The npm-package view of one boot row: what the module table needs to fetch the bundle. */ +export interface BootModuleRow { + /** Entry name == package name (module-table key). */ + id: string + /** Bundle endpoint, '/plugins/<id>/client.js?rev=<rev>'. */ + url: string + /** Bundle content hash. */ + rev: string +} + +/** The cordis-plugin view of one boot row: what entry composition needs (optional wire fields normalized). */ +export interface BootPluginRow { + /** Entry name == package name. */ + id: string + /** Package-name dependency edges ([] when the wire omits them). */ + inject: string[] + /** Stage-one prefetch tier (false when the wire omits it). */ + immediately: boolean +} + +/** The parsed boot manifest: one wire, two consumer views. */ +export interface BootManifest { + /** Consistency anchor over the whole graph. */ + rev: string + /** Rows as the module table consumes them. */ + modules: BootModuleRow[] + /** Rows as entry composition consumes them. */ + plugins: BootPluginRow[] +} + +/** + * Parse `window.__DSH_BOOT__` into the two consumer views. Wire boundary: + * a missing or malformed graph throws (the shell shows the loud failure — + * a page without a valid manifest cannot boot anything). + * @param wire - the raw `window.__DSH_BOOT__` value. + * @returns the manifest with optional plugin-view fields normalized. + */ +export function parseBootManifest(wire: unknown): BootManifest { + if (typeof wire !== 'object' || wire === null) { + throw new Error('client-modules: window.__DSH_BOOT__ is missing or not an object') + } + const graph = wire as Record<string, unknown> + if (typeof graph.rev !== 'string') { + throw new Error('client-modules: boot manifest rev must be a string') + } + if (!Array.isArray(graph.entries)) { + throw new Error('client-modules: boot manifest entries must be an array') + } + const modules: BootModuleRow[] = [] + const plugins: BootPluginRow[] = [] + for (const value of graph.entries as unknown[]) { + if (typeof value !== 'object' || value === null) { + throw new Error('client-modules: boot manifest entry is not an object') + } + const row = value as Record<string, unknown> + const where = typeof row.id === 'string' ? `"${row.id}"` : JSON.stringify(row) + if (typeof row.id !== 'string' || typeof row.url !== 'string' || typeof row.rev !== 'string') { + throw new Error(`client-modules: boot manifest entry ${where} must carry string id/url/rev`) + } + if (row.inject !== undefined && (!Array.isArray(row.inject) || row.inject.some(i => typeof i !== 'string'))) { + throw new Error(`client-modules: boot manifest entry ${where} inject must be a string array`) + } + if (row.immediately !== undefined && typeof row.immediately !== 'boolean') { + throw new Error(`client-modules: boot manifest entry ${where} immediately must be a boolean`) + } + modules.push({ id: row.id, url: row.url, rev: row.rev }) + plugins.push({ + id: row.id, + inject: row.inject === undefined ? [] : [...row.inject as string[]], + immediately: row.immediately === true, + }) + } + return { rev: graph.rev, modules, plugins } +} + +/** The shape a client bundle hands to `window.__ModuleLoader__.load` (registration handoff, contract C6). */ +export interface ClientPluginHandoff { + /** Plugin id (package name) — the registration key; must match the graph row being executed. */ + id: string + /** + * Closure factory holding the whole bundle body: receives the synchronous + * require bound to the module table and returns the bundle's export + * surface. Runs once, at materialization. + */ + factory: (require: (spec: string) => unknown) => Record<string, unknown> +} + +/** Window surface of the web boot protocol: the host-injected graph, the registration sink, and the kernel handoff slot. */ +export interface DshWindow { + /** Host-composed entry graph, injected before the shell bundle runs; wire-boundary raw until {@link parseBootManifest}. */ + __DSH_BOOT__?: unknown + /** Bundle registration sink; installed once per page by the {@link ClientModuleSystem} constructor (contract C6). */ + __ModuleLoader__?: { load(handoff: ClientPluginHandoff): void } + /** + * Kernel handoff slot: the shell kernel stores the instance here right + * after construction (before cordis exists) so the `./client` wrapper + * plugin can provide it as `ctx.modules`. Missing slot at wrapper apply + * time = kernel sequencing bug, thrown loud. + */ + __DSH_MODULES__?: ClientModuleSystem +} + +/** Per-module bookkeeping in {@link ClientModuleLoader.loadCache} (module-graph seam, flat today). */ +export interface ClientModuleRecord { + /** Module id (entry name / package name). */ + id: string + /** The materialized export surface (factory `module.exports`, or the shell module for static registrations). */ + surface: unknown + /** Owned `<style data-plugin>` tag ids (`data-plugin-css` values) injected during materialization. */ + styles: string[] + /** Observed `require()` edges (module-graph seam; only table words can appear today). */ + edges: Set<string> +} + +/** + * The internal-seam subset the vendored Loader and the client HMR plugin + * consume. Mounted on `ctx.loader.internal` by the shell boot and provided + * as `ctx.modules` (contract C5). + */ +export interface ClientModuleLoader { + /** Discriminant against Node's internal loader shapes ('v1'/'v2'). */ + version: 'client' + /** Materialized-module registry: id → record. The governance-side read face for entry export surfaces. */ + loadCache: Map<string, ClientModuleRecord> + /** + * Internal seam consumed by the vendored Loader's `tree.import`. Resolves + * `specifier` through the branch order documented on the module, fetching + * and executing a bundle when needed. + * @param specifier - module specifier (entry name or table word). + * @param parentURL - importer URL (unused — the client module graph is flat). + * @param attrs - import attributes (unused; interface parity with Node's seam). + * @returns the module's export surface. + */ + import(specifier: string, parentURL: string, attrs: Record<string, unknown>): Promise<unknown> + /** + * Register a shell-own module (app-shell — code that ships inside the shell + * bundle and never arrives as a plugin bundle). + * @param id - entry name (shell-owned pseudo id). + * @param module - the statically imported module namespace. + */ + registerStatic(id: string, module: unknown): void + /** + * Stage-one arrival: fetch the entry's bundle and execute it, registering + * its factory (no materialization — module side effects wait for import). + * No-op for static-registered ids and ids whose factory is already + * registered; concurrent calls share one in-flight task. To force a fresh + * fetch (HMR), {@link invalidate} first. + * @param id - graph entry name. + */ + prefetch(id: string): Promise<void> + /** + * Full reset of one module: drop its registered factory, its materialized + * record, and any consumed bundle text, so the next prefetch/import + * refetches and re-executes (the HMR invalidation hook). + * @param id - entry name to invalidate. + */ + invalidate(id: string): void +} + +/** Options for {@link ClientModuleSystem} (assembled by the web shell kernel at boot). */ +export interface ClientModuleSystemOptions { + /** Boot rows in the module-table view (from {@link parseBootManifest}). */ + modules: BootModuleRow[] + /** Module-table seed: platform-singleton specifier → shell instance. */ + staticModules: Record<string, unknown> + /** Bundle fetch seam (parallelizable half). Defaults to same-origin fetch().text(). */ + fetchBundle?: (url: string) => Promise<string> + /** + * Bundle execution seam (synchronously performs the load() registration). + * Defaults to a <script> element carrying the code. + */ + executeBundle?: (code: string, url: string) => void +} diff --git a/packages/client/modules/src/loader.ts b/packages/client/modules/src/client/system.ts similarity index 86% rename from packages/client/modules/src/loader.ts rename to packages/client/modules/src/client/system.ts index b2682a4bcd..abbafc5549 100644 --- a/packages/client/modules/src/loader.ts +++ b/packages/client/modules/src/client/system.ts @@ -1,13 +1,13 @@ /** - * ClientModuleLoaderImpl — the implementation behind the {@link ClientModuleLoader} + * ClientModuleSystem — the implementation behind the {@link ClientModuleLoader} * seam. The conceptual contract (lazy CJS model, resolution branch order) is - * documented on the package module and the public interfaces in `./index.ts`; - * this file owns the state tables and the fetch/execute/materialize machinery. + * documented on the public interfaces in `./manifest.ts`; this file owns the + * state tables and the fetch/execute/materialize machinery. */ import type { - ClientModuleLoader, ClientModuleLoaderOptions, ClientModuleRecord, - ClientPluginHandoff, DshWindow, WebBootEntry, -} from './index.ts' + BootModuleRow, ClientModuleLoader, ClientModuleRecord, + ClientModuleSystemOptions, ClientPluginHandoff, DshWindow, +} from './manifest.ts' /** A registered-but-unmaterialized bundle: the factory plus its source URL (diagnostics). */ interface RegisteredFactory { @@ -35,13 +35,6 @@ const defaultExecuteBundle = (code: string, url: string): void => { el.remove() } -const urlOf = (row: WebBootEntry): string => { - // url is conditional on the wire (shell-own pseudo rows omit it); those - // ids resolve through the static registry and never reach a fetch. - if (row.url === undefined) throw new Error(`client-modules: entry "${row.id}" has no bundle url and no static registration`) - return row.url -} - /** * A plugin bundle IS its package's client half: `<id>/client` (the exports * subpath external bundles emit) and the bare graph id name the same @@ -70,10 +63,10 @@ const claimStyles = (id: string): string[] => { /** * The client module system: state tables plus the arrival/materialization * machinery implementing {@link ClientModuleLoader} (whose members carry the - * seam contract docs). Construction indexes the boot graph and installs the + * seam contract docs). Construction indexes the boot rows and installs the * `window.__ModuleLoader__` registration sink (contract C6) — once per page. */ -export class ClientModuleLoaderImpl implements ClientModuleLoader { +export class ClientModuleSystem implements ClientModuleLoader { readonly version = 'client' readonly loadCache = new Map<string, ClientModuleRecord>() @@ -84,7 +77,7 @@ export class ClientModuleLoaderImpl implements ClientModuleLoader { private readonly pendingArrival = new Map<string, Promise<void>>() /** Materialization re-entrancy guard: factory-form CJS cannot deliver partial exports, so a cycle is fatal. */ private readonly materializing = new Set<string>() - private readonly graphRows = new Map<string, WebBootEntry>() + private readonly graphRows = new Map<string, BootModuleRow>() // Execution URL of the bundle currently being executed (bound into the // factory registration so diagnostics can name the source). private executingUrl = '' @@ -97,17 +90,17 @@ export class ClientModuleLoaderImpl implements ClientModuleLoader { private readonly executeBundle: (code: string, url: string) => void /** - * Build the module system over the host graph. - * @param options - entry graph, module-table staticModules, fetch/execute seams. + * Build the module system over the parsed boot rows. + * @param options - module rows, module-table staticModules, fetch/execute seams. */ - constructor(options: ClientModuleLoaderOptions) { + constructor(options: ClientModuleSystemOptions) { this.seed = new Map(Object.entries(options.staticModules)) this.fetchBundle = options.fetchBundle ?? defaultFetchBundle this.executeBundle = options.executeBundle ?? defaultExecuteBundle - for (const entry of options.graph.entries) { - if (this.graphRows.has(entry.id)) throw new Error(`client-modules: duplicate graph entry "${entry.id}"`) - this.graphRows.set(entry.id, entry) + for (const row of options.modules) { + if (this.graphRows.has(row.id)) throw new Error(`client-modules: duplicate graph entry "${row.id}"`) + this.graphRows.set(row.id, row) } const win = globalThis as DshWindow @@ -129,13 +122,12 @@ export class ClientModuleLoaderImpl implements ClientModuleLoader { } /** Fetch + execute one graph row so its factory is registered (idempotent per in-flight arrival). */ - private arrive(row: WebBootEntry): Promise<void> { - const { id } = row + private arrive(row: BootModuleRow): Promise<void> { + const { id, url } = row const pending = this.pendingArrival.get(id) if (pending !== undefined) return pending if (this.factories.has(id)) return Promise.resolve() const task = (async (): Promise<void> => { - const url = urlOf(row) const code = await this.fetchBundle(url) this.executingUrl = url this.executingId = id diff --git a/packages/client/modules/src/index.ts b/packages/client/modules/src/index.ts index cb22dfa7ca..ecfc31b77f 100644 --- a/packages/client/modules/src/index.ts +++ b/packages/client/modules/src/index.ts @@ -1,175 +1,393 @@ /** - * Client module system: the browser peer of Node's internal ESM loader, built - * as a lazy CJS table. The vendored cordis Loader consumes this object - * through its `internal` seam (the only call site is `EntryTree.import` → - * `internal.import`), which keeps entry governance (fiber lifecycle, inject - * waiting, update/refresh) entirely on the vendored side while this package - * owns code arrival. + * Node half of the client module system (dshClient dual-face package): scans + * the host Loader's entries for `dshClient` packages, composes the + * `window.__DSH_BOOT__` entry graph (wire single source: {@link WebBootEntry} + * in `./client/manifest.ts`), serves `/plugins/<id>/client.js`, taps the + * index render to inject the boot manifest, and provides the + * `clientModuleHost` service (the HMR node half's registration/notification + * face). * - * Lazy CJS model (web2 §0): executing a plugin bundle only REGISTERS its - * factory (`window.__ModuleLoader__.load({id, factory})`); every module body - * side effect — including CSS injection — lives inside the factory closure - * and runs at materialization, not at script execution. Materialization - * (factory(require) → export surface) happens on first import/require and is - * memoized in {@link ClientModuleLoader.loadCache}; a factory that requires - * another registered-but-unmaterialized module materializes it recursively, - * so load order needs no external sequencing. - * - * Resolution branch order (import): seed word → shell instance; memoized - * record → surface; static registry (shell-own modules, e.g. app-shell) → - * module; registered factory → materialize; graph row → fetch + execute + - * materialize; anything else → throw (loud — the runtime mirror of the - * build-time bundle purity gate). The synchronous `require` handed to - * factories walks the same order minus the fetch branch: fetching is async, - * so only already-executed bundles can be required — and cross-plugin value - * imports are a build error anyway. + * Scanning is incremental per package — there is no full-rescan code path. + * Every cordis `internal/plugin` emission (fiber construction/disposal) marks + * the fiber's entry name dirty; a microtask flush reconciles each dirty name + * against the live loader entries. The activation pass seeds the same dirty + * set with all current entries and flushes synchronously, so first scan and + * steady state share one implementation. Package metadata (including the + * negative "not a client package" verdict) is cached per name and never + * expires — plugin-set changes take effect on restart per the config-source + * ruling; bundle content changes reach the graph only through + * {@link ClientModuleHostService.rebuilt}. * @module @deepseek-ai/dsh-client-modules */ -import { ClientModuleLoaderImpl } from './loader.ts' +import { createHash } from 'node:crypto' +import { readFileSync } from 'node:fs' +import { readFile } from 'node:fs/promises' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { createRequire } from 'node:module' +import { dirname, join } from 'node:path' +import { Service } from 'cordis' +import type { Context } from 'cordis' +import type {} from '@cordisjs/plugin-loader' +import type {} from '@deepseek-ai/dsh-host-webserver' +import type { WebBootEntry, WebBootGraph } from './client/manifest.ts' -export { ClientModuleLoaderImpl } +export type { + BootManifest, BootModuleRow, BootPluginRow, WebBootEntry, WebBootGraph, +} from './client/manifest.ts' declare module 'cordis' { interface Context { - /** The client module system the web shell provides at boot (contract C5). */ - modules: ClientModuleLoader + /** The web plugin table (provided by the client-modules node half). */ + clientModuleHost: ClientModuleHostService + } +} + +/** package.json `dshClient` declaration shape (file boundary — validated field by field). */ +interface DshClientDeclaration { + inject?: string[] + platform: string + /** Boot phase-one prefetch mark; absent means lazy (fetched on demand). */ + immediately?: boolean +} + +/** Resolved package metadata for one dshClient package (cached per name, never expires). */ +interface PkgMeta { + clientPath: string + inject?: string[] + immediately: boolean +} + +/** One composed table row: the wire entry plus its bundle path. */ +interface WebPluginRecord { + entry: WebBootEntry + clientPath: string +} + +/** Narrow an unknown parsed JSON value to the dshClient declaration, throwing on malformed fields. */ +function parseDshClient(pkgName: string, value: unknown): DshClientDeclaration | undefined { + if (value === undefined) return undefined + if (typeof value !== 'object' || value === null) { + throw new Error(`client-modules: ${pkgName} has a non-object dshClient declaration`) + } + const decl = value as Record<string, unknown> + if (typeof decl.platform !== 'string') { + throw new Error(`client-modules: ${pkgName} dshClient.platform must be a string`) + } + if (decl.inject !== undefined && (!Array.isArray(decl.inject) || decl.inject.some(i => typeof i !== 'string'))) { + throw new Error(`client-modules: ${pkgName} dshClient.inject must be a string array`) + } + if (decl.immediately !== undefined && typeof decl.immediately !== 'boolean') { + throw new Error(`client-modules: ${pkgName} dshClient.immediately must be a boolean`) + } + return { + platform: decl.platform, + ...(decl.inject !== undefined ? { inject: decl.inject as string[] } : {}), + ...(decl.immediately !== undefined ? { immediately: decl.immediately } : {}), + } +} + +/** Resolve `exports["./client"]` to a relative path, accepting the string and one-level conditional forms. */ +function clientExportOf(pkgName: string, exportsField: unknown): string | undefined { + if (typeof exportsField !== 'object' || exportsField === null) return undefined + const client = (exportsField as Record<string, unknown>)['./client'] + if (client === undefined) return undefined + if (typeof client === 'string') return client + if (typeof client === 'object' && client !== null) { + const fallback = (client as Record<string, unknown>).default + if (typeof fallback === 'string') return fallback + } + throw new Error(`client-modules: ${pkgName} exports["./client"] has an unsupported shape`) +} + +/** sha1 content hash shortened to 12 hex chars (bundle rev / graph rev). */ +function shortHash(input: string | Buffer): string { + return createHash('sha1').update(input).digest('hex').slice(0, 12) +} + +/** Graph row for one bundle rev (url carries the rev as its cache-busting query). */ +function graphRow(id: string, rev: string, injectEdges: string[] | undefined, immediately: boolean): WebBootEntry { + return { + id, + url: `/plugins/${id}/client.js?rev=${rev}`, + rev, + ...(injectEdges !== undefined ? { inject: injectEdges } : {}), + ...(immediately ? { immediately: true } : {}), } } /** - * One composed client entry pushed by the host (web2 §0 graph row). - * `immediately` marks stage-one prefetch; `inject` is informational graph - * metadata (the authoritative edges live in each package's dshClient - * declaration and reach fibers through entry creation). - * - * Wire contract, held on both sides: the producing peer lives in - * `@deepseek-ai/dsh-host-webserver` (host packages keep zero workspace - * dependencies, so neither side imports the other's shape — drift between - * the two declarations is a bug against the web2 contract). + * Inject the boot entry graph into index.html: `window.__DSH_BOOT__` as the + * first script in <head> (before the shell bundle reads it). `<` is escaped in + * the JSON so plugin-controlled strings cannot break out of the script element. + * @param html - the index.html source. + * @param graph - the composed entry graph. + * @returns the html with the graph script injected. */ -export interface WebBootEntry { - /** Entry name == package name (or a shell-owned pseudo id, e.g. app-shell). */ - id: string - /** - * Bundle endpoint, '/plugins/<id>/client.js?rev=<rev>'. Absent only on - * shell-owned pseudo rows (app-shell) whose module is statically registered - * — a row that is neither fetchable nor static-registered fails loud. - */ - url?: string - /** Bundle content hash (cache-busting consistency anchor); absent with url. */ - rev?: string - /** Package-name dependency edges, informational (preflight display / HMR diffing). */ - inject?: string[] - /** Stage-one prefetch mark: fetch + execute (factory registration) during module-face boot. */ - immediately?: boolean -} - -/** The composed client entry graph the host injects as `window.__DSH_BOOT__` (dual-held wire contract — see {@link WebBootEntry}). */ -export interface WebBootGraph { - /** Consistency anchor over the whole graph (content + bundle hashes). */ - rev: string - /** Composed entries; order carries no semantics (activation order is fiber inject waiting). */ - entries: WebBootEntry[] -} - -/** The shape a client bundle hands to `window.__ModuleLoader__.load` (registration handoff, contract C6). */ -export interface ClientPluginHandoff { - /** Plugin id (package name) — the registration key; must match the graph row being executed. */ - id: string - /** - * Closure factory holding the whole bundle body: receives the synchronous - * require bound to the module table and returns the bundle's export - * surface. Runs once, at materialization. - */ - factory: (require: (spec: string) => unknown) => Record<string, unknown> -} - -/** Window surface this loader owns (bundle side of the handoff protocol) plus the host-injected graph. */ -export interface DshWindow { - /** Host-composed entry graph, injected before the shell bundle runs. */ - __DSH_BOOT__?: WebBootGraph - /** Bundle registration sink; installed once per page by {@link createClientModuleLoader} (contract C6). */ - __ModuleLoader__?: { load(handoff: ClientPluginHandoff): void } -} - -/** Per-module bookkeeping in {@link ClientModuleLoader.loadCache} (module-graph seam, flat today). */ -export interface ClientModuleRecord { - /** Module id (entry name / package name). */ - id: string - /** The materialized export surface (factory `module.exports`, or the shell module for static registrations). */ - surface: unknown - /** Owned `<style data-plugin>` tag ids (`data-plugin-css` values) injected during materialization. */ - styles: string[] - /** Observed `require()` edges (module-graph seam; only table words can appear today). */ - edges: Set<string> +export function injectBootManifest(html: string, graph: WebBootGraph): string { + const json = JSON.stringify(graph).replaceAll('<', '\\u003c') + const script = `<script>window.__DSH_BOOT__ = ${json}</script>` + const head = html.indexOf('<head>') + if (head !== -1) return `${html.slice(0, head + 6)}${script}${html.slice(head + 6)}` + // Headless fixture pages may lack <head>; prepending keeps the read-before-shell ordering. + return `${script}${html}` } /** - * The internal-seam subset the vendored Loader and the client HMR plugin - * consume. Mounted on `ctx.loader.internal` by the shell boot and provided - * as `ctx.modules` (contract C5). + * The web plugin table service: incremental dshClient scan + wire composition + * + bundle route + index tap. Construction runs the activation scan + * synchronously — a malformed declaration or missing bundle among the + * already-loaded entries aggregates into one loud throw (FAILED fiber; the + * boot sweep reports it). */ -export interface ClientModuleLoader { - /** Discriminant against Node's internal loader shapes ('v1'/'v2'). */ - version: 'client' - /** Materialized-module registry: id → record. The governance-side read face for entry export surfaces. */ - loadCache: Map<string, ClientModuleRecord> +export class ClientModuleHostService extends Service { + static inject = ['httpServer', 'loader'] + + private readonly table = new Map<string, WebPluginRecord>() + // Negative verdicts (unresolvable specifier — builtins like cordis:include, + // subpath rows — or a package without a web dshClient declaration) are + // cached as null and never expire: plugin-set changes take effect on restart. + private readonly pkgMeta = new Map<string, PkgMeta | null>() + private readonly rebuildListeners = new Set<(id: string, rev: string) => void>() + private readonly graphListeners = new Set<() => void>() + private readonly dirty = new Set<string>() + private readonly resolvePkgJson: (spec: string) => string + private flushQueued = false + private composed: WebBootGraph + /** - * Internal seam consumed by the vendored Loader's `tree.import`. Resolves - * `specifier` through the branch order documented on the module, fetching - * and executing a bundle when needed. - * @param specifier - module specifier (entry name or table word). - * @param parentURL - importer URL (unused — the client module graph is flat). - * @param attrs - import attributes (unused; interface parity with Node's seam). - * @returns the module's export surface. + * Build the service: subscribe, seed, and run the activation flush. + * @param ctx - plugin context carrying httpServer and loader. */ - import(specifier: string, parentURL: string, attrs: Record<string, unknown>): Promise<unknown> + constructor(ctx: Context) { + super(ctx, 'clientModuleHost') + // Resolution anchor: the config tree's baseUrl (the cordis.yml directory, + // whose package declares every composed plugin as a dependency). The + // modules package's own URL would miss sibling packages under pnpm's + // isolated node_modules. + if (ctx.baseUrl === undefined) { + throw new Error('client-modules: ctx.baseUrl is unset — the node half needs the config-tree anchor to resolve plugin packages') + } + const require = createRequire(ctx.baseUrl) + this.resolvePkgJson = spec => require.resolve(`${spec}/package.json`) + + // Subscribe before seeding so a fiber arriving mid-activation lands in the + // same dirty set (Set idempotence makes the overlap harmless). An entry-less + // fiber is a child plugin or a manual mount — never a loader row; O(1) drop. + ctx.on('internal/plugin', (fiber) => { + const entryName = fiber.entry?.options.name + if (entryName === undefined) return + this.dirty.add(entryName) + if (this.flushQueued) return + this.flushQueued = true + queueMicrotask(() => { + this.flushQueued = false + this.flush((err) => { ctx.logger.warn(err) }) + }) + }) + + // Activation pass: the initial scan IS the incremental path over the + // current entries, flushed synchronously (nothing async between subscribe, + // seed, and flush). + for (const entry of ctx.loader.entries()) this.dirty.add(entry.options.name) + this.composed = this.compose() + const failures: Error[] = [] + this.flush(err => failures.push(err)) + if (failures.length > 0) { + throw new AggregateError( + failures, + `client-modules: ${String(failures.length)} client package(s) failed to compose:\n${failures.map(e => ` - ${e.message}`).join('\n')}`, + ) + } + + ctx.effect( + () => ctx.httpServer.register({ kind: 'prefix', path: '/plugins', handler: this.serveBundle }), + 'client-modules: bundle route', + ) + ctx.effect( + () => ctx.httpServer.tapIndex(html => injectBootManifest(html, this.composed)), + 'client-modules: boot manifest injection', + ) + } + /** - * Register a shell-own module (app-shell — code that ships inside the shell - * bundle and never arrives as a plugin bundle). - * @param id - entry name (shell-owned pseudo id). - * @param module - the statically imported module namespace. + * Current composed entry graph (stable object between changes). + * @returns the graph served as `window.__DSH_BOOT__`. */ - registerStatic(id: string, module: unknown): void + graph(): WebBootGraph { + return this.composed + } + /** - * Stage-one arrival: fetch the entry's bundle and execute it, registering - * its factory (no materialization — module side effects wait for import). - * No-op for static-registered ids and ids whose factory is already - * registered; concurrent calls share one in-flight task. To force a fresh - * fetch (HMR), {@link invalidate} first. - * @param id - graph entry name. + * Absolute path of an entry's client bundle. + * @param id - entry id (package name). + * @returns the path, or undefined for an unknown id. */ - prefetch(id: string): Promise<void> + clientPath(id: string): string | undefined { + return this.table.get(id)?.clientPath + } + /** - * Full reset of one module: drop its registered factory, its materialized - * record, and any consumed bundle text, so the next prefetch/import - * refetches and re-executes (the HMR invalidation hook). - * @param id - entry name to invalidate. + * Re-hash one bundle (the HMR watch's registration hook — the only entry + * point through which bundle content changes reach the graph). + * @param id - entry id (package name). + * @returns the new rev, or undefined for an unknown id. */ - invalidate(id: string): void + rebuilt(id: string): string | undefined { + const record = this.table.get(id) + if (record === undefined) return undefined + const rev = shortHash(readFileSync(record.clientPath)) + if (rev === record.entry.rev) return rev + record.entry = graphRow(id, rev, record.entry.inject, record.entry.immediately === true) + this.composed = this.compose() + for (const notify of this.rebuildListeners) { + // Containment: rebuilt() runs inside the HMR watch callback — a + // throwing subscriber must not kill the poll or skip later subscribers. + try { + notify(id, rev) + } catch (error) { + this.ctx.logger.error(error) + } + } + this.notifyGraphChanged() + return rev + } + + /** + * Subscribe to bundle rebuilds; fires only when the re-hash changed the rev. + * @param listener - receives the entry id and its new bundle rev. + * @returns the unsubscriber. + */ + onRebuilt(listener: (id: string, rev: string) => void): () => void { + this.rebuildListeners.add(listener) + return () => { this.rebuildListeners.delete(listener) } + } + + /** + * Fires after any flush that recomposed the graph (row added/removed, or a + * rebuilt rev change). Pull model: listeners re-read {@link graph}. + * @param listener - notified with no payload. + * @returns the unsubscriber. + */ + onGraphChanged(listener: () => void): () => void { + this.graphListeners.add(listener) + return () => { this.graphListeners.delete(listener) } + } + + private compose(): WebBootGraph { + const entries = [...this.table.values()].map(record => record.entry) + return { rev: shortHash(JSON.stringify(entries)), entries } + } + + private notifyGraphChanged(): void { + for (const listener of this.graphListeners) { + // A throwing subscriber must not skip later subscribers (or escape into + // whatever triggered the flush — possibly an fs.watchFile callback). + try { + listener() + } catch (error) { + this.ctx.logger.error(error) + } + } + } + + private resolveMeta(pkgName: string): PkgMeta | null { + const cached = this.pkgMeta.get(pkgName) + if (cached !== undefined) return cached + let pkgPath: string + try { + pkgPath = this.resolvePkgJson(pkgName) + } catch { + // Not a resolvable package root: loader builtins (cordis:include) and + // subpath entries (…/gateway) land here — permanently not a client row. + this.pkgMeta.set(pkgName, null) + return null + } + const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as Record<string, unknown> + const decl = parseDshClient(pkgName, pkg.dshClient) + if (decl === undefined || decl.platform !== 'web') { + this.pkgMeta.set(pkgName, null) + return null + } + const clientRel = clientExportOf(pkgName, pkg.exports) + if (clientRel === undefined) { + throw new Error(`client-modules: ${pkgName} declares dshClient but exports no "./client" bundle`) + } + const meta: PkgMeta = { + clientPath: join(dirname(pkgPath), clientRel), + ...(decl.inject !== undefined ? { inject: decl.inject } : {}), + immediately: decl.immediately === true, + } + this.pkgMeta.set(pkgName, meta) + return meta + } + + /** Reconcile one entry name against the live loader entries. @returns whether the table changed. */ + private processOne(entryName: string): boolean { + let qualifies = false + for (const entry of this.ctx.loader.entries()) { + if (entry.options.name === entryName && entry.fiber !== undefined && !entry.disabled) { + qualifies = true + break + } + } + if (!qualifies) return this.table.delete(entryName) + if (this.table.has(entryName)) return false + const meta = this.resolveMeta(entryName) + if (meta === null) return false + // The rev rides the row from here on: a fiber restart reuses the row (and + // its rev) untouched; only rebuilt() re-reads the bundle. + const rev = shortHash(readFileSync(meta.clientPath)) + this.table.set(entryName, { entry: graphRow(entryName, rev, meta.inject, meta.immediately), clientPath: meta.clientPath }) + return true + } + + private flush(onError: (err: Error) => void): void { + let changed = false + for (const entryName of [...this.dirty]) { + this.dirty.delete(entryName) + try { + if (this.processOne(entryName)) changed = true + } catch (error) { + // Steady state: one broken package must not poison the others; the + // activation pass aggregates these into a loud throw instead. + onError(error instanceof Error ? error : new Error(String(error))) + } + } + if (changed) { + this.composed = this.compose() + this.notifyGraphChanged() + } + } + + private readonly serveBundle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => { + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405) + res.end() + return + } + /* v8 ignore next -- `?? '/'` arm: node:http always sets url on server requests. */ + const pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname) + // The id may contain a scope slash. Anything else under /plugins (including + // /plugins/events when the HMR row is absent) is an unknown resource. + const path = pathname.startsWith('/plugins/') && pathname.endsWith('/client.js') + ? this.clientPath(pathname.slice('/plugins/'.length, -'/client.js'.length)) + : undefined + if (path === undefined) { + res.writeHead(404) + res.end() + return + } + try { + const body = await readFile(path) + res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-cache' }) + res.end(body) + } catch { + // Registered but unreadable (bundle not built yet): loud 404 beats a silent SPA-fallback HTML page. + res.writeHead(404) + res.end() + } + } } -/** Options for {@link createClientModuleLoader} (assembled by the web shell at boot). */ -export interface ClientModuleLoaderOptions { - /** Host-composed entry graph. */ - graph: WebBootGraph - /** Module-table seed: platform-singleton specifier → shell instance. */ - staticModules: Record<string, unknown> - /** Bundle fetch seam (parallelizable half). Defaults to same-origin fetch().text(). */ - fetchBundle?: (url: string) => Promise<string> - /** - * Bundle execution seam (synchronously performs the load() registration). - * Defaults to a <script> element carrying the code. - */ - executeBundle?: (code: string, url: string) => void -} - -/** - * Build the client module system. - * @param options - entry graph, module-table staticModules, fetch/execute seams. - * @returns the loader the shell mounts as `ctx.loader.internal` and provides as `ctx.modules`. - */ -export function createClientModuleLoader(options: ClientModuleLoaderOptions): ClientModuleLoader { - return new ClientModuleLoaderImpl(options) -} +export default ClientModuleHostService diff --git a/packages/client/modules/src/invariant.ts b/packages/client/modules/src/invariant.ts index 60f90ed6e5..ad9605f5dd 100644 --- a/packages/client/modules/src/invariant.ts +++ b/packages/client/modules/src/invariant.ts @@ -15,14 +15,25 @@ export const name = 'client-modules-invariant' export const inject = ['invariants'] /** - * No runtime invariant: the module loader is pre-plugin kernel machinery — - * it emits no cordis events (the vendored Loader owns entry lifecycle events) - * and its mutable state (loadCache, handoff slot) lives below the plugin - * layer where invariant observers cannot mount before it runs; resolve branch - * order and handoff discipline are asserted by the web boot specs against the - * real execution path. + * Owned relation: the node half's boot entry graph must stay self-consistent + * — every row must resolve a clientPath under the same id (the + * /plugins/<id>/client.js URL it advertises would otherwise 404 on a browser + * that just received the graph). Checked on every scan trigger (cordis + * 'internal/plugin'): graph() and clientPath() read the same table object, + * so the relation holds at any instant — no need to wait out the node half's + * own microtask-debounced flush. */ -const install: InvariantInstaller = () => {} +const install: InvariantInstaller = (ctx, fail) => { + ctx.on('internal/plugin', () => { + const host = ctx.get('clientModuleHost') + if (host === undefined) return // browser side / host without the node half: nothing to audit + for (const row of host.graph().entries) { + if (host.clientPath(row.id) === undefined) { + fail(`web plugin graph row "${row.id}" advertises ${row.url} but resolves no client bundle path — the served __DSH_BOOT__ would 404 on fetch`) + } + } + }, { global: true }) +} /** * Register this package's invariant companion. diff --git a/packages/client/modules/tests/loader.spec.ts b/packages/client/modules/tests/loader.spec.ts index ca2627d266..7bd3f0b693 100644 --- a/packages/client/modules/tests/loader.spec.ts +++ b/packages/client/modules/tests/loader.spec.ts @@ -1,6 +1,6 @@ // @vitest-environment jsdom /** - * ClientModuleLoaderImpl behavior: lazy CJS arrival (bundle execution only + * ClientModuleSystem behavior: lazy CJS arrival (bundle execution only * registers the factory), materialization on first import/require with * memoization and recursive self-sequencing, the resolution branch order, * shared in-flight arrival, invalidate-refetch (HMR), style claiming, the @@ -9,9 +9,9 @@ */ import { afterEach, describe, expect, it, vi } from 'vitest' import { - ClientModuleLoaderImpl, createClientModuleLoader, - type ClientModuleLoader, type ClientPluginHandoff, type DshWindow, type WebBootEntry, -} from '../src/index.ts' + ClientModuleSystem, + type BootModuleRow, type ClientModuleLoader, type ClientPluginHandoff, type DshWindow, +} from '../src/client/index.ts' const win = globalThis as DshWindow @@ -24,7 +24,7 @@ afterEach(() => { for (const el of document.querySelectorAll('style, script')) el.remove() }) -const row = (id: string): WebBootEntry => ({ id, url: `/plugins/${id}/client.js?rev=0` }) +const row = (id: string): BootModuleRow => ({ id, url: `/plugins/${id}/client.js?rev=0`, rev: '0' }) interface Bench { loader: ClientModuleLoader @@ -38,14 +38,14 @@ interface Bench { * through the window sink (`null` scripts a bundle that never calls load). */ function bench( - entries: WebBootEntry[], + entries: BootModuleRow[], bundles: Record<string, Factory | null> = {}, opts: { seed?: Record<string, unknown>; gated?: string[] } = {}, ): Bench { const fetched: string[] = [] const gates = new Map<string, () => void>() - const loader = createClientModuleLoader({ - graph: { rev: 'test', entries }, + const loader = new ClientModuleSystem({ + modules: entries, staticModules: opts.seed ?? {}, fetchBundle: (url) => { fetched.push(url) @@ -175,7 +175,7 @@ describe('require resolution', () => { describe('static registry', () => { it('serves shell-own modules to import and require without any fetch', async () => { const shell = { marker: 'app-shell' } - const b = bench([row('a'), { id: 'app-shell' }], { + const b = bench([row('a')], { a: req => ({ dep: req('app-shell') }), }) b.loader.registerStatic('app-shell', shell) @@ -216,18 +216,13 @@ describe('failure modes', () => { await expect(b.loader.prefetch('nope')).rejects.toThrow('prefetch("nope") — not a graph entry') }) - it('a graph row with no url and no static registration is loud', async () => { - const b = bench([{ id: 'ghost' }]) - await expect(b.loader.import('ghost', '', {})).rejects.toThrow('no bundle url and no static registration') - }) - it('a duplicate graph entry is loud at construction', () => { expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"') }) it('double boot is loud', () => { bench([]) - expect(() => new ClientModuleLoaderImpl({ graph: { rev: 't', entries: [] }, staticModules: {} })) + expect(() => new ClientModuleSystem({ modules: [], staticModules: {} })) .toThrow('already installed (double boot?)') }) }) @@ -289,7 +284,7 @@ describe('default transport seams', () => { const code = 'window.__ModuleLoader__ = document.__realmBridge;\n' + 'window.__ModuleLoader__.load({ id: "dee", factory: function () { return { marker: "via-script" } } })' vi.stubGlobal('fetch', async () => ({ ok: true, text: async () => code })) - const loader = createClientModuleLoader({ graph: { rev: 't', entries: [row('dee')] }, staticModules: {} }) + const loader: ClientModuleLoader = new ClientModuleSystem({ modules: [row('dee')], staticModules: {} }) ;(document as unknown as Record<string, unknown>).__realmBridge = win.__ModuleLoader__ const surface = await loader.import('dee', '', {}) expect((surface as { marker: string }).marker).toBe('via-script') @@ -300,7 +295,7 @@ describe('default transport seams', () => { it('a non-ok bundle response is loud with the status', async () => { vi.stubGlobal('fetch', async () => ({ ok: false, status: 404 })) - const loader = createClientModuleLoader({ graph: { rev: 't', entries: [row('dee')] }, staticModules: {} }) + const loader = new ClientModuleSystem({ modules: [row('dee')], staticModules: {} }) await expect(loader.prefetch('dee')).rejects.toThrow('answered 404') }) }) diff --git a/packages/client/modules/tsconfig.json b/packages/client/modules/tsconfig.json index 076aa22e9f..bcde7e62b1 100644 --- a/packages/client/modules/tsconfig.json +++ b/packages/client/modules/tsconfig.json @@ -3,22 +3,14 @@ "compilerOptions": { "rootDir": "src", "outDir": "lib/types", - "lib": [ - "ES2024", - "DOM", - "DOM.Iterable" - ], - "types": [] + "lib": ["ES2024", "DOM", "DOM.Iterable"], + "types": ["node"] }, - "include": [ - "src" - ], + "include": ["src"], "references": [ - { - "path": "../../../vendor/cordis" - }, - { - "path": "../../support/invariants" - } + { "path": "../../../vendor/cordis" }, + { "path": "../../../vendor/loader" }, + { "path": "../../host/webserver" }, + { "path": "../../support/invariants" } ] } diff --git a/packages/client/modules/tsdown.config.ts b/packages/client/modules/tsdown.config.ts new file mode 100644 index 0000000000..e0187f543c --- /dev/null +++ b/packages/client/modules/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle('@deepseek-ai/dsh-client-modules', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/web/README.md b/packages/client/web/README.md index 4b26238cf6..6cea165608 100644 --- a/packages/client/web/README.md +++ b/packages/client/web/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-client-web -Web shell kernel: `bootWebShell(el, seams?)` mounts the whole client through the two-stage boot (web2). Stage one (module face): build the client module system (`@deepseek-ai/dsh-client-modules`) over the host-pushed entry graph (`window.__DSH_BOOT__`) and prefetch the `immediately` tier in parallel — bundle execution registers factories only. Stage two (plugin face): mount the vendored cordis Loader with the module system injected as its `internal` seam, create one loader entry per graph row plus the shell-own app-shell assembly entry (tree.import materializes each module), and gate AppRoot on the settle (loader quiesced + every entry fiber ACTIVE → full UI in one switch). Composition is entirely the host graph's: the roster and the immediately tier live in the composing app; the shell makes zero composition decisions. +Web shell kernel: `new AppWebEntry(el, seams?).run()` mounts the whole client through the two-stage boot (web2). Stage one (module face): build the client module system (`@deepseek-ai/dsh-client-modules`) over the host-pushed entry graph (`window.__DSH_BOOT__`) and prefetch the `immediately` tier in parallel — bundle execution registers factories only. Stage two (plugin face): mount the vendored cordis Loader with the module system injected as its `internal` seam, create one loader entry per graph row plus the shell-own app-shell assembly entry (tree.import materializes each module), and gate AppRoot on the settle (loader quiesced + every entry fiber ACTIVE → full UI in one switch). Composition is entirely the host graph's: the roster and the immediately tier live in the composing app; the shell makes zero composition decisions. Shell self-sufficiency (web2 hard rule): the kernel value-imports no plugin package — the boot status store and signals are hand-rolled here (`loader-status.ts`), so the loading page works while (and especially when) plugins fail. The app-shell assembly (`@deepseek-ai/dsh-client-app-shell`, a shell-owned pseudo entry with no npm package behind it) is the only module registered through `registerStatic`; it inject-waits on slots/sessions/layout like any plugin. diff --git a/packages/client/web/src/boot.tsx b/packages/client/web/src/boot.tsx index 6c04f1619b..bd755a5fc1 100644 --- a/packages/client/web/src/boot.tsx +++ b/packages/client/web/src/boot.tsx @@ -1,23 +1,32 @@ /** - * Web shell boot — the kernel face consumed by the apps/web entry. Everything - * here is machinery that cannot itself be an entry, and none of it + * Web shell boot kernel — the face consumed by the apps/web entry. Everything + * here is machinery that cannot itself be a loader entry, and none of it * value-imports a plugin package (web2 shell self-sufficiency rule: the - * loading page must work while — especially when — plugins fail). + * loading page must work while — especially when — plugins fail). The one + * sanctioned exception is the modules package (design §4.7 bootstrap + * identity): the module system cannot arrive through itself, so its class + * and its client-half wrapper are shell-bundled and the kernel adopts its + * plugin entry once cordis is up. * - * Two-stage boot (web2 §0): - * Stage one (module face): build the module system over the host graph - * (`window.__DSH_BOOT__`) and prefetch every `immediately` row in parallel - * — fetch + execute registers factories only; module side effects wait for - * materialization. Prefetch failures are non-fatal here: stage two's - * import path retries the fetch and owns the loud failure. - * Stage two (plugin face): mount the vendored cordis Loader, inject the - * module system as its internal seam (BEFORE any entry exists — the - * bare-import fallback in tree.import must never run in a browser), create - * one loader entry per graph row (tree.import materializes each module), - * let fibers activate on service availability, then loader.await() + a - * full fiber sweep (all ACTIVE, else reject listing who/what/which - * service) → flip the settled signal so AppRoot switches to the real UI in - * one pass. + * AppWebEntry.run(), module face first, then plugin face: parse + * `window.__DSH_BOOT__` into the two-view BootManifest (wire boundary, D16) + * → build the module system over the module-view rows → render the loading + * page → prefetch every `immediately` row in parallel with mounting the + * vendored cordis Loader (internal-seam injection BEFORE any entry exists — + * the bare-import fallback in tree.import must never run in a browser) → + * await the prefetch tier, THEN adopt the modules entry and create one + * loader entry per plugin-view row plus the shell-own app-shell assembly + * entry → loader.await() + a full fiber sweep (all ACTIVE, else fail + * listing who/what/which service) → flip the settled signal so AppRoot + * switches to the real UI in one pass. + * + * Entry creation waits for the whole immediately tier: materialization runs + * synchronous cross-package require edges (e.g. i18n → runtime/client) that + * fiber inject waiting cannot protect — a bundle's factory must be + * registered before any dependent entry materializes. Per-row prefetch + * failures still resolve silently (the create-side import refetches and + * owns the loud failure), so the barrier never turns one bad bundle into a + * boot-wide fail-fast. * * Composition lives in the host graph; the shell makes zero composition * decisions (the app-shell assembly is itself a graph entry, the only @@ -25,148 +34,205 @@ */ import { Context } from 'cordis' import Loader from '@cordisjs/plugin-loader' -import { createRoot } from 'react-dom/client' +import { createRoot, type Root } from 'react-dom/client' +import * as ModulesClient from '@deepseek-ai/dsh-client-modules/client' import { - createClientModuleLoader, - type ClientModuleLoader, type ClientModuleLoaderOptions, type DshWindow, type WebBootGraph, -} from '@deepseek-ai/dsh-client-modules' + ClientModuleSystem, parseBootManifest, + type BootManifest, type ClientModuleSystemOptions, type DshWindow, +} from '@deepseek-ai/dsh-client-modules/client' import * as AppShell from './app-shell.ts' import { APP_SHELL_ID } from './app-shell.ts' import { AppRoot } from './AppRoot.tsx' import { getStaticModules } from './seed.ts' -import { - STATE_LABELS, createLoaderStatusStore, createSignal, type LoaderStatusStore, -} from './loader-status.ts' +import { STATE_LABELS, createLoaderStatusStore, createSignal } from './loader-status.ts' import './base.css' /** Module transport seams the shell passes through (jsdom tests replace the <script> path). */ -export type BootSeams = Pick<ClientModuleLoaderOptions, 'fetchBundle' | 'executeBundle'> +export type BootSeams = Pick<ClientModuleSystemOptions, 'fetchBundle' | 'executeBundle'> /** - * Sweep every loader entry after the tree quiesced: an entry without a fiber - * failed its import; a fiber not ACTIVE is FAILED (apply threw) or PENDING - * (a required service never arrived — cordis inject waiting has no timeout, - * so this sweep is the fail-loud compensation). + * The modules package's own graph row id. The kernel adopts that entry + * itself (its wrapper is statically registered — shell-bundled code, never + * fetched), so the plugin-row loop must skip it: the vendored Group.create + * does not deduplicate by name, and a second fiber would provide 'modules' + * twice. */ -function assertEntriesActive(ctx: Context): void { - const failures: string[] = [] - for (const entry of ctx.loader.entries()) { - const name = entry.options.name - if (entry.fiber === undefined) { - failures.push(`${name}: import failed (see console for the import error)`) - continue - } - const state = STATE_LABELS[entry.fiber.state] - if (state === 'active') continue - if (state === 'pending') { - const missing = Object.keys(entry.fiber.inject).filter((service) => ctx.get(service) === undefined) - failures.push(`${name}: pending (waiting for service${missing.length === 1 ? '' : 's'}: ${missing.join(', ') || 'unknown'})`) - } else { - failures.push(`${name}: ${state}`) - } - } - if (failures.length > 0) { - throw new Error(`web boot: ${String(failures.length)} entr${failures.length === 1 ? 'y' : 'ies'} did not activate\n${failures.join('\n')}`) - } -} - -/** Stage one: prefetch the immediately tier (factory registration only; failures defer to stage two's import). */ -async function prefetchImmediateTier(modules: ClientModuleLoader, graph: WebBootGraph): Promise<void> { - await Promise.all(graph.entries - .filter((row) => row.immediately === true) - .map((row) => modules.prefetch(row.id).catch(() => { - // Import (stage two) refetches and reports this loudly per entry; - // swallowing here keeps one failing prefetch from masking the others. - }))) -} - -/** Stage two: mount the Loader, inject the internal seam, create the graph entries, settle, sweep. */ -async function runPluginBoot( - ctx: Context, modules: ClientModuleLoader, graph: WebBootGraph, status: LoaderStatusStore, -): Promise<void> { - await ctx.plugin(Loader) - const loader = ctx.loader - // Inject the module system BEFORE any entry exists: tree.import falls back - // to a bare dynamic import when internal is undefined, which in a browser - // is a guaranteed loud failure — correct as a tripwire, never as a path. - loader.internal = modules as never - - // Status projection: AppRoot displays fiber truth. Every internal/status - // transition under an entry re-projects that entry's row from its ROOT - // fiber (child plugin fibers share the same entry). - ctx.on('internal/status', (fiber) => { - const entry = fiber.entry - if (entry === undefined || entry.fiber === undefined) return - status.set(entry.options.name, STATE_LABELS[entry.fiber.state]) - }) - - // Entry creation order carries no semantics (fiber inject waiting owns - // activation order); creating concurrently lets non-prefetched bundle - // fetches parallelize. The app-shell assembly entry is appended by the - // kernel: it is shell-own code (host graph rows are all plugin bundles), - // and mounting the assembly is not a composition decision — it rides the - // same entry lifecycle so the sweep and status cover it uniformly. - const rows = [...graph.entries.map((row) => row.id), APP_SHELL_ID] - await Promise.all(rows.map(async (name) => { - status.set(name, 'loading') - const id = await loader.create({ name }) - // A failed import leaves the entry fiberless (Entry._init logs and - // returns); project it as failed — no fiber means no status event. - if (loader.resolve(id).fiber === undefined) { - status.set(name, 'failed') - } - })) - - await loader.await() - assertEntriesActive(ctx) -} +const MODULES_ID = '@deepseek-ai/dsh-client-modules' /** - * Mount the web shell into a DOM element and start the two-stage boot chain. - * @param el - mount point (the app's #root). - * @param seams - optional module transport overrides (test environments). - * @returns unmount disposer. + * The web shell kernel: mounts the loading page into a DOM element and runs + * the two-stage boot over the host graph. Fields hold only what must exist + * before cordis does — the parsed manifest, the module system, and the + * loading-page UI handles; everything else lives in plugins. */ -export function bootWebShell(el: HTMLElement, seams?: BootSeams): () => void { - const graph = (globalThis as DshWindow).__DSH_BOOT__ - if (graph === undefined) throw new Error('web boot: no entry graph (window.__DSH_BOOT__ missing)') +export class AppWebEntry { + private readonly el: HTMLElement + private readonly seams: BootSeams | undefined + private readonly status = createLoaderStatusStore() + private readonly settled = createSignal(false) + private readonly error = createSignal<string | undefined>(undefined) + // Assigned by run() before any private method or settled-gated closure reads them. + private ctx!: Context + private modules!: ClientModuleSystem + private manifest!: BootManifest + private root: Root | undefined - const ctx = new Context() - const modules = createClientModuleLoader({ graph, staticModules: getStaticModules(), ...seams }) - // The app-shell assembly is the only shell-own module: every other graph - // row is a plugin bundle arriving through fetch (web2 single package form). - modules.registerStatic(APP_SHELL_ID, AppShell) - // Contract C5: the module system is a boot-owned kernel service (ctx.modules). - ctx.reflect.provide('modules', modules) + /** + * Hold the mount point; all work happens in {@link run}. + * @param el - mount point (the app's #root). + * @param seams - optional module transport overrides (test environments). + */ + constructor(el: HTMLElement, seams?: BootSeams) { + this.el = el + this.seams = seams + } - const status = createLoaderStatusStore() - const settled = createSignal(false) - const error = createSignal<string | undefined>(undefined) + /** + * Run the boot chain to settlement. Boot-chain failures resolve (not + * reject): the loading page stays up and renders the failure report (the + * fail-loud surface the kernel owns). Rejects only when the boot manifest + * is missing or malformed — there is nothing to boot against. + * @returns resolves once the UI settled or the failure report rendered. + */ + async run(): Promise<void> { + this.manifest = parseBootManifest((globalThis as DshWindow).__DSH_BOOT__) - const root = createRoot(el) - root.render( - <AppRoot - settled={settled} - status={status} - error={error} - renderApp={() => { - const shell = ctx.get('appShell') - // Unreachable after a clean settle (the app-shell entry is in every graph). - if (shell === undefined) throw new Error('web boot: appShell service missing after settled') - return shell.renderApp() - }} - />, - ) + this.modules = new ClientModuleSystem({ + modules: this.manifest.modules, staticModules: getStaticModules(), ...this.seams, + }) + // The app-shell assembly is the only shell-own module: every other graph + // row is a plugin bundle arriving through fetch (web2 single package form). + this.modules.registerStatic(APP_SHELL_ID, AppShell) + // Adoption handoff, supply side (design §4.7): register the modules + // package's own client half under its bare package name (= graph row id + // = entry name — a suffixed key would miss the statics branch and + // trigger a real fetch), and put the instance on the kernel slot the + // wrapper's apply reads to provide ctx.modules. + this.modules.registerStatic(MODULES_ID, ModulesClient) + ;(globalThis as DshWindow).__DSH_MODULES__ = this.modules - prefetchImmediateTier(modules, graph) - .then(() => runPluginBoot(ctx, modules, graph, status)) - .then( - () => { settled.set(true) }, - (reason: unknown) => { - // Stay on the loading page; surface the sweep report (fail loud). - console.error(reason) - error.set(reason instanceof Error ? reason.message : String(reason)) - }, + this.root = createRoot(this.el) + this.root.render( + <AppRoot + settled={this.settled} + status={this.status} + error={this.error} + renderApp={() => { + const shell = this.ctx.get('appShell') + // Unreachable after a clean settle (the app-shell entry is in every graph). + if (shell === undefined) throw new Error('web boot: appShell service missing after settled') + return shell.renderApp() + }} + />, ) - return () => { root.unmount() } + + // The immediately tier prefetches in parallel with Loader mounting; + // runPluginBoot awaits it before creating entries (see module comment: + // cross-package synchronous require edges need every immediately-tier + // factory registered before any materialization). + const prefetching = this.prefetchImmediateTier() + this.ctx = new Context() + try { + await this.runPluginBoot(prefetching) + this.settled.set(true) + } catch (reason) { + // Stay on the loading page; surface the sweep report (fail loud). + console.error(reason) + this.error.set(reason instanceof Error ? reason.message : String(reason)) + } + } + + /** Unmount the shell (loading page or settled UI). */ + dispose(): void { + this.root?.unmount() + } + + /** Prefetch the immediately tier (factory registration only; failures defer to the import path). */ + private async prefetchImmediateTier(): Promise<void> { + await Promise.all(this.manifest.plugins + .filter((row) => row.immediately) + .map((row) => this.modules.prefetch(row.id).catch(() => { + // Import refetches and reports this loudly per entry; swallowing + // here keeps one failing prefetch from masking the others. + }))) + } + + /** Plugin face: mount the Loader, inject the internal seam, adopt modules, create the graph entries, settle, sweep. */ + private async runPluginBoot(prefetching: Promise<void>): Promise<void> { + const ctx = this.ctx + await ctx.plugin(Loader) + const loader = ctx.loader + // Inject the module system BEFORE any entry exists: tree.import falls back + // to a bare dynamic import when internal is undefined, which in a browser + // is a guaranteed loud failure — correct as a tripwire, never as a path. + loader.internal = this.modules as never + + // Status projection: AppRoot displays fiber truth. Every internal/status + // transition under an entry re-projects that entry's row from its ROOT + // fiber (child plugin fibers share the same entry). + ctx.on('internal/status', (fiber) => { + const entry = fiber.entry + if (entry === undefined || entry.fiber === undefined) return + this.status.set(entry.options.name, STATE_LABELS[entry.fiber.state]) + }) + + // Barrier before any entry exists: entry creation materializes bundles, + // and materialization runs synchronous cross-package require edges that + // need every immediately-tier factory already registered (module + // comment). Resolves even when individual prefetches failed. + await prefetching + + // Adoption handoff, plugin side: the modules entry is created first — + // its wrapper apply reads the kernel slot and provides ctx.modules (the + // provide lives on the plugin face; see MODULES_ID for why the row loop + // must then skip it). + const rows = [MODULES_ID, ...this.manifest.plugins.map((row) => row.id).filter((id) => id !== MODULES_ID), APP_SHELL_ID] + // Entry creation order carries no semantics (fiber inject waiting owns + // activation order); creating concurrently lets non-prefetched bundle + // fetches parallelize. The app-shell assembly entry is appended by the + // kernel: it is shell-own code (host graph rows are all plugin bundles), + // and mounting the assembly is not a composition decision — it rides the + // same entry lifecycle so the sweep and status cover it uniformly. + await Promise.all(rows.map(async (name) => { + this.status.set(name, 'loading') + const id = await loader.create({ name }) + // A failed import leaves the entry fiberless (Entry._init logs and + // returns); project it as failed — no fiber means no status event. + if (loader.resolve(id).fiber === undefined) { + this.status.set(name, 'failed') + } + })) + + await loader.await() + this.assertEntriesActive() + } + + /** + * Sweep every loader entry after the tree quiesced: an entry without a + * fiber failed its import; a fiber not ACTIVE is FAILED (apply threw) or + * PENDING (a required service never arrived — cordis inject waiting has no + * timeout, so this sweep is the fail-loud compensation). + */ + private assertEntriesActive(): void { + const ctx = this.ctx + const failures: string[] = [] + for (const entry of ctx.loader.entries()) { + const name = entry.options.name + if (entry.fiber === undefined) { + failures.push(`${name}: import failed (see console for the import error)`) + continue + } + const state = STATE_LABELS[entry.fiber.state] + if (state === 'active') continue + if (state === 'pending') { + const missing = Object.keys(entry.fiber.inject).filter((service) => ctx.get(service) === undefined) + failures.push(`${name}: pending (waiting for service${missing.length === 1 ? '' : 's'}: ${missing.join(', ') || 'unknown'})`) + } else { + failures.push(`${name}: ${state}`) + } + } + if (failures.length > 0) { + throw new Error(`web boot: ${String(failures.length)} entr${failures.length === 1 ? 'y' : 'ies'} did not activate\n${failures.join('\n')}`) + } + } } diff --git a/packages/client/web/src/index.ts b/packages/client/web/src/index.ts index 6fa7df6c1b..3a9ccda2ba 100644 --- a/packages/client/web/src/index.ts +++ b/packages/client/web/src/index.ts @@ -1,13 +1,13 @@ /** - * Web shell library entry. The shell's product is {@link bootWebShell} — - * apps/web's vite entry calls it against #root; everything else (AppRoot + * Web shell library entry. The shell's product is {@link AppWebEntry} — + * apps/web's vite entry runs it against #root; everything else (AppRoot * gate, app-shell assembly entry, module-table staticModules, platform constants) is * internal to the boot chain. PLATFORM_MODULES is re-exported as the C1 * single source of truth for the tsdown client externals projection. * @module @deepseek-ai/dsh-client-web */ -export { bootWebShell, type BootSeams } from './boot.tsx' +export { AppWebEntry, type BootSeams } from './boot.tsx' export { AppRoot, type AppRootProps } from './AppRoot.tsx' export { buildRenderApp, type AssemblyDeps } from './app.tsx' export { DocumentTitle, type DocumentTitleProps } from './DocumentTitle.tsx' diff --git a/packages/context/README.md b/packages/context/README.md index 4f06db67dd..933dd510ca 100644 --- a/packages/context/README.md +++ b/packages/context/README.md @@ -1,6 +1,6 @@ # context/ — request-context extensions -Product plugins that add model-visible request context without defining a tool. `workspace-context` is included by the default `dsh-agent-spine-demo` bundle and can be disabled through bundle config; `time-context` is opt-in, while the standard TUI and ACP bundles compose `session-reference` explicitly. +Product plugins that add model-visible request context without defining a tool. `workspace-context` is included by the default `dsh-agent-spine-demo` bundle and can be disabled through bundle config; `time-context` is opt-in, while the standard TUI bundle composes `session-reference` explicitly. | Package | Role | ctx key | |---|---|---| diff --git a/packages/context/session-reference/README.md b/packages/context/session-reference/README.md index 4fca9a9977..5ee3f34151 100644 --- a/packages/context/session-reference/README.md +++ b/packages/context/session-reference/README.md @@ -1,6 +1,6 @@ # `@deepseek-ai/dsh-session-reference` -`ctx.sessionReferences` prepares bounded, read-only snapshots of other sessions as prompt-prefix context. It consumes `ctx.sessionQuery` and the backend-independent compact checkpoint marker; SQLite FTS is not required. The standard TUI and ACP demo bundles mount it, while other hosts may call the service directly. +`ctx.sessionReferences` prepares bounded, read-only snapshots of other sessions as prompt-prefix context. It consumes `ctx.sessionQuery` and the backend-independent compact checkpoint marker; SQLite FTS is not required. The standard TUI bundle mounts it, while other hosts may call the service directly. ## Public API @@ -12,7 +12,7 @@ Preparation calls `ctx.sessionQuery.readSurface()` once per distinct source and never rereads it after enqueue. It projects only direct-user `user/message`, direct-user `steering/message`, assistant text, and `user/message` checkpoints carrying the canonical `dsh-compact` source marker from the folded current surface. For a source prompt that already contains baked prefix context, projection reads only its model-hidden display content, preventing recursive snapshot propagation. Shadowed pre-compaction events, tools, reasoning, context, plugin-generated user messages other than marked compact checkpoints, and unfinished assistant chunks are excluded. A compacted source therefore contributes its latest checkpoint plus retained later conversation, not restored shadowed text. -The context source is `{ kind: 'plugin', plugin: 'session-reference' }` with `placement: 'prompt-prefix'`. Its metadata records version `1`, source ids and labels, capture seqs, compact presence, retained/omitted message counts, omitted UTF-8 bytes, and truncation state. AgentLoop writes the snapshot, `## My request:` delimiter, and effective prompt into one `user/message` or `steering/message`; the same event's model-hidden envelope retains the direct prompt and metadata for TUI/ACP replay. Later source mutation, compaction, or deletion cannot change target replay. +The context source is `{ kind: 'plugin', plugin: 'session-reference' }` with `placement: 'prompt-prefix'`. Its metadata records version `1`, source ids and labels, capture seqs, compact presence, retained/omitted message counts, omitted UTF-8 bytes, and truncation state. AgentLoop writes the snapshot, `## My request:` delimiter, and effective prompt into one `user/message` or `steering/message`; the same event's model-hidden envelope retains the direct prompt and metadata for UI replay. Later source mutation, compaction, or deletion cannot change target replay. ## Configuration diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 3c57dbd478..7ac6f7d1db 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -188,6 +188,32 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'clientModuleHost', + summary: 'The web plugin table service: incremental dshClient scan + wire composition + bundle route + index tap.', + methods: [ + { + signature: 'graph(): WebBootGraph', + jsDoc: '/**\n * Current composed entry graph (stable object between changes).\n * @returns the graph served as `window.__DSH_BOOT__`.\n */', + }, + { + signature: 'clientPath(id: string): string | undefined', + jsDoc: '/**\n * Absolute path of an entry\'s client bundle.\n * @param id - entry id (package name).\n * @returns the path, or undefined for an unknown id.\n */', + }, + { + signature: 'rebuilt(id: string): string | undefined', + jsDoc: '/**\n * Re-hash one bundle (the HMR watch\'s registration hook — the only entry\n * point through which bundle content changes reach the graph).\n * @param id - entry id (package name).\n * @returns the new rev, or undefined for an unknown id.\n */', + }, + { + signature: 'onRebuilt(listener: (id: string, rev: string) => void): () => void', + jsDoc: '/**\n * Subscribe to bundle rebuilds; fires only when the re-hash changed the rev.\n * @param listener - receives the entry id and its new bundle rev.\n * @returns the unsubscriber.\n */', + }, + { + signature: 'onGraphChanged(listener: () => void): () => void', + jsDoc: '/**\n * Fires after any flush that recomposed the graph (row added/removed, or a\n * rebuilt rev change). Pull model: listeners re-read {@link graph}.\n * @param listener - notified with no payload.\n * @returns the unsubscriber.\n */', + }, + ], + }, { key: 'codeRuntime', summary: 'Registers one `ctx.codeRuntime` implementation.', @@ -314,6 +340,20 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'httpServer', + summary: 'The web-shape HTTP carrier service.', + methods: [ + { + signature: 'register(route: WebRoute): () => void', + jsDoc: '/**\n * Register a named route. Duplicate (kind, path) throws — route patterns are\n * a composition-level contract, so a collision is a misconfiguration.\n * @param route - kind, path, and the owning handler.\n * @returns the disposer removing the route.\n */', + }, + { + signature: 'tapIndex(transform: (html: string) => string): () => void', + jsDoc: '/**\n * Register an index.html transform, applied to every index response in\n * registration order.\n * @param transform - pure html-to-html function.\n * @returns the disposer removing the transform.\n */', + }, + ], + }, { key: 'invariants', summary: 'Package-owned invariant registry with global and regex-based selection.', @@ -650,6 +690,20 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'storage', + summary: 'The storage hub service.', + methods: [ + { + signature: 'mount<K extends keyof StorageForms>(form: K, facility: StorageForms[K]): () => void', + jsDoc: '/**\n * Mount a data-form facility on the hub. Mounting is an effect: the\n * returned disposer unmounts the form.\n * @param form - Form key declared in {@link StorageForms}.\n * @param facility - The facility instance to expose.\n * @returns the disposer that unmounts the form.\n */', + }, + { + signature: 'form<K extends keyof StorageForms>(form: K): StorageForms[K]', + jsDoc: '/**\n * Resolve a mounted data form.\n * @param form - Form key declared in {@link StorageForms}.\n * @returns the mounted facility.\n */', + }, + ], + }, { key: 'subagents', summary: 'Named provider registry and capability-checked start surface.', @@ -854,6 +908,28 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'workspace', + summary: 'The workspace registry service.', + methods: [ + { + signature: 'async create(path: string, title?: string): Promise<Workspace>', + jsDoc: '/**\n * Create a workspace over an existing directory. The path is canonicalized\n * through `fs.realpath` first — a nonexistent path rejects with the\n * original `ENOENT`, a path resolving to anything but a directory rejects,\n * and a canonical path already owned by another workspace (including a\n * symlink resolving to it) rejects.\n * @param path - Directory the workspace points at; canonicalized before storing.\n * @param title - Display title; defaults to `basename` of the canonical path.\n * @returns the created workspace after durability.\n */', + }, + { + signature: 'get(id: WorkspaceId): Workspace | undefined', + jsDoc: '/**\n * Look up a workspace by id.\n * @param id - The workspace id.\n * @returns the workspace, or `undefined` when unknown.\n */', + }, + { + signature: 'list(): Workspace[]', + jsDoc: '/**\n * Snapshot of all workspaces, in load-then-creation order.\n * @returns a fresh array of the cached entities.\n */', + }, + { + signature: 'async resolveByPath(path: string): Promise<Workspace | undefined>', + jsDoc: '/**\n * Resolve a workspace by directory path, through the same `fs.realpath`\n * canon as {@link create} (hence async). A path that does not exist rejects\n * with the original error — a missing directory has no canonical form to\n * compare (a workspace whose recorded directory vanished is only reachable\n * by id; see `Workspace.status`).\n * @param path - Directory path in any spelling (symlinks, `..`, trailing slash).\n * @returns the owning workspace, or `undefined` when none matches.\n */', + }, + ], + }, ] /** Every harness event, sorted by name. */ @@ -1005,6 +1081,13 @@ export const EVENT_API: readonly EventApiEntry[] = [ jsDoc: '/**\n * A command was registered or unregistered. This is an unfiltered registry\n * notification because a global or scoped change may affect any UI view.\n * Observer failures are contained and cannot veto the registry mutation.\n * @mode emit\n */', summary: 'A command was registered or unregistered.', }, + { + name: 'domain/changed', + mode: 'emit', + signature: '\'domain/changed\'(change: DomainChanged): void', + jsDoc: '/**\n * A domain record or the global singleton changed, emitted once per write\n * strictly after the backend acknowledged durability. Events of one\n * domain arrive in its write-chain order.\n * @param change - domain, table (`\'\'` for global), key (`\'\'` for global),\n * operation discriminant, and on `put` the new snapshot.\n * @mode emit\n */', + summary: 'A domain record or the global singleton changed, emitted once per write strictly after the backend acknowledged durability.', + }, { name: 'fs/edit-intent', mode: 'waterfall', @@ -2023,6 +2106,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SpillSource', declaration: 'export interface SpillSource {\n toolName: string;\n callId: CallId;\n label: string;\n}', }, + { + name: 'StorageForms', + declaration: 'export interface StorageForms {\n}', + }, { name: 'StreamChunk', declaration: 'export type StreamChunk = {\n type: \'block-start\';\n index: number;\n blockType: ContentBlockType;\n} | {\n type: \'text-delta\';\n index: number;\n text: string;\n} | {\n type: \'reasoning-delta\';\n index: number;\n text: string;\n} | {\n type: \'tool-call-delta\';\n index: number;\n id: CallId;\n name?: string;\n argumentsDelta: string;\n} | {\n type: \'block-end\';\n index: number;\n block: ContentBlock;\n} | {\n type: \'usage\';\n usage: TokenUsage;\n} | {\n type: \'finish\';\n reason: FinishReason;\n replayState?: unknown;\n};', @@ -2315,6 +2402,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'WebFetchResult', declaration: 'export interface WebFetchResult {\n readonly url: string;\n readonly statusCode: number;\n readonly body: WebFetchBody;\n readonly truncated: boolean;\n}', }, + { + name: 'WebRoute', + declaration: 'export interface WebRoute {\n kind: WebRouteKind;\n path: string;\n handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;\n}', + }, + { + name: 'WebRouteKind', + declaration: 'export type WebRouteKind = \'exact\' | \'prefix\';', + }, { name: 'WebSearchProvider', declaration: 'export interface WebSearchProvider {\n readonly id: string;\n available(): boolean;\n search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult>;\n}', @@ -2359,6 +2454,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'WorkflowStopReason', declaration: 'export type WorkflowStopReason = \'completed\' | \'cancelled\' | \'error\';', }, + { + name: 'Workspace', + declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly sessionIds: readonly SessionId[];\n setTitle(title: string): Promise<void>;\n attachSession(sessionId: SessionId): Promise<void>;\n detachSession(sessionId: SessionId): Promise<void>;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', + }, ] /** The inherited `ctx` surface (cordis core + loader/hmr/timer), in curated order. */ diff --git a/packages/cordis/tool-cordis/src/present.ts b/packages/cordis/tool-cordis/src/present.ts index e13570cf43..2f824003df 100644 --- a/packages/cordis/tool-cordis/src/present.ts +++ b/packages/cordis/tool-cordis/src/present.ts @@ -1,5 +1,5 @@ /** - * ACP render intents for the three cordis tools — all `generic` cards, decided + * UI render intents for the three cordis tools — all `generic` cards, decided * up front as part of the tool design. Presenters are pure functions of the * call arguments (they run on replay too): no I/O, no session state, no clock. * No `presentResult` overrides exist — the tools' text results are their @@ -13,7 +13,7 @@ import type { GenericCallView } from '@deepseek-ai/dsh-tools' /** * The `cordis_inspect` call card: a read, titled with the requested section. * @param args - the validated call arguments. - * @returns the generic card the ACP bridge renders. + * @returns the generic call card. */ export function presentInspectCall(args: { what?: string; name?: string }): GenericCallView { const target = args.name === undefined ? args.what : `${args.what}: ${args.name}` @@ -27,7 +27,7 @@ export function presentInspectCall(args: { what?: string; name?: string }): Gene /** * The `cordis_mount` call card: an execute carrying the mount code as raw input. * @param args - the validated call arguments. - * @returns the generic card the ACP bridge renders. + * @returns the generic call card. */ export function presentMountCall(args: { code: string }): GenericCallView { return { @@ -41,7 +41,7 @@ export function presentMountCall(args: { code: string }): GenericCallView { /** * The `cordis_unmount` call card: a delete, titled with the mount id. * @param args - the validated call arguments. - * @returns the generic card the ACP bridge renders. + * @returns the generic call card. */ export function presentUnmountCall(args: { id: string }): GenericCallView { return { diff --git a/packages/core/session/src/index.ts b/packages/core/session/src/index.ts index 5e4320f046..5a6b274b3e 100644 --- a/packages/core/session/src/index.ts +++ b/packages/core/session/src/index.ts @@ -129,8 +129,10 @@ function snapshotSessionHeader(id: SessionId, source?: SessionHeader): SessionHe if (record.id !== id) { throw new Error(`session header id "${String(record.id)}" does not match session id "${id}"`) } - if (typeof record.createdAt !== 'number' || !Number.isFinite(record.createdAt)) { - throw new Error('session header createdAt must be a finite number') + if (typeof record.createdAt !== 'number' + || !Number.isSafeInteger(record.createdAt) + || record.createdAt < 0) { + throw new Error('session header createdAt must be a non-negative safe integer') } if (record.cwd !== undefined) { if (typeof record.cwd !== 'string') throw new Error('session header cwd must be a string') diff --git a/packages/core/session/src/types.ts b/packages/core/session/src/types.ts index 017245aed2..a01f1a6a79 100644 --- a/packages/core/session/src/types.ts +++ b/packages/core/session/src/types.ts @@ -36,7 +36,7 @@ export interface SessionHeader { readonly version: number /** The session's id (mirrors the {@link Session}'s id). */ readonly id: SessionId - /** Unix epoch milliseconds when the session was created. */ + /** Non-negative safe-integer Unix epoch milliseconds when the session was created. */ readonly createdAt: number /** Absolute working directory the session was created in (if any). */ readonly cwd?: string @@ -139,10 +139,9 @@ export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap] * * 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). + * on every write (last-write-wins), so entries need no stable identity. The + * three statuses describe the complete portable lifecycle needed by model and + * UI consumers. */ export interface TodoItem { /** What this task is — a short imperative line shown in the UI. */ diff --git a/packages/core/session/tests/session.spec.ts b/packages/core/session/tests/session.spec.ts index 132a250a97..e649214a29 100644 --- a/packages/core/session/tests/session.spec.ts +++ b/packages/core/session/tests/session.spec.ts @@ -757,7 +757,7 @@ describe('Session', () => { { header: 1, error: /not a plain JSON record/ }, { header: null, error: /not a plain JSON record/ }, { header: { ...base, version: 1 }, error: /header version/ }, - { header: { ...base, createdAt: '123' }, error: /createdAt must be a finite number/ }, + { header: { ...base, createdAt: '123' }, error: /createdAt must be a non-negative safe integer/ }, { header: { ...base, cwd: 1 }, error: /header cwd must be a string/ }, { header: { ...base, cwd: 'relative' }, error: /header cwd must be an absolute path/ }, { header: { ...base, parentSession: 1 }, error: /header parentSession must be a string/ }, @@ -962,7 +962,7 @@ describe('SessionStore', () => { await ctx.plugin(SessionStore) const session = ctx.sessions.create(SessionId('plain')) expect(session.header).toMatchObject({ version: SESSION_FORMAT_VERSION, id: 'plain' }) - expect(typeof session.header.createdAt).toBe('number') + expect(Number.isSafeInteger(session.header.createdAt)).toBe(true) expect(session.header.cwd).toBeUndefined() expect(session.header.parentSession).toBeUndefined() }) @@ -1001,7 +1001,10 @@ describe('SessionStore', () => { { meta: { parentSession: 1n }, error: /header is not losslessly JSON-serializable/ }, { meta: { cwd: 1 }, error: /header cwd must be a string/ }, { meta: { parentSession: 1 }, error: /header parentSession must be a string/ }, - { meta: { createdAt: '123' }, error: /header createdAt must be a finite number/ }, + { meta: { createdAt: '123' }, error: /header createdAt must be a non-negative safe integer/ }, + { meta: { createdAt: 1.5 }, error: /header createdAt must be a non-negative safe integer/ }, + { meta: { createdAt: -1 }, error: /header createdAt must be a non-negative safe integer/ }, + { meta: { createdAt: Number.MAX_SAFE_INTEGER + 1 }, error: /header createdAt must be a non-negative safe integer/ }, { meta: { seedLength: '1' }, error: /seedLength must be a non-negative safe integer/ }, { meta: { seedLength: 0.5 }, error: /seedLength must be a non-negative safe integer/ }, { meta: { seedLength: -1 }, error: /seedLength must be a non-negative safe integer/ }, diff --git a/packages/core/tools/src/code-mode.ts b/packages/core/tools/src/code-mode.ts index 30e85c3ad7..9497839607 100644 --- a/packages/core/tools/src/code-mode.ts +++ b/packages/core/tools/src/code-mode.ts @@ -363,7 +363,7 @@ export function createRunCodeTool(registry: ToolRegistry, requireRuntime: () => exec.signal.removeEventListener('abort', onOuterAbort) } }, - // ACP execute cards use the program as their visible title. + // The program is the call's always-visible UI label. presentCall: args => ({ card: 'generic', title: args.code, diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index 468944fa2f..acd478fc29 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -69,7 +69,7 @@ export { defineContentToolFixture, type ContentToolFixtureOptions } from './test // The render-intent vocabulary a tool declares via `presentCall`/`presentResult` // lives in its own UI-facing module; re-export it so `@deepseek-ai/dsh-tools` -// stays the single public surface for consumers (producers + the ACP bridge). +// stays the single public surface for tool producers and UI adapters. export type { ToolCallKind, FileLocation, diff --git a/packages/core/tools/src/presentation.ts b/packages/core/tools/src/presentation.ts index e2fd2cf9ec..17b88b822f 100644 --- a/packages/core/tools/src/presentation.ts +++ b/packages/core/tools/src/presentation.ts @@ -8,19 +8,17 @@ import type { ContentBlock } from '@deepseek-ai/dsh-llm' /** - * Category of a tool call, used by a UI to pick an icon / treatment. A neutral - * vocabulary owned here (NOT an ACP type) so tools describe themselves without - * depending on any client protocol; a UI bridge maps it to its own enum. The - * member set mirrors the common ACP `ToolKind` values; `other` is the default. + * Category of a tool call, used by a UI to pick an icon or treatment. The + * provider-neutral vocabulary lets tools describe themselves without depending + * on a particular client; `other` is the default. */ export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other' /** * A file location a tool reads or modifies, so a capable UI can "follow along" — - * highlight or jump to the file (and line) as the tool runs. Provider-neutral; - * a UI bridge maps it to its own affordance (the ACP bridge forwards it as - * `tool_call.locations`). `path` is what the tool operated on (the model-facing - * path); `line` is an optional 1-based line to focus (e.g. a read's offset). + * highlight or jump to the file (and line) as the tool runs. `path` is what the + * tool operated on (the model-facing path); `line` is an optional 1-based line + * to focus (e.g. a read's offset). */ export interface FileLocation { path: string @@ -29,10 +27,9 @@ export interface FileLocation { /** * A single-file change a tool is about to make, for a UI that renders inline - * diffs (an editor's diff card). Provider-neutral; the ACP bridge forwards it as - * a `{ type: 'diff' }` tool-call content block. `oldText` is `null` for a - * new-file create (nothing to diff against); an overwrite also uses `null`, - * because a call-time presenter has no access to the file's prior content. + * diffs. `oldText` is `null` for a new-file create (nothing to diff against); + * an overwrite also uses `null`, because a call-time presenter has no access to + * the file's prior content. */ export interface FileDiff { path: string diff --git a/packages/core/tools/tests/code-mode.spec.ts b/packages/core/tools/tests/code-mode.spec.ts index 0681ffc571..14f80c66d2 100644 --- a/packages/core/tools/tests/code-mode.spec.ts +++ b/packages/core/tools/tests/code-mode.spec.ts @@ -696,10 +696,8 @@ describe('the run_code dispatch bridge', () => { it('presents the program as the execute-card title', async () => { const { ctx } = await setup({ mode: 'code' }) const tool = ctx.tools.get(RUN_CODE_NAME)! - // The program IS the title, mirroring how command tools title their cards - // with the command: an ACP client's execute-card header is the only - // always-visible slot (Zed renders no body content and no raw input for - // execute-kind cards without a real terminal). + // The program is the title, mirroring how command tools label their cards + // with the command while retaining the same value in the expanded input. expect(tool.presentCall?.({ code: 'return 1' })).toEqual({ card: 'generic', title: 'return 1', diff --git a/packages/examples/README.md b/packages/examples/README.md index d247577b44..53f8583ce8 100644 --- a/packages/examples/README.md +++ b/packages/examples/README.md @@ -7,12 +7,12 @@ Pre-composed plugin bundles a thin leaf `cordis.yml` loads instead of assembling | `agent-spine-demo/` | `@deepseek-ai/dsh-agent-spine-demo` | The executor-less/UI-less agent spine as one bundle plugin, with fallback session titles and an opt-in persisted-goal stack | | `tui-demo/` | `@deepseek-ai/dsh-tui-demo` | Full-screen terminal app: the spine + persisted goals + `/goal` command + JSONL persistence + `dsh-tui` + a pre-created `main` agent, with a boot `bin` | | `cli-demo/` | `@deepseek-ai/dsh-cli-demo` | Headless one-shot app: the spine + JSONL persistence + a pre-created `main` agent, with text and DSH-native JSON output | -| `acp-demo/` | `@deepseek-ai/dsh-acp-demo` | ACP server app: the spine + persisted goals + `/goal` command + JSONL persistence + the [`acp`](../ui/acp/README.md) bridge (no stdout logger), with a boot `bin` | +| `acp-demo/` | `@deepseek-ai/dsh-acp-demo` | ACP automation server app: the spine + persisted goals + JSONL persistence + the [`acp`](../acp/acp/README.md) bridge (no stdout logger), with a boot `bin` | | `jsonrpc-demo/` | `@deepseek-ai/dsh-jsonrpc-demo` | Bin-only runtime that boots an external `cordis.yml` for the stdio JSON-RPC SDK client | -`agent-spine-demo` is the shared bundle; `tui-demo`, `cli-demo`, and `acp-demo` compose it with full-screen terminal, headless one-shot, and ACP front doors and own their boot bins. `jsonrpc-demo` mounts no composition of its own — it boots whatever tree the deployment's `cordis.yml` names, and is what the Python SDK runtime launches. +`agent-spine-demo` is the shared bundle; `tui-demo`, `cli-demo`, and `acp-demo` compose it with full-screen terminal, headless one-shot, and ACP automation front doors and own their boot bins. `jsonrpc-demo` mounts no composition of its own — it boots whatever tree the deployment's `cordis.yml` names, and is what the Python SDK runtime launches. -These are **not** product API. The spine pieces they bundle live in [`core/`](../core/README.md), the bridges/channels/boot-glue in [`ui/`](../ui/README.md), and the swappable backends (LLM adapter, bash executor) in their capability groups; a demo bundle just picks one concrete composition of them. Swap or fork one freely. +These are **not** product API. The spine pieces they bundle live in [`core/`](../core/README.md), human/SDK channels and boot glue in [`ui/`](../ui/README.md), the automation transport in [`acp/`](../acp/README.md), and swappable backends in their capability groups; a demo bundle just picks one concrete composition of them. Swap or fork one freely. Do not confuse this group with the repo-root [`examples/`](../../examples/AGENTS.md): that directory holds the runnable `cordis.yml` **leaves**; this group holds the **bundles** those leaves load. diff --git a/packages/examples/acp-demo/README.md b/packages/examples/acp-demo/README.md index bd8c980993..e215a80939 100644 --- a/packages/examples/acp-demo/README.md +++ b/packages/examples/acp-demo/README.md @@ -1,77 +1,57 @@ # @deepseek-ai/dsh-acp-demo -The **ACP server app**: a Cordis app plugin that composes the default agent spine ([`@deepseek-ai/dsh-agent-spine-demo`](../agent-spine-demo/README.md)) with the front-door cluster an [Agent Client Protocol](../../ui/acp/README.md) server needs, and a `bin` that boots a leaf `cordis.yml` speaking ACP JSON-RPC on stdio. +ACP automation server app: the default agent spine, client-created agents through [`@deepseek-ai/dsh-acp`](../../acp/acp/README.md), JSONL persistence, and semantic checkpointing behind one JSON-RPC stdio bin. Programmatic clients create fresh sessions; this package mounts no human UI. -It is the structured counterpart to [`@deepseek-ai/dsh-tui-demo`](../tui-demo/README.md): both consume the same spine, but ACP creates sessions from its client and reserves stdout for its wire protocol. +## Composition -## What it bakes in — and what it deliberately omits - -stdout is the ACP JSON-RPC channel, so the cluster is defined as much by what it LEAVES OUT as what it includes: - -| Plugin | Why | +| Plugin | Role | |---|---| -| `@deepseek-ai/dsh-agent-spine-demo` | the spine, pre-creating **no** agents (ACP `session/new` creates them on demand) | -| `@deepseek-ai/dsh-commands` | the human-command registry used for ACP discovery and direct slash dispatch | -| `@deepseek-ai/dsh-command-goal` | the discoverable direct `/goal` producer; the app enables the spine's persisted-goal stack with it | -| `@deepseek-ai/dsh-user-interaction` | the human question/answer seam used by clients that can complete ACP elicitation requests | -| `@deepseek-ai/dsh-session-persistence-jsonl` | durable JSONL session log (the bridge advertises `loadSession`) | -| `@deepseek-ai/dsh-session-query-sqlite` + `@deepseek-ai/dsh-session-reference` | combined exact/FTS session queries and bounded `dsh-session:` snapshots; the default leaf adds the model-facing query tools | -| `@deepseek-ai/dsh-session-checkpoint-policy` | semantic durability barriers before model requests and top-level tool effects, plus completed-step checkpoints | -| `@deepseek-ai/dsh-acp` | the bridge that owns stdout for JSON-RPC and provides ACP-backed user answers when a leaf explicitly exposes a user-question tool | -| ~~`@deepseek-ai/dsh-tool-ask-user`~~ | **omitted by default** — ACP elicitation support is still client-dependent, so leaves must opt in deliberately | -| ~~`@deepseek-ai/dsh-user-approval`~~ | **omitted by default** — permission policy is deployment-specific; sandbox/approval leaves opt in and the ACP bridge then supplies the answerer | -| ~~console logger~~ | **omitted** — it writes to stdout and would corrupt the protocol frames ([the stdout-purity footgun](../../ui/acp/README.md)) | -| ~~`hmr`~~ | **omitted** — the editor owns the subprocess | +| `@deepseek-ai/dsh-agent-spine-demo` | Providerless agent spine with no pre-created agents; `session/new` creates each agent. | +| `@deepseek-ai/dsh-session-persistence-jsonl` | Durable session logs used by checkpointing, observability, and snapshot replay. | +| `@deepseek-ai/dsh-session-checkpoint-policy` | Durability barriers before model calls and top-level tool effects, plus completed-step checkpoints. | +| `@deepseek-ai/dsh-session-query-sqlite` | Derived exact/FTS session-query service, opened before the ACP transport so leaf consumers are ready for the first model request. | +| `@deepseek-ai/dsh-acp` | Automation-only ACP transport over stdin/stdout. | -The app owns this cluster through one ordered Cordis effect. Teardown drains the ACP bridge before removing the checkpoint policy or persistence backend, so a graceful disconnect persists the real closing `step/end` and `turn/end` events rather than leaving crash recovery to synthesize them. Because the package wires no logger entry, an ACP leaf has **nothing to get wrong by default**: it only picks backends. A leaf author can still add `@cordisjs/plugin-logger-console` as a sibling entry, so the rule remains: never add a stdout logger to an ACP leaf; use a stderr exporter instead. +The app does not install commands, user interaction, session navigation, configuration pickers, or a stdout logger. It owns these plugins through one ordered effect so the query service is ready before ACP accepts work and ACP sessions quiesce before checkpointing and persistence detach. Leaf configurations supply LLM, executor, sandbox, approval, filesystem, and model-facing tool plugins. ## Config | Key | Default | Routed to | |---|---|---| -| `provider` | (required) | the initial provider route for each per-session agent the bridge creates; ACP model selection may replace it per session | -| `model` | (required) | the initial model for each per-session agent; ACP clients may switch among adapter-advertised models | -| `maxParallelToolCalls` | agent-loop default | positive-integer concurrent tool-call cap shared by the bundled loop's agents; `1` is serial | -| `persona` | — | the deployment persona template (may reference `{{provider}}`/`{{model}}`/`{{cwd}}`), routed to `dsh-system-prompt` | -| `toolOrder` | — | explicit model-facing tool order (a name list with one `'<unlisted-tools>'` rest entry; absent — lexicographic; an unregistered name fails each turn at prompt assembly), routed to `dsh-system-prompt` | -| `dshHome` | `$DSH_HOME` or `~/.dsh` | Harness home exposed to model bash and used by local skill discovery | -| `sessionTitle` | spine example limits | fallback title word/byte limits routed through `dsh-agent-spine-demo` | -| `tools` | `{ mode: 'native' }` | tool-registry presentation config (`native` / `code` / `both`), routed through `dsh-agent-spine-demo` | -| `workspaceContext` | (required) | workspace-instruction byte budget/config, or `false`; routed to the providerless-safe `dsh-workspace-context` plugin | -| `skills` | owner defaults | registry-cache, local-provider, and model-facing skill-tool config, routed through `dsh-agent-spine-demo` | -| `toolBash` | owner defaults | model-facing bash config routed through `dsh-agent-spine-demo`, including bash's producer-local `enableRunInBackground` | -| `toolTasks` | owner defaults | generic `task_output` wait bounds routed through `dsh-agent-spine-demo` | -| `goals` | owner defaults | persisted goal-domain and model-tool config; `false` removes the goal stack and `/goal` producer | -| `llmRetry` | owner defaults | bounded transient model-request retry policy routed through `dsh-agent-spine-demo` | -| `persistenceRoot` | `./.sessions` | the JSONL backend's root directory and the parent of the derived `session-query.db` index | -| `packChunks` | `false` | write delta-chunk runs as packed storage rows (the JSONL backend's `packChunks`) | -| `persistenceCompression` | `'zstd'` | JSONL artifact encoding (`'zstd'` or raw `'none'`) | -| `sessionReferences` | service defaults | cross-session candidate and snapshot limits routed to `dsh-session-reference` | +| `provider` | required | Provider route for each ACP-created agent. | +| `model` | required | Model for each ACP-created agent. | +| `maxParallelToolCalls` | agent-loop default | Positive-integer tool-call concurrency cap; `1` is serial. | +| `persona` | — | Deployment persona template for `dsh-system-prompt`. | +| `toolOrder` | lexicographic | Explicit model-facing tool order for `dsh-system-prompt`. | +| `tools` | `{ mode: 'native' }` | Native, Code Mode, or combined model tool transport. | +| `dshHome` | `$DSH_HOME` or `~/.dsh` | Harness home shared by bash and local skill discovery. | +| `sessionTitle` | spine example limits | Durable fallback-title limits; titles remain off the ACP wire. | +| `persistenceRoot` | `./.sessions` | JSONL backend root and parent directory of the derived `session-query.db` index. | +| `packChunks` | `false` | Pack consecutive delta-chunk events in storage. | +| `persistenceCompression` | `zstd` | Checksummed Zstandard frames or raw `none`. | +| `workspaceContext` | required | Workspace-instruction byte budget/config, or `false`. | +| `skills` | owner defaults | Skill registry, local provider, and model-facing skill tool. | +| `toolBash` | owner defaults | Model-facing bash tool config. | +| `toolTasks` | owner defaults | Generic background-task control config, or `false`. | +| `goals` | owner defaults | Persisted same-session goal domain and model tools, or `false`. | +| `llmRetry` | owner defaults | Bounded transient model-request retry policy. | -The leaf supplies the swappable backends: an LLM adapter (`llm-deepseek` for the real model, `llm-replay` for keyless snapshot replay), a bash executor, and optionally a `ctx.fs` provider. Workspace context becomes a no-op without `ctx.fs`; the shipped [`examples/acp-agent/cordis.yml`](../../../examples/acp-agent/cordis.yml) selects `dsh-sandbox-policy`, `dsh-fs-sandbox`, `dsh-fs-policy`, and `dsh-tool-fs` so baseline instructions and model-facing `read`/`write`/`edit` share one provider, sandbox mode, workspace root, and observed-version policy. +The shipped [`examples/acp-agent/cordis.yml`](../../../examples/acp-agent/cordis.yml) adds the DeepSeek adapter, sandboxed bash and filesystem providers, one-shot approval policy, compaction, subagents, workflows, hooks, a derived session-query index, generic timeout and spill policies, and model-facing tools. Snapshot overlays replace only nondeterministic providers or policy values. -## The bin +## Bin -`dsh-acp-demo [--config path-to-cordis.yml]` (short form `-c`; default `./cordis.yml`): - -- loads a gitignored `.env` from the cwd — **skipped** in snapshot REPLAY so a stray key can never trigger a live call; -- honors `DSH_SNAPSHOT=replay` by booting the sibling `cordis.snapshot.yml` (the keyless replay tree, `llm-replay` in place of `llm-deepseek`); -- in a snapshot run, disposes the context on stdin EOF so the session log is fully flushed before exit. - -The repository installs Loader's optional `node-addon-require-builtin` peer, so the built bin resolves bare plugin specifiers through the internal module loader under plain Node. (`demo:acp` runs under tsx, whose tsconfig `paths` map resolves them instead.) - -All diagnostics go to **stderr** — stdout is the protocol. +`dsh-acp-demo [--config path-to-cordis.yml]` (short form `-c`; default `./cordis.yml`) loads the gitignored `.env`, except in replay mode; `DSH_SNAPSHOT=replay` selects the sibling `cordis.snapshot.yml`; stdin EOF disposes the context and flushes sessions before exit. Loader's installed optional `node-addon-require-builtin` peer resolves bare plugin specifiers for the built bin under plain Node. Diagnostics use stderr because stdout is the ACP wire. ## Model Experience -Indirectly, through `dsh-agent-spine-demo` and `dsh-acp`, which compose each ACP agent's prompt, goal tools, and message history. Direct `/goal` input and output remain outside the model, while accepted mutations append domain-owned model-visible snapshots. +Indirectly, through `dsh-agent-spine-demo` and the leaf's model-facing plugins. ACP prompt text becomes the ordinary logged user message; protocol metadata and permission choices do not enter the model request. #### KV Cache effect -No direct invalidation; the named consumer owns any request-prefix changes. +Append-only per session; the app adds no request-prefix content itself. ## Known Limitations and Deferred Work -- **JSONL persistence is baked in** — config chooses its root but cannot select a different backend; that requires a sibling entry or differently composed app package. -- **User-question and approval mechanisms are omitted by default** — the bridge can answer both when their services/tools are composed, but this front door does not enable those deployment policies itself. -- **A leaf can still corrupt stdout** — the app mounts no console logger, but it cannot prevent a sibling leaf entry from writing non-protocol bytes to the ACP channel. +- **JSONL persistence is fixed** — a different backend requires another composition. +- **Sibling plugins can corrupt stdout** — the app cannot prevent another entry from writing non-protocol bytes. +- **Fresh automation sessions only** — resume and human interaction belong to other front doors. diff --git a/packages/examples/acp-demo/package.json b/packages/examples/acp-demo/package.json index 36de692404..8edf3a43d3 100644 --- a/packages/examples/acp-demo/package.json +++ b/packages/examples/acp-demo/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-acp-demo", - "description": "ACP server app: agent spine + human commands + JSONL persistence + ACP bridge (no stdout logger, hmr, or pre-created agents), with a JSON-RPC stdio bin", + "description": "ACP automation server app: agent spine + JSONL persistence + ACP transport, with a JSON-RPC stdio bin", "version": "0.0.1", "private": true, "type": "module", @@ -38,8 +38,6 @@ "@cordisjs/plugin-include": "^1.0.4", "@cordisjs/plugin-loader": "^1.0.0-rc.5", "@deepseek-ai/dsh-acp": "^0.0.1", - "@deepseek-ai/dsh-commands": "^0.0.1", - "@deepseek-ai/dsh-command-goal": "^0.0.1", "@deepseek-ai/dsh-agent-spine-demo": "^0.0.1", "@deepseek-ai/dsh-app-boot": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", @@ -47,9 +45,7 @@ "@deepseek-ai/dsh-session-persistence-jsonl": "^0.0.1", "@deepseek-ai/dsh-session-query": "^0.0.1", "@deepseek-ai/dsh-session-query-sqlite": "^0.0.1", - "@deepseek-ai/dsh-session-reference": "^0.0.1", "@deepseek-ai/dsh-tools": "^0.0.1", - "@deepseek-ai/dsh-user-interaction": "^0.0.1", "@deepseek-ai/dsh-workspace-context": "^0.0.1", "cordis": "^4.0.0-rc.7", "schemastery": "^3.17.0" @@ -58,8 +54,6 @@ "@cordisjs/plugin-include": "workspace:^", "@cordisjs/plugin-loader": "workspace:^", "@deepseek-ai/dsh-acp": "workspace:^", - "@deepseek-ai/dsh-commands": "workspace:^", - "@deepseek-ai/dsh-command-goal": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-spine-demo": "workspace:^", "@deepseek-ai/dsh-app-boot": "workspace:^", @@ -68,10 +62,8 @@ "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", "@deepseek-ai/dsh-session-query": "workspace:^", "@deepseek-ai/dsh-session-query-sqlite": "workspace:^", - "@deepseek-ai/dsh-session-reference": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", - "@deepseek-ai/dsh-user-interaction": "workspace:^", "@deepseek-ai/dsh-workspace-context": "workspace:^", "cordis": "^4.0.0-rc.7", "schemastery": "^3.17.0" diff --git a/packages/examples/acp-demo/src/bin.ts b/packages/examples/acp-demo/src/bin.ts index 60127760e4..3f528a5fca 100644 --- a/packages/examples/acp-demo/src/bin.ts +++ b/packages/examples/acp-demo/src/bin.ts @@ -5,7 +5,7 @@ * loading, Loader guards, snapshot config selection, and settled-tree boot live * in dsh-app-boot. Replay skips `.env` and selects sibling * `cordis.snapshot.yml` so a stray key cannot trigger a model call. EOF disposes - * and flushes snapshot runs; editors normally own process lifetime. Stdout is + * and flushes snapshot runs; the calling automation owns process lifetime. Stdout is * reserved for JSON-RPC, so diagnostics go only to stderr. * @module @deepseek-ai/dsh-acp-demo/bin */ diff --git a/packages/examples/acp-demo/src/index.ts b/packages/examples/acp-demo/src/index.ts index 1a05a14e3e..833cc723fd 100644 --- a/packages/examples/acp-demo/src/index.ts +++ b/packages/examples/acp-demo/src/index.ts @@ -1,7 +1,7 @@ /** - * The ACP server app: the default agent spine ({@link @deepseek-ai/dsh-agent-spine-demo}), - * human-command registry, JSONL session persistence, and the - * {@link @deepseek-ai/dsh-acp} bridge. The app owns those plugins through one + * The ACP automation server app: the default agent spine + * ({@link @deepseek-ai/dsh-agent-spine-demo}), JSONL session persistence, and + * the {@link @deepseek-ai/dsh-acp} bridge. The app owns those plugins through one * ordered lifecycle so ACP sessions quiesce before persistence detaches. It * writes nothing to stdout. * It pre-creates no agents and leaves adapters, executors, and optional tools to @@ -15,8 +15,6 @@ import type { Context } from 'cordis' import { join } from 'node:path' import z from 'schemastery' import * as acp from '@deepseek-ai/dsh-acp' -import CommandService from '@deepseek-ai/dsh-commands' -import * as commandGoal from '@deepseek-ai/dsh-command-goal' import * as agentCore from '@deepseek-ai/dsh-agent-spine-demo' import * as workspaceContext from '@deepseek-ai/dsh-workspace-context' import ToolRegistry, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools' @@ -25,17 +23,14 @@ import SessionPersistenceJsonl, { type JsonlCompression, } from '@deepseek-ai/dsh-session-persistence-jsonl' import * as sessionCheckpointPolicy from '@deepseek-ai/dsh-session-checkpoint-policy' -import UserInteractionService from '@deepseek-ai/dsh-user-interaction' import SessionQuerySqlite from '@deepseek-ai/dsh-session-query-sqlite' -import SessionReferenceService, { type Config as SessionReferenceConfig } from '@deepseek-ai/dsh-session-reference' export const name = 'acp-demo' const DEFAULT_PERSISTENCE_ROOT = './.sessions' /** - * App config: the swappable per-deployment values. `provider` and `model` configure the - * agent template the ACP bridge creates each session's agent from (NOT a - * pre-created agent — ACP creates agents at `session/new`); `persona` is the + * App config: the swappable per-deployment values. `provider` and `model` configure + * each agent the ACP bridge creates at `session/new`; `persona` is the * deployment persona (forwarded to the system-prompt plugin); `toolOrder` is * the explicit model-facing tool order (forwarded to the system-prompt plugin); * `tools` is the tool registry's config (its presentation `mode`, forwarded @@ -64,8 +59,6 @@ export interface Config { packChunks?: boolean /** JSONL artifact encoding; defaults to checksummed Zstandard frames. */ persistenceCompression?: JsonlCompression - /** Cross-session reference discovery and snapshot byte budgets. */ - sessionReferences?: SessionReferenceConfig /** Controls automatic AGENTS.md/CLAUDE.md loading; configure a byte budget or set `false`. */ workspaceContext: agentCore.Config['workspaceContext'] /** Skill registry, local-provider, and model-facing consumer config forwarded to agent-spine-demo. */ @@ -74,7 +67,7 @@ export interface Config { toolBash?: NonNullable<agentCore.Config['toolBash']> /** Generic background-task controls forwarded through agent-core; set false to omit their tool surface. */ toolTasks?: NonNullable<agentCore.Config['toolTasks']> - /** Persisted same-session goals; owner defaults enable them, or false disables the stack and command. */ + /** Persisted same-session goals; owner defaults enable them, or false disables the stack and tools. */ goals?: agentCore.GoalConfig | false /** Bounded transient model-request retry policy forwarded through agent-core. */ llmRetry?: NonNullable<agentCore.Config['llmRetry']> @@ -98,7 +91,6 @@ export const Config: z<Config> = z.object({ persistenceRoot: z.string().default(DEFAULT_PERSISTENCE_ROOT), packChunks: z.boolean().default(false), persistenceCompression: JsonlCompressionSchema, - sessionReferences: SessionReferenceService.Config, workspaceContext: z.union([z.const(false), workspaceContext.Config]).required(), skills: agentCore.SkillConfigSchema, toolBash: agentCore.ToolBashConfigSchema, @@ -109,7 +101,7 @@ export const Config: z<Config> = z.object({ /* jscpd:ignore-end */ /** - * Compose the spine with the ACP front door. The agent-spine-demo bundle pre-creates + * Compose the spine with the ACP automation transport. The agent-spine-demo bundle pre-creates * NO agents (its `agents` list defaults to `[]`) and carries the deployment * `persona`; the JSONL backend and derived query index persist under * `persistenceRoot`; the ACP bridge owns stdout for JSON-RPC and creates one @@ -118,26 +110,32 @@ export const Config: z<Config> = z.object({ * attached until ACP agents have flushed their closing events. No logger, no * `hmr` — stdout stays pure. */ -export function apply(ctx: Context, config: Config): void { +export async function apply(ctx: Context, config: Config): Promise<void> { const goals = config.goals ?? {} const persistenceRoot = config.persistenceRoot ?? DEFAULT_PERSISTENCE_ROOT - ctx.effect(function* () { - yield ctx.plugin(CommandService).dispose - if (goals !== false) yield ctx.plugin(commandGoal).dispose - yield ctx.plugin(agentCore, { ...agentCore.pickSpineConfig(config), goals }).dispose - yield ctx.plugin(UserInteractionService).dispose + await ctx.effect(async function* () { + const spine = ctx.plugin(agentCore, { ...agentCore.pickSpineConfig(config), goals }) + await spine + yield spine.dispose // Same rationale as the Config schema above: each front door forwards its own // persistence passthroughs rather than sharing a facade with stdio-demo. /* jscpd:ignore-start */ - yield ctx.plugin(SessionPersistenceJsonl, { + const persistence = ctx.plugin(SessionPersistenceJsonl, { root: persistenceRoot, ...config.packChunks !== undefined ? { packChunks: config.packChunks } : {}, ...(config.persistenceCompression === undefined ? {} : { compression: config.persistenceCompression }), - }).dispose + }) + await persistence + yield persistence.dispose /* jscpd:ignore-end */ - yield ctx.plugin(sessionCheckpointPolicy).dispose - yield ctx.plugin(SessionQuerySqlite, { path: join(persistenceRoot, 'session-query.db') }).dispose - yield ctx.plugin(SessionReferenceService, config.sessionReferences ?? {}).dispose - yield ctx.plugin(acp, { provider: config.provider, model: config.model }).dispose + const checkpoint = ctx.plugin(sessionCheckpointPolicy) + await checkpoint + yield checkpoint.dispose + const query = ctx.plugin(SessionQuerySqlite, { path: join(persistenceRoot, 'session-query.db') }) + await query + yield query.dispose + const transport = ctx.plugin(acp, { provider: config.provider, model: config.model }) + await transport + yield transport.dispose }, 'acp-demo.composition') } diff --git a/packages/examples/acp-demo/tests/acp-agent.spec.ts b/packages/examples/acp-demo/tests/acp-agent.spec.ts index 18cd0b5221..b2b9c87ad6 100644 --- a/packages/examples/acp-demo/tests/acp-agent.spec.ts +++ b/packages/examples/acp-demo/tests/acp-agent.spec.ts @@ -5,7 +5,6 @@ import { tmpdir } from 'node:os' import { Context } from 'cordis' import Loader from '@cordisjs/plugin-loader' import { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' -import { SessionId } from '@deepseek-ai/dsh-session' import { TOOL_ORDER_REST } from '@deepseek-ai/dsh-system-prompt' import type { Message } from '@deepseek-ai/dsh-llm' import * as acpAgent from '../src/index.ts' @@ -31,9 +30,6 @@ async function mount(config: acpAgent.Config, withBash = false): Promise<Context }) } await ctx.plugin(acpAgent, config) - // The bundle mounts its children inside apply() (not awaited there); let their - // fibers settle so the spine services are ready. - await new Promise(resolve => setTimeout(resolve, 50)) return ctx } @@ -84,7 +80,6 @@ describe('dsh-acp-demo composition', () => { persona: 'hi', persistenceRoot: '/tmp/dsh-acp-demo-test', persistenceCompression: 'none', - sessionReferences: { candidateLimit: 1 }, skills: await isolatedSkillsConfig(), workspaceContext: false, }) @@ -92,24 +87,20 @@ describe('dsh-acp-demo composition', () => { expect(ctx.get('sessions')).toBeDefined() expect(ctx.get('sessionPersistence')).toBeDefined() expect(ctx.get('sessionQuery')).toBeDefined() - expect(ctx.get('sessionReferences')).toBeDefined() + expect(ctx.get('sessionReferences')).toBeUndefined() expect((ctx.get('sessionPersistence') as unknown as { config: { compression?: string } }).config.compression).toBe('none') expect(ctx.get('agentLoop')).toBeDefined() - expect(ctx.get('userInteraction')).toBeDefined() + expect(ctx.get('userInteraction')).toBeUndefined() + expect(ctx.get('commands')).toBeUndefined() expect(ctx.get('tools')?.get('ask_user_question')).toBeUndefined() expect(ctx.get('goals')).toBeDefined() expect(ctx.get('tools')?.get('get_goal')).toBeDefined() - const target = ctx.sessions.create(SessionId('candidate-target')) - ctx.sessions.create(SessionId('candidate-one')) - ctx.sessions.create(SessionId('candidate-two')) - await expect(ctx.sessionReferences.listCandidates({ id: target.id, session: target } as Agent)) - .resolves.toHaveLength(1) // No pre-created agents — ACP session/new creates them on demand. expect(ctx.get('agents')!.list()).toHaveLength(0) await ctx.fiber.dispose() }) - it('can explicitly omit the persisted-goal stack and its command', async () => { + it('can explicitly omit the persisted-goal stack', async () => { const ctx = await mount({ provider: 'mock', model: 'mock', @@ -117,12 +108,7 @@ describe('dsh-acp-demo composition', () => { workspaceContext: false, }) expect(ctx.get('goals')).toBeUndefined() - const handle = await ctx.agents.create({ - sessionId: 'disabled-goals' as import('@deepseek-ai/dsh-session').SessionId, - agentOptions: { provider: 'mock', model: 'mock' }, - }) - expect(ctx.commands.find(handle.agent, 'goal')).toBeUndefined() - await handle.dispose() + expect(ctx.get('tools')?.get('get_goal')).toBeUndefined() await ctx.fiber.dispose() }) @@ -133,8 +119,12 @@ describe('dsh-acp-demo composition', () => { // persistenceRoot, so the runtime fallback is the one that fires. const ctx = new Context() // No persona: covers the omitted-persona forwarding branch too. - acpAgent.apply(ctx, { provider: 'mock', model: 'mock', skills: await isolatedSkillsConfig(), workspaceContext: false }) - await new Promise(resolve => setTimeout(resolve, 50)) + await acpAgent.apply(ctx, { + provider: 'mock', + model: 'mock', + skills: await isolatedSkillsConfig(), + workspaceContext: false, + }) expect(ctx.get('sessionPersistence')).toBeDefined() await ctx.fiber.dispose() }) @@ -155,8 +145,7 @@ describe('dsh-acp-demo composition', () => { it('uses default skill config when apply is called directly without skills', async () => { await withIsolatedSkillHomes(async () => { const ctx = new Context() - acpAgent.apply(ctx, { provider: 'mock', model: 'mock', workspaceContext: false }) - await new Promise(resolve => setTimeout(resolve, 50)) + await acpAgent.apply(ctx, { provider: 'mock', model: 'mock', workspaceContext: false }) expect(ctx.skills).toBeDefined() expect(await ctx.skills.list()).toEqual([]) await ctx.fiber.dispose() diff --git a/packages/examples/acp-demo/tests/built-bin.e2e.ts b/packages/examples/acp-demo/tests/built-bin.e2e.ts index eb49988dc8..02e82ac5ac 100644 --- a/packages/examples/acp-demo/tests/built-bin.e2e.ts +++ b/packages/examples/acp-demo/tests/built-bin.e2e.ts @@ -18,7 +18,6 @@ import { Readable, Writable } from 'node:stream' import { promisify } from 'node:util' import { zstdDecompress } from 'node:zlib' import { afterEach, describe, expect, it } from 'vitest' -import { ACP_SESSION_REFERENCE_META_KEY } from '@deepseek-ai/dsh-acp' /** * Published-entry smoke: run `lib/bin.js` under plain Node in a symlinked external consumer and @@ -36,8 +35,7 @@ const dshPackages = [ 'bash/bash-local', 'bash/tool-bash', 'context/workspace-context', 'support/invariants', 'ui/app-boot', 'session-persistence/session-persistence', 'session-persistence/session-checkpoint-policy', 'session-persistence/session-persistence-jsonl', - 'session-query/session-query', 'session-query/session-query-sqlite', - 'context/session-reference', 'ui/acp', 'examples/acp-demo', 'util/paths', + 'acp/acp', 'examples/acp-demo', 'util/paths', ] const vendorPackages = [ 'cordis', 'loader', 'include', 'timer', 'hmr', 'logger-console', @@ -45,8 +43,8 @@ const vendorPackages = [ ] // Resolve ACP's declared third-party dependencies from that package, not this test: pnpm's strict // layout need not hoist them. Symlink those exact paths into the plain-Node consumer. -const npmDeps = ['@agentclientprotocol/sdk', 'zod'] -const acpPkgDir = join(repoRoot, 'packages/ui/acp') +const npmDeps = ['@agentclientprotocol/sdk'] +const acpPkgDir = join(repoRoot, 'packages/acp/acp') async function pkgName(absDir: string): Promise<string> { const json = JSON.parse(await readFile(join(absDir, 'package.json'), 'utf8')) as { name: string } @@ -72,7 +70,7 @@ async function makeConsumer(): Promise<string> { await link(abs, await pkgName(abs), nm) } for (const dep of npmDeps) { - // Resolve from `ui/acp`'s package.json URL (the package that declares the + // Resolve from ACP's package.json URL (the package that declares the // dep), not this test file's location — `acp-agent` does not depend on these. const fromAcp = pathToFileURL(join(acpPkgDir, 'package.json')).href const resolved = fileURLToPath(import.meta.resolve(`${dep}/package.json`, fromAcp)) @@ -154,8 +152,12 @@ describe.skipIf(!existsSync(acpBin))('dsh-acp-demo BUILT bin (node lib/bin.js, n Writable.toWeb(child.stdin!) as WritableStream<Uint8Array>, Readable.toWeb(passthrough) as ReadableStream<Uint8Array>, ) + const updates: SessionNotification['update'][] = [] const makeClient = (_a: AcpAgent): Client => ({ - sessionUpdate(_p: SessionNotification): Promise<void> { return Promise.resolve() }, + sessionUpdate(params: SessionNotification): Promise<void> { + updates.push(params.update) + return Promise.resolve() + }, requestPermission(_p: RequestPermissionRequest): Promise<RequestPermissionResponse> { return Promise.resolve({ outcome: { outcome: 'cancelled' } }) }, @@ -163,33 +165,17 @@ describe.skipIf(!existsSync(acpBin))('dsh-acp-demo BUILT bin (node lib/bin.js, n const client = new ClientSideConnection(makeClient, stream) const init = await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - // A response at all proves the built bin booted the bridge (the settle-race - // regression would exit before answering); loadSession proves the real app - // mounted, not a collapsed export shape. - expect(init.agentCapabilities?.loadSession).toBe(true) - expect(init.agentCapabilities?.sessionCapabilities?.list).toEqual({}) + expect(init.agentCapabilities).toEqual({ + promptCapabilities: { image: false, audio: false, embeddedContext: false }, + }) const sessionCwd = consumer const { sessionId } = await client.newSession({ cwd: sessionCwd, mcpServers: [] }) const result = await client.prompt({ sessionId, prompt: [{ type: 'text', text: 'reply' }] }) expect(result.stopReason).toBe('end_turn') - await expect.poll(async () => { - return (await client.listSessions({ cwd: sessionCwd })).sessions.find(candidate => candidate.sessionId === sessionId) - }).toMatchObject({ - sessionId, - cwd: sessionCwd, - title: 'reply', - }) - const listed = await client.listSessions({ cwd: sessionCwd }) - const reference = listed.sessions.find(candidate => candidate.sessionId === sessionId) - ?._meta?.[ACP_SESSION_REFERENCE_META_KEY] - expect(reference).toBeTypeOf('object') - expect(reference).not.toBeNull() - expect(reference).toHaveProperty('uri') - if (typeof reference !== 'object' || reference === null || !('uri' in reference)) { - throw new Error('expected session reference metadata') - } - expect(reference.uri).toBeTypeOf('string') - expect(reference.uri).toMatch(/^dsh-session:[A-Za-z0-9_-]+$/u) + await expect.poll(() => updates).toEqual([{ + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'ACP BUILT OK' }, + }]) const sessionsRoot = join(sessionCwd, '.sessions') let log: string | undefined await expect.poll(async () => { diff --git a/packages/examples/acp-demo/tests/load-path.e2e.ts b/packages/examples/acp-demo/tests/load-path.e2e.ts index a866aaa243..9f61e28314 100644 --- a/packages/examples/acp-demo/tests/load-path.e2e.ts +++ b/packages/examples/acp-demo/tests/load-path.e2e.ts @@ -17,11 +17,10 @@ import { } from '@agentclientprotocol/sdk' /** - * Source-path Loader smoke through the package's own bin, covering initialize, session/new, and - * session/load across the `unwrapExports` path implicated by postmortem 0001. Session creation and - * unknown-id loading reach factories but not the model, so a dummy key is sufficient. The temp cwd - * is also the session workspace, and an explicit root tsconfig keeps unbuilt path aliases resolvable - * when the child starts outside the repository. + * Source-path Loader smoke through the package's own bin, covering the + * automation server's initialize and fresh-session path across the + * `unwrapExports` shape implicated by postmortem 0001. Session creation reaches + * the factory but not the model, so a dummy key is sufficient. */ const binScript = fileURLToPath(new URL('../src/bin.ts', import.meta.url)) @@ -118,7 +117,7 @@ async function boot(): Promise<Spawned & { cwd: string }> { } describe('dsh-acp-demo real-load-path smoke (bin + Loader, keyless)', () => { - it('boots via its bin and answers initialize → session/new → session/load', async () => { + it('boots via its bin and exposes only fresh text sessions', async () => { const { client, cwd, stderr } = await boot() // initialize: a broken export shape (collapsed bridge plugin, dropped inject) // crashes the tree on the first service read here — see postmortem 0001. @@ -126,22 +125,14 @@ describe('dsh-acp-demo real-load-path smoke (bin + Loader, keyless)', () => { protocolVersion: PROTOCOL_VERSION, clientCapabilities: {}, }) - expect(init.agentCapabilities?.loadSession).toBe(true) + expect(init.agentCapabilities).toEqual({ + promptCapabilities: { image: false, audio: false, embeddedContext: false }, + }) // session/new reaches the agent FACTORY (create) without the model. const { sessionId } = await client.newSession({ cwd, mcpServers: [] }) expect(sessionId).toBeTruthy() - // session/load reaches the resume FACTORY + persistence without the model: load an UNKNOWN - // id (loading the live `sessionId` would correctly reject as "already loaded"). Persistence - // and resume run from the JSON-RPC loop outside bridge injection; a healthy tree reaches - // not-found, while a collapsed export would fail earlier with missing injection. - const unknownId = '00000000-0000-4000-8000-000000000000' - await client.loadSession({ sessionId: unknownId, cwd, mcpServers: [] }).then( - () => { throw new Error('expected session/load of an unknown id to reject') }, - (error: unknown) => { expect(String(error)).not.toContain('without inject') }, - ) - expect(stderr.join('')).not.toContain('without inject') }, 30_000) }) diff --git a/packages/examples/acp-demo/tsconfig.json b/packages/examples/acp-demo/tsconfig.json index 0115fc938b..6eeffc5eef 100644 --- a/packages/examples/acp-demo/tsconfig.json +++ b/packages/examples/acp-demo/tsconfig.json @@ -21,7 +21,10 @@ "path": "../../ui/app-boot" }, { - "path": "../../ui/acp" + "path": "../../acp/acp" + }, + { + "path": "../../core/agent" }, { "path": "../../session-query/session-query" @@ -29,30 +32,12 @@ { "path": "../../session-query/session-query-sqlite" }, - { - "path": "../../context/session-reference" - }, - { - "path": "../../ui/commands" - }, - { - "path": "../../goal/command-goal" - }, - { - "path": "../../core/agent" - }, { "path": "../agent-spine-demo" }, { "path": "../../context/workspace-context" }, - { - "path": "../../ui/user-interaction" - }, - { - "path": "../../ui/tool-ask-user" - }, { "path": "../../session-persistence/session-checkpoint-policy" }, diff --git a/packages/examples/agent-spine-demo/README.md b/packages/examples/agent-spine-demo/README.md index 57d5922535..05ea5c75e2 100644 --- a/packages/examples/agent-spine-demo/README.md +++ b/packages/examples/agent-spine-demo/README.md @@ -45,7 +45,7 @@ The spine is everything COMMON to every front door. The swappable and front-door - **model-backed session-title providers** — the bundle mounts the fallback service with overridable example limits (5 words, 40 fallback bytes, 80 accepted-title bytes); a leaf may opt into exactly one first-message or all-messages LLM provider. - **the bash executor** — the bundle ships `tool-bash` (the consumer schema); the leaf provides `ctx.bash` (`bash-local` or a sandboxed impl). - **non-local skill providers** — the bundle ships the skill registry, the local filesystem provider, and the `skill` tool; deployments can add other providers such as embedded or remote catalogs as siblings. -- **presentation + per-app infra** — the terminal TUI or ACP front door and `hmr`. These form the coupled front-door cluster that the app packages ([`dsh-tui-demo`](../tui-demo/README.md), [`dsh-acp-demo`](../acp-demo/README.md)) bake in. `timer` is in the spine because it is common and stdout-silent; front doors own stdout and remain outside. +- **front-door + per-app infra** — the terminal TUI or ACP automation transport and `hmr`. App packages ([`dsh-tui-demo`](../tui-demo/README.md), [`dsh-acp-demo`](../acp-demo/README.md)) own those choices. `timer` is in the spine because it is common and stdout-silent; front doors own stdout and remain outside. This is the [interface/implementation/consumer seam](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md) raised to the composition level: the bundle owns the shared spine, the leaf owns the backends, the app package owns the front door. @@ -63,7 +63,7 @@ For example, `{ invariants: { enabled: true, package_allowlist: ['^@deepseek-ai/ ## Why a code bundle, not a shared YAML include -A YAML include can deduplicate config but cannot own a bin or provide front-door defaults. App packages make stdout-safe ACP wiring the default, though a leaf can still add an unsafe logger. Bundle children register services in the root isolate-keyed store, so injected leaf siblings see them without load-order coupling. +A YAML include can deduplicate config but cannot own a bin or provide front-door defaults. The ACP app package makes protocol-pure stdout wiring the default, though a leaf can still add an unsafe logger. Bundle children register services in the root isolate-keyed store, so injected leaf siblings see them without load-order coupling. The bounded retry policy may repeat a transiently failed request in a new numbered step. Retry status and failed partial chunks stay outside model history, each provider attempt can still incur billing, front doors derive usage across every logged step, and the reconstructed request preserves the prior prefix for provider cache reuse. diff --git a/packages/examples/tui-demo/tests/tui-agent.spec.ts b/packages/examples/tui-demo/tests/tui-agent.spec.ts index f515253dd2..cdab42289b 100644 --- a/packages/examples/tui-demo/tests/tui-agent.spec.ts +++ b/packages/examples/tui-demo/tests/tui-agent.spec.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { join } from 'node:path' import type { Context } from 'cordis' import Loader from '@cordisjs/plugin-loader' import { TOOL_ORDER_REST } from '@deepseek-ai/dsh-system-prompt' @@ -60,7 +61,7 @@ describe('dsh-tui-demo app', () => { ]) expect(calls[0]?.config).toBeUndefined() expect(calls[2]?.config).toEqual({ root: '/tmp/tui-sessions', compression: 'none' }) - expect(calls[4]?.config).toEqual({ path: '/tmp/tui-sessions/session-query.db' }) + expect(calls[4]?.config).toEqual({ path: join('/tmp/tui-sessions', 'session-query.db') }) expect(calls[5]?.config).toEqual({ maxReferences: 2, candidateLimit: 7, diff --git a/packages/fs/tool-fs/src/diff.ts b/packages/fs/tool-fs/src/diff.ts index cf5b808662..48766a9fbc 100644 --- a/packages/fs/tool-fs/src/diff.ts +++ b/packages/fs/tool-fs/src/diff.ts @@ -7,7 +7,7 @@ import { structuredPatch } from 'diff' import type { FileDiff } from '@deepseek-ai/dsh-tools' -/** Context lines shown on each side of an applied hunk (matches claude-agent-acp). */ +/** Context lines shown on each side of an applied hunk. */ export const DIFF_CONTEXT = 3 /** @@ -15,8 +15,7 @@ export const DIFF_CONTEXT = 3 * contextual-diff hunks. Attached opaquely (as `unknown`) on the tool result and * persisted with the session log — it must be JSON-serializable (the session * validates this at `append`), so `presentResult` reproduces the diff card on - * replay. The producing tool owns this shape; the bridge only sees the opaque - * `meta` and the tool narrows it back via {@link diffsFromMeta}. + * replay. The producing tool owns and narrows this opaque shape. */ export type FsDiffMeta = { diffs: FileDiff[] } diff --git a/packages/fs/tool-fs/src/session-cwd.ts b/packages/fs/tool-fs/src/session-cwd.ts index 841769fb4d..396e50351c 100644 --- a/packages/fs/tool-fs/src/session-cwd.ts +++ b/packages/fs/tool-fs/src/session-cwd.ts @@ -1,6 +1,6 @@ /** * Derive the working directory a filesystem tool resolves relative paths against: the calling - * agent's per-session workspace (`exec.agent.session.header.cwd`), so each ACP session's + * agent's per-session workspace (`exec.agent.session.header.cwd`), so each session's * `read`/`write`/`edit` act on ITS workspace, not the server's launch dir — mirroring how * `dsh-tool-bash` defaults a bash `workdir` to the session cwd. * Non-agent calls return `undefined`, leaving the fallback in the provider rather than reading diff --git a/packages/fs/tool-fs/src/write.ts b/packages/fs/tool-fs/src/write.ts index ba96dbe40c..37a6d67e59 100644 --- a/packages/fs/tool-fs/src/write.ts +++ b/packages/fs/tool-fs/src/write.ts @@ -125,9 +125,8 @@ export function applyWriteTool(ctx: Context, sandbox: FsSandboxSurface): void { after: outcome.after, } }, - // Pure display: a diff card (an editor renders write as a new-file / full- replace diff). - // `oldText: null` — a call-time presenter has no access to the file's prior content, so - // even an overwrite renders new-file style, matching claude-agent-acp. + // Pure display: a diff card. A call-time presenter has no access to prior + // file content, so `oldText: null` also represents an overwrite here. presentCall(args): DiffCallView { return { card: 'diff', @@ -136,10 +135,9 @@ export function applyWriteTool(ctx: Context, sandbox: FsSandboxSurface): void { locations: [{ path: args.file_path }], } }, - // Result-time display: a `diff` card so the completed `tool_call_update` re-installs the - // diff rather than the model-facing result text (an ACP `tool_call_update.content` REPLACES - // the call's content, so a text result would clobber the pending diff card). Overwrites use - // applied metadata; creates and identical overwrites use the replay-safe args fallback. + // Result-time display repeats the diff because completed views replace the + // pending view. Overwrites use applied metadata; creates and identical + // overwrites use the replay-safe args fallback. presentResult(args, result: ToolResult): DiffResultView | undefined { if (result.isError) return undefined const diffs = diffsFromMeta(result.meta) diff --git a/packages/fs/tool-fs/tests/diff.spec.ts b/packages/fs/tool-fs/tests/diff.spec.ts index 21f977f0fa..d682bf40b9 100644 --- a/packages/fs/tool-fs/tests/diff.spec.ts +++ b/packages/fs/tool-fs/tests/diff.spec.ts @@ -2,7 +2,7 @@ * Unit tests for the result-time contextual-diff computation (`src/diff.ts`): * the pure before/after → {@link FileDiff}[] hunk builder and the defensive * `meta` narrowing. These pin the exact hunk reconstruction (context lines, - * multi-hunk replaceAll, pure insertion/deletion, no-op) the ACP bridge renders. + * multi-hunk replaceAll, pure insertion/deletion, no-op) that UIs render. */ import { describe, expect, it } from 'vitest' diff --git a/packages/fs/tool-fs/tests/integration.spec.ts b/packages/fs/tool-fs/tests/integration.spec.ts index e911b9addc..c835baebb9 100644 --- a/packages/fs/tool-fs/tests/integration.spec.ts +++ b/packages/fs/tool-fs/tests/integration.spec.ts @@ -284,8 +284,8 @@ describe('bare provider (no dsh-fs-policy)', () => { }) // Per-session cwd: a relative file_path resolves against the calling session's workspace -// (`exec.agent.session.header.cwd`), not the backend's config.cwd — so an ACP editor's -// per-session dir wins, matching dsh-tool-bash. +// (`exec.agent.session.header.cwd`), not the backend's config.cwd, so the +// caller-selected session workspace wins, matching dsh-tool-bash. describe('per-session cwd', () => { let sessionDir: string beforeEach(async () => { diff --git a/packages/fs/tool-fs/tests/tools.spec.ts b/packages/fs/tool-fs/tests/tools.spec.ts index bc193cc23a..8f93b524a9 100644 --- a/packages/fs/tool-fs/tests/tools.spec.ts +++ b/packages/fs/tool-fs/tests/tools.spec.ts @@ -7,7 +7,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join, sep } from 'node:path' +import { join, resolve, sep } from 'node:path' import { CallId } from '@deepseek-ai/dsh-llm' import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' import ToolRegistry from '@deepseek-ai/dsh-tools' @@ -425,8 +425,8 @@ describe('edit tool', () => { }) describe('tool-owned presentation (pure presentCall)', () => { - // presentCall is a pure display function of args (no I/O); it drives the ACP - // card's title/kind and the `locations` an editor follows along to. + // presentCall is a pure display function of args (no I/O); it drives the + // card's title/kind and the `locations` a UI follows along to. const presentCall = async (name: string, args: unknown) => { const { ctx } = await setup() return ctx.tools.get(name)?.presentCall?.(args) @@ -478,7 +478,7 @@ describe('tool-owned presentation (pure presentCall)', () => { describe('result-time contextual diff (meta + presentResult)', () => { // An edit records the applied contextual hunk on `tool/result` meta, and the tool's - // presentResult narrows it back into a `diff` result card the bridge renders. + // presentResult narrows it back into a replayable `diff` result card. const withContext = 'a\nb\nc\nOLD\nd\ne\nf\n' it('edit: execute attaches the applied hunk as meta { diffs }', async () => { @@ -519,9 +519,8 @@ describe('result-time contextual diff (meta + presentResult)', () => { }) it('write CREATE: an empty applied-diff projection still falls back to the whole-file diff card', async () => { - // A create has no prior content, yet the completed card must be a `diff` — an - // ACP tool_call_update.content REPLACES the call's content, so a non-diff result would - // clobber the pending new-file diff. + // A create has no prior content, yet the completed replacement view must + // remain a diff instead of clobbering the pending new-file diff with text. const { ctx } = await setup() const session = { header: {} } const result = await call(ctx, 'write', { file_path: 'new.txt', content: 'fresh\n' }, { session }) @@ -729,13 +728,13 @@ describe('sandbox escalation surface (write/edit)', () => { it('a plain write stamps the default mode with the calling session root', async () => { const { ctx, fs } = await setupConfining() await call(ctx, 'write', { file_path: 'a.txt', content: 'x' }, escalationAgent()) - expect(fs.stamped).toEqual([{ mode: 'workspace-write', workspaceRoot: '/session-project' }]) + expect(fs.stamped).toEqual([{ mode: 'workspace-write', workspaceRoot: resolve('/session-project') }]) }) it('a standing session override folds onto the stamp', async () => { const { ctx, fs } = await setupConfining() await call(ctx, 'write', { file_path: 'a.txt', content: 'x' }, escalationAgent([{ type: 'sandbox/mode', data: { mode: 'read-only' } }])) - expect(fs.stamped).toEqual([{ mode: 'read-only', workspaceRoot: '/session-project' }]) + expect(fs.stamped).toEqual([{ mode: 'read-only', workspaceRoot: resolve('/session-project') }]) }) it('a denied write maps to the shared marker plus the escalation hint (isError)', async () => { @@ -768,7 +767,7 @@ describe('sandbox escalation surface (write/edit)', () => { agent: escalationAgent() as never, signal: new AbortController().signal, }) - expect(fs.stamped).toEqual([{ mode: 'danger-full-access', workspaceRoot: '/session-project' }]) + expect(fs.stamped).toEqual([{ mode: 'danger-full-access', workspaceRoot: resolve('/session-project') }]) }) it('a rejected escalation fails closed with its own text and never mutates', async () => { diff --git a/packages/goal/command-goal/README.md b/packages/goal/command-goal/README.md index d47e5df1e4..2bf52eb5f2 100644 --- a/packages/goal/command-goal/README.md +++ b/packages/goal/command-goal/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-command-goal -Human-facing `/goal` control over [`ctx.goals`](../goal/README.md). The plugin registers one global command through [`ctx.commands`](../../ui/commands/README.md), so every composed command adapter discovers it; the shipped TUI and ACP execute it without a model turn. The [human goal-command Agent Note](../../../.agents/notes/implemented/feature/2026-07-19-human-goal-command.md) owns the UX and composition decisions. +Human-facing `/goal` control over [`ctx.goals`](../goal/README.md). The plugin registers one global command through [`ctx.commands`](../../ui/commands/README.md), so every composed command adapter discovers it; the shipped TUI executes it without a model turn. The [human goal-command Agent Note](../../../.agents/notes/implemented/feature/2026-07-19-human-goal-command.md) owns the UX and composition decisions. ## Command contract @@ -30,7 +30,7 @@ The producer injects `commands` and `goals`. A custom app mounts their owners pl name: '@deepseek-ai/dsh-command-goal' ``` -The TUI and ACP demo apps enable the complete persisted-goal stack and this command by default; `goals: false` removes both. The UI-less `agent-spine-demo` requires an explicit `goals: {}` so headless one-shot callers do not silently change from one physical turn to a multi-round operation. +The TUI app enables the complete persisted-goal stack and this command by default. The ACP automation app enables the domain and model tools without mounting the command registry; `goals: false` removes that stack. The UI-less `agent-spine-demo` requires an explicit `goals: {}` so headless one-shot callers do not silently change from one physical turn to a multi-round operation. ## Model Experience @@ -50,7 +50,7 @@ Command discovery and direct output do not affect the cache. A mutation appends ## Known Limitations and Deferred Work -- **Plain-text interaction only** — the generic command registry has no modal edit form or replacement-confirmation callback; inline edit and explicit clear keep destructive intent deterministic on both TUI and ACP. +- **Plain-text interaction only** — the generic command registry has no modal edit form or replacement-confirmation callback; inline edit and explicit clear keep destructive intent deterministic across adapters. - **No per-command round-cap argument** — `defaultMaxGoalRounds` remains deployment config, while a direct human request may ask the model to edit `max_goal_rounds` through the separately authorized goal tool. - **No continuous status widget** — bare `/goal` is the portable observation surface; adapter-specific badges and reconnectable command output remain future UI work. -- **TUI and ACP only** — the headless CLI and JSON-RPC adapters do not consume `ctx.commands`. Ordinary human prompts can still authorize the model-facing goal tools when those are composed. +- **TUI only in the shipped apps** — the headless CLI, ACP automation, and JSON-RPC adapters do not consume `ctx.commands`. Ordinary prompts can still authorize model-facing goal tools when those are composed. diff --git a/packages/goal/tool-goal/README.md b/packages/goal/tool-goal/README.md index 346ac07dcc..68fd695c9f 100644 --- a/packages/goal/tool-goal/README.md +++ b/packages/goal/tool-goal/README.md @@ -8,7 +8,7 @@ The model-facing control surface for [`ctx.goals`](../goal/README.md): `get_goal - `create_goal(objective, max_goal_rounds?)` creates one goal from a direct top-level human turn. The model may infer long-running goal intent without an exact command phrase; non-human turns and subagents are rejected at execution. - `update_goal(goal_id, revision, action, objective?, max_goal_rounds?, blocked_reason?)` supports `edit`, `pause`, `resume`, `complete`, and `blocked`. Replacements belong only to `edit`; `blocked_reason` is required only for `blocked` and is persisted with the stable code `model-reported`. Strict-schema empty-string and zero fillers count as omitted, while meaningful values remain limited to their action. -All calls are exclusive, so a model-ordered batch observes earlier mutations and their new revisions. ACP and other clients receive pure generic cards: read for `get_goal`, other for mutations. Mutation cards select the first meaningful action value and otherwise show the goal id, so accepted fillers never produce blank input. +All calls are exclusive, so a model-ordered batch observes earlier mutations and their new revisions. UI clients receive pure generic cards: read for `get_goal`, other for mutations. Mutation cards select the first meaningful action value and otherwise show the goal id, so accepted fillers never produce blank input. All three canonical values match the compact JSON already rendered to Native callers: `{ goal: null }` or `{ goal: { id, revision, objective, phase, roundsStarted, maxGoalRounds, blockedReason? }, activation }`. Programmatic consumers therefore receive the same domain structure without parsing the rendered JSON. diff --git a/packages/hooks/hooks-claude/src/index.ts b/packages/hooks/hooks-claude/src/index.ts index 3595d9445c..24c72ce273 100644 --- a/packages/hooks/hooks-claude/src/index.ts +++ b/packages/hooks/hooks-claude/src/index.ts @@ -137,7 +137,7 @@ export function apply(ctx: Context, config: Config): void { const groups: MatcherGroup[] = parsed[point] ?? [] const outputs: HookOutput[] = [] // Run the hook in the agent's session workspace (the `session/new` cwd on the session - // header), not the executor default (the ACP server's launch dir). + // header), not the executor or front-door process's launch dir. const workdir = opts.agent?.session.header.cwd // CLAUDE_PROJECT_DIR: an explicit config value wins; otherwise default it to the session // workspace (the same dir the hook runs in). diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 1badfe65e8..c9bdd73a64 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-host-apiproxy -The ApiProxy front layer every client shape shares: the TS contract (`src/api/`, zero Node dependencies, importable from the browser) and the fetch carrier pair (`src/fetch/`: `toFetchHandler` on the host side, `AbstractApiClient` plus platform subclasses on the client side). Host assembly lives in `dsh-host-runtime`. +The API gateway every client shape shares: the TS contract (`src/api/`, zero Node dependencies, importable from the browser), the fetch carrier pair (`src/fetch/`: `toFetchHandler` on the host side, `AbstractApiClient` plus platform subclasses on the client side), and the host-side implementation (`src/api-proxy.ts`: `createApiProxy` plus the default-exported `ApiProxyService` gateway plugin — config `{provider, model}`, provides `ctx.apiProxy`). Transport-agnostic by design: this package registers no routes; carriers (HTTP today, IPC later) wrap `ctx.apiProxy` themselves. The core spine composition lives in `dsh-host-runtime`. ## Contract layer (`/api`) @@ -24,6 +24,6 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work -- **`respond` routing is shipped, but pending-interaction state is host-side work** — the wire shape (POST `/api/respond`, `RpcReceipt`) is final; the pending table that makes late/duplicate answers meaningful lives in `dsh-host-runtime` and is still a stub there. +- **`respond` routing is shipped, but pending-interaction state is host-side work** — the wire shape (POST `/api/respond`, `RpcReceipt`) is final; the pending table that makes late/duplicate answers meaningful lives in `src/api-proxy.ts` and is still minimal (questions only, no approvals). - **Reserved seams stay out of `RpcMethodMap`** — `session.fork`, `prompt.mode: 'inject'`, `task.list`, `host.listModels`, and a describe `hostInstanceId` are documented reservations; an unknown method fails loud at envelope parse rather than getting a not-implemented code. - **No protocol version field** — client and host ship together; `host.describe` gains a version negotiation field only when an independently released client exists. diff --git a/packages/host/apiproxy/package.json b/packages/host/apiproxy/package.json index fe50c16a60..471cccc96d 100644 --- a/packages/host/apiproxy/package.json +++ b/packages/host/apiproxy/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-host-apiproxy", - "description": "ApiProxy front layer: the TS contract (api/) and the fetch carrier pair (fetch/); host assembly lives in dsh-host-runtime", + "description": "API gateway: the ApiProxy contract (api/), the fetch carrier pair (fetch/), and the host-side gateway plugin providing ctx.apiProxy", "version": "0.0.1", "private": true, "type": "module", @@ -40,12 +40,16 @@ ], "license": "BSD-3-Clause", "dependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-brand": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/dsh-user-approval": "workspace:^", "@deepseek-ai/dsh-user-interaction": "workspace:^", + "schemastery": "^3.18.0", "zod": "^4.4.3" }, "peerDependencies": { diff --git a/packages/host/runtime/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts similarity index 97% rename from packages/host/runtime/src/api-proxy.ts rename to packages/host/apiproxy/src/api-proxy.ts index acf77751af..a5ae45f1af 100644 --- a/packages/host/runtime/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -11,12 +11,14 @@ import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm' import type { JsonValue, Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' +// Type-only: brings the `ctx.tools` Context merge into this program (viewFor reads presenters). +import type {} from '@deepseek-ai/dsh-tools' import type { ApiProxy, HistoryEntry, HostFrame, MuxFrame, QuestionResponsePayload, SessionSummary, ToolEventView, -} from '@deepseek-ai/dsh-host-apiproxy/api' -import { questionResponsePayloadSchema } from '@deepseek-ai/dsh-host-apiproxy/api/questions.schema' -import type { ClientResponse, RpcError, RpcReceipt, RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' -import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' +} from './api/index.ts' +import { questionResponsePayloadSchema } from './api/questions.schema.ts' +import type { ClientResponse, RpcError, RpcReceipt, RpcRequest, RpcResponse } from './api/rpc.ts' +import { RpcId } from './api/rpc.ts' import type { AskUserQuestionAnswer, AskUserQuestionItem, AskUserQuestionRequest, } from '@deepseek-ai/dsh-user-interaction' @@ -170,7 +172,7 @@ async function summarizeCold(persistence: SessionPersistence, meta: SessionHeade } } -/** Host-level default agent routing (same shape as bootHost's HostDefaults; avoids an impl→index reverse import). */ +/** Host-level default agent routing (same shape as dsh-host-runtime's HostDefaults, kept structural to avoid a reverse dependency). */ export interface ApiProxyDefaults { provider: string model: string @@ -272,8 +274,8 @@ function backscanArgs(events: readonly SessionEvent[], callId: string): { name: class SessionNotFound extends Error {} /** - * Implement ApiProxy over the ctx composed by bootHost. - * @param ctx - the root context returned by bootHost (sessions/agents services mounted). + * Implement ApiProxy over a composed host context. + * @param ctx - a context with the host spine mounted (sessions/agents/tools/userInteraction services). * @param defaults - host-level default provider/model: injected as * agentOptions on create/resume, reported by describe from the same source. * @returns the ApiProxy implementation. diff --git a/packages/host/apiproxy/src/index.ts b/packages/host/apiproxy/src/index.ts index 2999e48b24..aba792bd9c 100644 --- a/packages/host/apiproxy/src/index.ts +++ b/packages/host/apiproxy/src/index.ts @@ -1,13 +1,70 @@ /** - * @deepseek-ai/dsh-host-apiproxy — the front layer every client shape shares: - * the ApiProxy contract (api/: types + zod schemas, browser-safe) and the - * fetch carrier pair (fetch/: toFetchHandler on the host side, AbstractApiClient + - * platform subclasses on the client side). Host assembly (bootHost/createApiProxy/startHost) - * lives in @deepseek-ai/dsh-host-runtime. + * @deepseek-ai/dsh-host-apiproxy — the API gateway every client shape shares: + * the ApiProxy contract (api/: types + zod schemas, browser-safe), the fetch + * carrier pair (fetch/: toFetchHandler on the host side, AbstractApiClient + + * platform subclasses on the client side), and the host-side implementation + * (api-proxy.ts: createApiProxy + the ApiProxyService gateway plugin providing + * `ctx.apiProxy`). Transport-agnostic by design: this package registers no + * routes — carriers (HTTP today, IPC later) wrap `ctx.apiProxy` themselves. */ +import { Context, Service } from 'cordis' +import z from 'schemastery' +import type { ApiProxy } from './api/index.ts' +import { createApiProxy } from './api-proxy.ts' + export type * from './api/index.ts' export { RpcId } from './api/rpc.ts' export { toFetchHandler } from './fetch/handler.ts' export { AbstractApiClient, InProcessApiClient } from './fetch/client.ts' export type { IApiClient } from './fetch/client.ts' +export { createApiProxy } from './api-proxy.ts' +export type { ApiProxyDefaults } from './api-proxy.ts' + +declare module 'cordis' { + interface Context { + /** The host-side ApiProxy implementation (the transport-agnostic gateway face). */ + apiProxy: ApiProxy + } +} + +/** Gateway plugin config: the host-level default agent routing. */ +export interface Config { + /** Default provider route for created/resumed agents. */ + provider: string + /** Default model id. */ + model: string +} + +/** + * The API gateway service: implements the ApiProxy contract over the composed + * host context and provides it as `ctx.apiProxy`. The default project + * directory for new sessions is the host process working directory (not a + * config field this round). + */ +export class ApiProxyService extends Service implements ApiProxy { + static inject = ['agents', 'sessions', 'tools', 'userInteraction'] + + static Config: z<Config> = z.object({ + provider: z.string().required(), + model: z.string().required(), + }) + + readonly sessions: ApiProxy['sessions'] + readonly host: ApiProxy['host'] + readonly events: ApiProxy['events'] + readonly respond: ApiProxy['respond'] + + constructor(ctx: Context, config: Config) { + super(ctx, 'apiProxy') + const api = createApiProxy(ctx, { provider: config.provider, model: config.model, cwd: process.cwd() }) + this.sessions = api.sessions + this.host = api.host + this.events = api.events + // createApiProxy returns closures (no `this` capture); bind only satisfies + // the unbound-method lint without changing behavior. + this.respond = api.respond.bind(api) + } +} + +export default ApiProxyService diff --git a/packages/host/apiproxy/src/invariant.ts b/packages/host/apiproxy/src/invariant.ts index 068cbcaa72..a96b5d081d 100644 --- a/packages/host/apiproxy/src/invariant.ts +++ b/packages/host/apiproxy/src/invariant.ts @@ -15,11 +15,12 @@ export const name = 'host-apiproxy-invariant' export const inject = ['invariants'] /** - * No runtime invariant: this package is the wire contract layer (types, - * schemas, fetch carrier glue) — it emits no cordis events and owns no - * mutable cross-plugin relation. rpcId round-trip and schema acceptance are - * enforced at the carrier boundary and exercised by the protocol-isomorphism - * suite; the live implementation relations belong to dsh-host-runtime. + * No runtime invariant: this package is the wire contract layer plus the + * host-side gateway over services owned elsewhere — it emits no cordis events + * of its own; the session/agent event streams it projects are asserted by + * their owning packages' companions. rpcId round-trip and schema acceptance + * are enforced at the carrier boundary and exercised by the + * protocol-isomorphism suite. */ const install: InvariantInstaller = () => {} diff --git a/packages/host/apiproxy/tsconfig.json b/packages/host/apiproxy/tsconfig.json index 718c5a9042..4e22627590 100644 --- a/packages/host/apiproxy/tsconfig.json +++ b/packages/host/apiproxy/tsconfig.json @@ -8,18 +8,33 @@ "src" ], "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, { "path": "../../util/brand" }, { "path": "../../llm/llm" }, + { + "path": "../../core/agent" + }, { "path": "../../core/session" }, { "path": "../../core/tools" }, + { + "path": "../../session-persistence/session-persistence" + }, + { + "path": "../../session-title/session-title" + }, { "path": "../../ui/user-approval" }, diff --git a/packages/host/runtime/README.md b/packages/host/runtime/README.md index 15cff947df..221f0f46c0 100644 --- a/packages/host/runtime/README.md +++ b/packages/host/runtime/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-host-runtime -Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence, a derived SQLite FTS session-query index, immediate fallback titles, optional first-message model summaries, system prompt, tool and agent registries, agent loop, five workspace-authorized model-facing session-query tools, workspace instructions, local bash, the generic tool-timeout and 50,000-byte spill policies, and the provider-neutral user-interaction service), `createApiProxy` implements the [`dsh-host-apiproxy`](../apiproxy/README.md) contract over that composition, and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }`. +Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence, a derived SQLite FTS session-query index, immediate fallback titles, optional first-message model summaries, system prompt, tool and agent registries, agent loop, five workspace-authorized model-facing session-query tools, workspace instructions, local bash, the generic tool-timeout and 50,000-byte spill policies, and the provider-neutral user-interaction service), and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }` (its `api` comes from [`dsh-host-apiproxy`](../apiproxy/README.md)'s `createApiProxy` over that composition). Which plugins mount and with what defaults is decided only here — shells must not `ctx.plugin` to alter the assembly. `RunningHost.ctx` is a formal seam with exactly two sanctioned uses: mounting protocol front-door plugins (e.g. a future `dsh acp`) and headless session-event subscription; consuming clients must not bypass `api` through it. diff --git a/packages/host/runtime/package.json b/packages/host/runtime/package.json index f6d43afae0..cb31e87fe9 100644 --- a/packages/host/runtime/package.json +++ b/packages/host/runtime/package.json @@ -39,7 +39,6 @@ "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", - "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", "@deepseek-ai/dsh-session-query-sqlite": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", diff --git a/packages/host/runtime/src/index.ts b/packages/host/runtime/src/index.ts index af10f0be16..03780817a9 100644 --- a/packages/host/runtime/src/index.ts +++ b/packages/host/runtime/src/index.ts @@ -1,14 +1,11 @@ /** * @deepseek-ai/dsh-host-runtime — host runtime assembly layer: the core spine - * composition (bootHost), the ApiProxy implementation (createApiProxy), and - * the one-step shell seam (startHost). Host-level configuration (defaults, - * persistenceRoot, future user profile) lives here. + * composition (bootHost) and the one-step shell seam (startHost). The ApiProxy + * implementation lives in @deepseek-ai/dsh-host-apiproxy. Host-level + * configuration (defaults, persistenceRoot, future user profile) lives here. */ export { bootHost } from './boot.ts' export type { BootHostOptions, HostDefaults, HostHandle } from './boot.ts' -export { createApiProxy } from './api-proxy.ts' -export type { ApiProxyDefaults } from './api-proxy.ts' export { startHost } from './start.ts' export type { StartHostOptions, RunningHost } from './start.ts' -export { mountWebPlugins } from './web-plugins.ts' diff --git a/packages/host/runtime/src/start.ts b/packages/host/runtime/src/start.ts index 94e5f22da1..d9009246bb 100644 --- a/packages/host/runtime/src/start.ts +++ b/packages/host/runtime/src/start.ts @@ -2,16 +2,14 @@ * One-step host startup seam: boot core → assemble ApiProxy → assemble the * fetch handler. The returned RunningHost is shell-agnostic — node:http * (dsh web), in-process injection (dsh -p, tests), an IPC bridge (future - * Electron sidecar), and front-door plugin mounting (future dsh acp) all - * consume the same shape. + * Electron sidecar), and automation transports all consume the same shape. */ import type { Context } from 'cordis' import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api' -import { toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy' +import { createApiProxy, toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy' import { bootHost } from './boot.ts' import type { BootHostOptions, HostDefaults } from './boot.ts' -import { createApiProxy } from './api-proxy.ts' /** Options for startHost. */ export interface StartHostOptions { @@ -33,8 +31,7 @@ export interface RunningHost { defaults: HostDefaults /** * Root context — a formal seam, not an escape hatch: (1) the mount point for - * protocol front-door plugins (`dsh acp` = startHost() → ctx.plugin(uiAcp, config)); - * (2) headless session-event subscription. Discipline: consuming clients must + * automation transports; (2) headless session-event subscription. Discipline: consuming clients must * not bypass `api` through ctx; shells must not ctx.plugin to alter the * assembly (mounting a front door is the shell's own shape, not an assembly change). */ diff --git a/packages/host/runtime/src/web-plugins.ts b/packages/host/runtime/src/web-plugins.ts deleted file mode 100644 index 5866d46492..0000000000 --- a/packages/host/runtime/src/web-plugins.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Web client plugin assembly: mounts @cordisjs/plugin-loader with an in-memory - * entry tree over the caller-supplied client plugin roster. The roster is a - * composition decision and lives in the composing app (apps/cli); this module - * only owns the mount/settle/fail-loud mechanics. The web plugin registry - * discovers fetch-arrival entries among the mounted packages by their - * package.json dshClient declarations; node halves are empty applies, so - * mounting them here costs nothing beyond Loader governance. - */ -import { createRequire } from 'node:module' -import type { Context } from 'cordis' -import Loader from '@cordisjs/plugin-loader' - -/** What the shell hands the web plugin registry (loader view + module resolution seam). */ -export interface MountedWebPlugins { - /** Entry enumeration surface of the mounted Loader (registry scan source). */ - loader: { entries(): Iterable<{ options: { name: string }; fiber?: unknown; disabled: boolean }> } - /** Resolve a plugin package's package.json absolute path. */ - resolvePkgJson: (name: string) => string -} - -/** - * Mount the Loader (when absent) and create one in-memory entry per client - * plugin package, then wait for the tree to settle. A plugin whose import - * fails leaves its entry fiber-less — surfaced here as a loud throw listing - * the failures (misconfiguration must not silently drop a client plugin). - * @param ctx - host root context (bootHost product). - * @param plugins - client plugin package names to mount (the composition layer's roster). - * @param anchor - module URL anchoring bare-specifier resolution (the composing - * app's import.meta.url; the roster packages must be dependencies of that app). - * @returns the loader view and package.json resolver the registry consumes. - */ -export async function mountWebPlugins( - ctx: Context, plugins: readonly string[], anchor: string, -): Promise<MountedWebPlugins> { - // The Loader resolves bare specifiers against ctx.baseUrl; without one the - // import silently fails and every entry stays fiber-less. The composing app - // declares the roster packages as dependencies, so its URL is the right anchor. - ctx.baseUrl ??= anchor - if (ctx.get('loader') === undefined) await ctx.plugin(Loader) - const existing = new Set([...ctx.loader.entries()].map(entry => entry.options.name)) - for (const name of plugins) { - if (!existing.has(name)) await ctx.loader.create({ name }) - } - await ctx.loader.await() - const dead = [...ctx.loader.entries()] - .filter(entry => plugins.includes(entry.options.name)) - .filter(entry => entry.fiber === undefined && !entry.disabled) - if (dead.length > 0) { - throw new Error(`web-plugins: client plugin(s) failed to load: ${dead.map(e => e.options.name).join(', ')}`) - } - const require = createRequire(anchor) - return { - loader: ctx.loader, - resolvePkgJson: name => require.resolve(`${name}/package.json`), - } -} diff --git a/packages/host/runtime/tests/api-proxy-cold.spec.ts b/packages/host/runtime/tests/api-proxy-cold.spec.ts index 3d4ba8e15a..a3e2bf4e7a 100644 --- a/packages/host/runtime/tests/api-proxy-cold.spec.ts +++ b/packages/host/runtime/tests/api-proxy-cold.spec.ts @@ -16,7 +16,7 @@ import UserInteractionService from '@deepseek-ai/dsh-user-interaction' import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' -import { createApiProxy } from '../src/api-proxy.ts' +import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy' const sid = (id: string): SessionId => id as SessionId diff --git a/packages/host/runtime/tests/api-proxy-view.spec.ts b/packages/host/runtime/tests/api-proxy-view.spec.ts index a7dcdc73c5..596bf25ac8 100644 --- a/packages/host/runtime/tests/api-proxy-view.spec.ts +++ b/packages/host/runtime/tests/api-proxy-view.spec.ts @@ -21,7 +21,7 @@ import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import UserInteractionService from '@deepseek-ai/dsh-user-interaction' import type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api' import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' -import { createApiProxy } from '../src/api-proxy.ts' +import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy' const reply = (text: string): Promise<ContentBlock[]> => Promise.resolve([{ type: 'text', text }]) diff --git a/packages/host/runtime/tests/web-plugins.spec.ts b/packages/host/runtime/tests/web-plugins.spec.ts deleted file mode 100644 index b558c253c2..0000000000 --- a/packages/host/runtime/tests/web-plugins.spec.ts +++ /dev/null @@ -1,111 +0,0 @@ -/** - * mountWebPlugins unit coverage (keyless). The Loader-facing behavior — - * baseUrl anchoring, entry creation with idempotent reuse, the fiber-less - * fail-loud sweep, and the resolver seam — is exercised against a stubbed - * loader service so it runs without built lib/ artifacts. The roster is - * caller-supplied now (composition moved to apps/cli), so these tests pass - * their own lists. - */ -import { Context } from 'cordis' -import { afterEach, describe, expect, it } from 'vitest' -import { mountWebPlugins } from '../src/web-plugins.ts' - -const ROSTER = [ - '@deepseek-ai/dsh-plugin-a', - '@deepseek-ai/dsh-plugin-b', - '@deepseek-ai/dsh-plugin-c', -] as const - -interface FakeEntry { - options: { name: string } - fiber?: unknown - disabled: boolean -} - -/** Loader stub provided under the real service name (mountWebPlugins skips ctx.plugin(Loader) when present). */ -class FakeLoader { - readonly created: string[] = [] - awaited = 0 - constructor(private readonly entriesList: FakeEntry[], private readonly onCreate?: (name: string) => void) {} - entries(): Iterable<FakeEntry> { - return this.entriesList - } - async create(options: { name: string }): Promise<void> { - this.created.push(options.name) - this.onCreate?.(options.name) - } - async await(): Promise<void> { - this.awaited += 1 - } -} - -let root: Context | undefined - -afterEach(async () => { - await root?.fiber.dispose() - root = undefined -}) - -function withLoader(entriesList: FakeEntry[], onCreate?: (name: string) => void): { ctx: Context; loader: FakeLoader } { - root = new Context() - const loader = new FakeLoader(entriesList, onCreate) - root.reflect.provide('loader', loader) - return { ctx: root, loader } -} - -describe('mountWebPlugins (stubbed loader)', () => { - it('creates one entry per roster package, awaits the tree, and returns the loader view + resolver', async () => { - const entriesList: FakeEntry[] = [] - const { ctx, loader } = withLoader(entriesList, (name) => { - entriesList.push({ options: { name }, fiber: {}, disabled: false }) - }) - const mounted = await mountWebPlugins(ctx, ROSTER, import.meta.url) - expect(loader.created).toEqual([...ROSTER]) - expect(loader.awaited).toBe(1) - expect([...mounted.loader.entries()].map(e => e.options.name)).toEqual([...ROSTER]) - // The resolver resolves a real package manifest through real module resolution, anchored at this test file. - expect(mounted.resolvePkgJson('@deepseek-ai/dsh-host-runtime')).toMatch(/package\.json$/) - expect(ctx.baseUrl).toBeDefined() - }) - - it('reuses existing entries (idempotent mount creates no duplicates)', async () => { - const preexisting: FakeEntry[] = ROSTER.map(name => ({ options: { name }, fiber: {}, disabled: false })) - const { ctx, loader } = withLoader(preexisting) - await mountWebPlugins(ctx, ROSTER, import.meta.url) - expect(loader.created).toEqual([]) - }) - - it('throws listing every fiber-less entry (silent import failure must not drop a client plugin)', async () => { - const entriesList: FakeEntry[] = [] - const { ctx } = withLoader(entriesList, (name) => { - // First one loads; the rest stay fiber-less (import failed silently). - entriesList.push({ options: { name }, fiber: entriesList.length < 1 ? {} : undefined, disabled: false }) - }) - await expect(mountWebPlugins(ctx, ROSTER, import.meta.url)) - .rejects.toThrow(/client plugin\(s\) failed to load: .*dsh-plugin-c/) - }) - - it('skips disabled entries in the fail-loud sweep (disabled is the one valid fiber-less state)', async () => { - const entriesList: FakeEntry[] = ROSTER.map(name => ({ options: { name }, fiber: undefined, disabled: true })) - const { ctx } = withLoader(entriesList) - await expect(mountWebPlugins(ctx, ROSTER, import.meta.url)).resolves.toBeDefined() - }) - - it('mounts the real Loader when none is present (the ctx.plugin(Loader) branch)', async () => { - root = new Context() - // An empty roster keeps this keyless and artifact-free: the branch under - // test is only the Loader auto-mount. - await mountWebPlugins(root, [], import.meta.url) - expect(root.get('loader') !== undefined).toBe(true) - }, 30_000) // cold-cache import of the real vendored Loader crosses the network-disk 5s default - - it('keeps a caller-set baseUrl (anchors only when absent)', async () => { - const entriesList: FakeEntry[] = [] - const { ctx } = withLoader(entriesList, (name) => { - entriesList.push({ options: { name }, fiber: {}, disabled: false }) - }) - ctx.baseUrl = 'file:///caller/anchor/' - await mountWebPlugins(ctx, ROSTER, import.meta.url) - expect(ctx.baseUrl).toBe('file:///caller/anchor/') - }) -}) diff --git a/packages/host/webserver/README.md b/packages/host/webserver/README.md index 9e59699bd6..f00984ea90 100644 --- a/packages/host/webserver/README.md +++ b/packages/host/webserver/README.md @@ -1,16 +1,16 @@ # @deepseek-ai/dsh-host-webserver -Web-shape HTTP carrier: a `node:http` server routing `/api/*` to an injected fetch-shaped handler (node:http ↔ WHATWG bridge with SSE streamed out chunk by chunk) and everything else to static file serving with the step1-locked semantics — traversal outside the dist root is 403, any miss falls back to `index.html` with HTTP 200 (SPA routing), unknown extensions ship as octet-stream, non-GET/HEAD is 405. +Plain HTTP route-registration plugin (default-exported `WebServerService`, config `{host, port, distIndex}`): a `node:http` server that listens on activation and provides `ctx.webServer` — `register(route)` adds a named `exact`/`prefix` route (duplicate `(kind, path)` throws: route patterns are a composition-level contract, so a collision is a misconfiguration; the returned disposer removes the route), `tapIndex(transform)` adds an index.html transform applied in registration order, and `port` reads the listening port (the OS-assigned value when `port` is 0). The match order is fixed — exact over the whole table, then longest prefix, then the static dist fallback with the locked semantics: traversal outside the dist root is 403, any miss falls back to `index.html` with HTTP 200 (SPA routing), unknown extensions ship as octet-stream, non-GET/HEAD is 405. Registration order carries no request-facing semantics. -The package has zero workspace dependencies on purpose: the handler arrives by structural typing (`{ fetch: typeof fetch }`), so `webserver ← runtime` is a runtime injection relationship, never a package dependency. Callers supply both the bind `host` and `port`; port `0` requests an OS-assigned port and the running handle reports the assigned value. `dsh web` defaults to `127.0.0.1` and accepts `--host 0.0.0.0` for deliberate network access. Web (browser) shape only — Electron loads dist over `file://` and carries fetch over an IPC bridge, not this server. This package never prints; the URL line belongs to the shell. +The package knows no harness concepts: the `/api` bridge is the connection plugin's route, plugin bundles and the HMR event stream are the modules/hmr plugins' routes. `host` accepts only `127.0.0.1` (default posture) and `0.0.0.0` (deliberate network exposure); `distIndex` is an assembly fact the composing app resolves and injects, never self-resolved (dist location is workspace knowledge of the app). Web (browser) shape only — Electron loads dist over `file://` and carries fetch over an IPC bridge, not this server. This package never prints; the URL line belongs to the shell. -Client-disconnect detection hangs off the **response** `close` event, not the request: since Node 16, `IncomingMessage` `close` fires as soon as the request body is consumed (immediately for a bodyless GET), which would abort every SSE stream right after open. `RunningWebServer.close()` pairs `close()` with `closeAllConnections()` because SSE connections never end on their own. +A listen failure (EADDRINUSE…) throws out of activation — a FAILED fiber the boot's fail-loud sweep reports. A request whose handling throws (a malformed %-escape hitting `decodeURIComponent`, a client dropping mid-body) is answered 400 — or the socket destroyed when headers are already out — and logged as a warning; it never exits the process. Disposal pairs `close()` with `closeAllConnections()` because held-open responses (SSE) never end on their own. -A request whose handling throws (a malformed %-escape hitting `decodeURIComponent`, a client dropping mid-body) is answered 400 — or the socket destroyed when headers are already out — and reported to `onError`; it never becomes a process-killing unhandled rejection. +In development, the client-plugin registry synchronously captures each built bundle's stat baseline before it returns, then polls those baselines and re-hashes changed content. Each rescan stages its candidate table, graph, and watch map before publishing them, so a baseline failure preserves the prior graph. An immediate rebuild therefore cannot disappear into an asynchronously established watch baseline; a rename window marks the path dirty, retains the last successful baseline, and forces a re-hash when the bundle reappears even with identical metadata. ## Model Experience -None, as the package is a pure HTTP carrier between the browser and the injected API handler; nothing here reaches a model request. +None, as the package is a pure HTTP carrier between the browser and the routes other plugins register; nothing here reaches a model request. #### KV Cache effect @@ -18,6 +18,6 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work -- **No TLS, auth, or origin policy** — callers that bind a non-loopback address expose the server to that network; deployment hardening (or fronting it with a real reverse proxy) is deliberately out of scope for the dev-facing v1. +- **No TLS, auth, or origin policy** — binding a non-loopback address exposes the server to that network; deployment hardening (or fronting it with a real reverse proxy) is deliberately out of scope for the dev-facing v1. - **The starter MIME table is minimal** — extensions beyond the vite-emitted set fall back to `application/octet-stream`; extend the table when an asset class actually ships. -- **Socket options are fixed** — callers select the bind host and port, while backlog and other socket settings remain internal until a deployment needs them. +- **Socket options are fixed** — config selects the bind host and port, while backlog and other socket settings remain internal until a deployment needs them. diff --git a/packages/host/webserver/package.json b/packages/host/webserver/package.json index 01d8a22e9d..0dab038f41 100644 --- a/packages/host/webserver/package.json +++ b/packages/host/webserver/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-host-webserver", - "description": "Web-shape HTTP carrier: static file serving plus the /api/* bridge to an injected fetch-shaped handler (SSE streamed through)", + "description": "Plain HTTP route-registration plugin: named-route registry (webServer service) + index transform taps + static dist fallback; knows no harness concepts", "version": "0.0.1", "private": true, "type": "module", @@ -30,6 +30,9 @@ "cordis": "^4.0.0-rc.7", "@deepseek-ai/dsh-invariants": "^0.0.1" }, + "dependencies": { + "schemastery": "^3.18.0" + }, "devDependencies": { "cordis": "^4.0.0-rc.7", "@deepseek-ai/dsh-invariants": "workspace:^" diff --git a/packages/host/webserver/src/index.ts b/packages/host/webserver/src/index.ts index 60ad92d18c..936dd4f5a1 100644 --- a/packages/host/webserver/src/index.ts +++ b/packages/host/webserver/src/index.ts @@ -1,232 +1,184 @@ /** - * @deepseek-ai/dsh-host-webserver — the web-shape HTTP carrier: node:http server - * routing /api/* to an injected fetch-shaped handler (node:http ↔ WHATWG - * bridge with SSE streamed out chunk by chunk) and everything else to static - * file serving. Web (browser) shape only — Electron loads dist over file:// - * and carries fetch over an IPC bridge, not this server. This package never - * prints: the URL line belongs to the shell. + * @deepseek-ai/dsh-host-webserver — plain HTTP route-registration plugin: a + * node:http server plus the `httpServer` service (named-route registry + index + * transform taps + static dist fallback). Knows no harness concepts — every + * feature surface (API bridge, plugin bundles, SSE) is a route some other + * plugin registers. Web (browser) shape only — Electron loads dist over + * file:// and carries fetch over an IPC bridge, not this server. This package + * never prints: the URL line belongs to the shell. */ import { createServer } from 'node:http' -import type { IncomingMessage, ServerResponse } from 'node:http' +import type { IncomingMessage, ServerResponse, Server } from 'node:http' import { readFile } from 'node:fs/promises' import type { AddressInfo } from 'node:net' import { dirname } from 'node:path' +import { Context, Service } from 'cordis' +import z from 'schemastery' import { serveStatic } from './static.ts' -import { createPluginEventChannel } from './plugin-events.ts' -import type { HostWebPluginRegistry, WebBootGraph } from './web-plugins.ts' -export { createHostWebPluginRegistry } from './web-plugins.ts' -export type { - HostWebPluginRegistry, LoaderEntryView, LoaderView, WebBootEntry, WebBootGraph, WebPluginRegistryDeps, -} from './web-plugins.ts' -export type { PluginEventChannel, PluginEventFrame } from './plugin-events.ts' - -/** Options for startWebServer. */ -export interface WebServerOptions { - /** Address or hostname to listen on. */ - host: string - /** Port to listen on; zero requests an OS-assigned port. */ - port: number - /** - * Absolute path of index.html inside the static root — the caller resolves - * it (dist location is workspace knowledge of the shell, not this package's). - */ - distIndex: string - /** Fetch-shaped API carrier; /api/*-prefixed requests are bridged to it. */ - apiHandler: { fetch: typeof fetch } - /** - * Web plugin table. When present, every index.html response carries the - * `window.__DSH_BOOT__` entry graph script, `/plugins/<id>/client.js` serves - * each fetch entry's client bundle, and `GET /plugins/events` streams graph/ - * rebuilt frames (SSE) — rebuilt frames ride the registry's own bundle-watch - * notifications (`onRebuilt`). Absent = all three surfaces off (carrier-only - * use). - */ - webPlugins?: Pick<HostWebPluginRegistry, 'graph' | 'clientPath' | 'onRebuilt'> +declare module 'cordis' { + interface Context { + httpServer: HttpServerService + } } -/** Listening web server handle. */ -export interface RunningWebServer { - /** The listening port, including the OS-assigned value when options.port is zero. */ +/** Route match kind: 'exact' matches the pathname verbatim; 'prefix' p matches p and p/<anything>. */ +export type WebRouteKind = 'exact' | 'prefix' + +/** One named route registration. */ +export interface WebRoute { + kind: WebRouteKind + /** Absolute pathname, no trailing slash. */ + path: string + /** Owns the full response lifecycle (may hold the response open, e.g. SSE). */ + handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void> +} + +/** Gateway config: listen address plus the static dist anchor (injected by the composing app, never self-resolved). */ +export interface Config { + /** Listen host; the two supported values are loopback and all-interfaces. */ + host: '127.0.0.1' | '0.0.0.0' + /** Listen port; zero requests an OS-assigned port. */ port: number - /** - * Shutdown: close + closeAllConnections (SSE connections never end on their - * own; without the force-close, close() would hang). Idempotent. - */ - close(): Promise<void> + /** Absolute path of index.html inside the static root (dist location is workspace knowledge of the app). */ + distIndex: string } /** - * Start the web-shape HTTP server on the caller-selected host and port. - * Routing: /api/* → apiHandler bridge; non-GET/HEAD → 405; everything else → - * static with the step1-locked semantics (403 traversal, SPA fallback 200). - * A listen failure (EADDRINUSE…) rejects — the shell decides how to exit; a - * server error after listen goes to onError. A request whose handling throws - * (malformed %-escapes, a client dropping mid-body) is answered 400 — or the - * socket destroyed when headers are already out — and reported to onError; - * it never becomes an unhandled rejection. - * @param options - port, static root anchor, and the API carrier. - * @param onError - sink for post-listen server errors and per-request handling failures. - * @returns the running server handle once listening. + * The web-shape HTTP carrier service. Activation listens immediately (route + * registration order carries no request-facing semantics: named routes are + * composed to be disjoint, and the static dist fallback answers anything not + * yet claimed during the boot window). A listen failure throws out of init — + * a FAILED fiber the boot's fail-loud sweep reports. */ -export function startWebServer(options: WebServerOptions, onError: (err: Error) => void): Promise<RunningWebServer> { - const { host, port, distIndex, apiHandler, webPlugins } = options - const distRoot = dirname(distIndex) - const renderIndex = webPlugins === undefined ? undefined : async (): Promise<string> => { - const html = await readFile(distIndex, 'utf8') - return injectBootManifest(html, webPlugins.graph()) - } - const pluginEvents = webPlugins === undefined ? undefined : createPluginEventChannel() - // Rebuilt frames come from the registry's own bundle watch (dev mode); a - // prod registry without watching simply never notifies. - const unsubscribeRebuilt = webPlugins !== undefined && pluginEvents !== undefined - ? webPlugins.onRebuilt((id, rev) => { pluginEvents.broadcast({ type: 'rebuilt', id, rev }) }) - : undefined +export class HttpServerService extends Service { + static Config: z<Config> = z.object({ + host: z.union([z.const('127.0.0.1'), z.const('0.0.0.0')]).required(), + port: z.natural().max(65535).required(), + distIndex: z.string().required(), + }) - const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => { - /* v8 ignore next -- `?? '/'` arm: node:http always sets url on server - requests; the field is only optional on the client-side IncomingMessage type */ - const rawPath = new URL(req.url ?? '/', 'http://x').pathname - if (rawPath.startsWith('/api/')) { - await bridge(req, res, apiHandler) - return - } - if (req.method !== 'GET' && req.method !== 'HEAD') { - res.writeHead(405) - res.end() - return - } - if (webPlugins !== undefined && pluginEvents !== undefined && rawPath === '/plugins/events') { - pluginEvents.connect(res, webPlugins.graph()) - return - } - if (webPlugins !== undefined && rawPath.startsWith('/plugins/') && rawPath.endsWith('/client.js')) { - await servePluginBundle(decodeURIComponent(rawPath), res, webPlugins) - return - } - await serveStatic(decodeURIComponent(rawPath), res, distRoot, distIndex, renderIndex) + private readonly exact = new Map<string, WebRoute>() + private readonly prefixes = new Map<string, WebRoute>() + private readonly indexTaps: ((html: string) => string)[] = [] + private readonly distRoot: string + private readonly distIndex: string + private server!: Server + private listenedPort!: number + + constructor(ctx: Context, private config: Config) { + super(ctx, 'httpServer') + this.distIndex = config.distIndex + this.distRoot = dirname(config.distIndex) } - // Last-resort guard: handle() rejecting would otherwise be an unhandled - // rejection, and one malformed request (a bad %-escape hitting - // decodeURIComponent, a client dropping mid-body) would kill the whole - // process. Nothing after this catch can throw again on the same response. - const server = createServer((req, res) => { - handle(req, res).catch((err: unknown) => { - onError(err instanceof Error ? err : new Error(String(err))) - if (res.headersSent) { - res.destroy() + + /** The listening port (the OS-assigned value when config.port is 0). */ + get port(): number { + return this.listenedPort + } + + /** + * Register a named route. Duplicate (kind, path) throws — route patterns are + * a composition-level contract, so a collision is a misconfiguration. + * @param route - kind, path, and the owning handler. + * @returns the disposer removing the route. + */ + register(route: WebRoute): () => void { + const table = route.kind === 'exact' ? this.exact : this.prefixes + if (table.has(route.path)) { + throw new Error(`webserver: duplicate ${route.kind} route "${route.path}"`) + } + table.set(route.path, route) + return () => { table.delete(route.path) } + } + + /** + * Register an index.html transform, applied to every index response in + * registration order. + * @param transform - pure html-to-html function. + * @returns the disposer removing the transform. + */ + tapIndex(transform: (html: string) => string): () => void { + this.indexTaps.push(transform) + return () => { + const at = this.indexTaps.indexOf(transform) + if (at !== -1) this.indexTaps.splice(at, 1) + } + } + + /** Listen; resolves once the socket is bound (rejection = FAILED fiber). */ + async [Service.init](): Promise<void> { + const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => { + /* v8 ignore next -- `?? '/'` arm: node:http always sets url on server + requests; the field is only optional on the client-side IncomingMessage type */ + const rawPath = new URL(req.url ?? '/', 'http://x').pathname + const route = this.match(rawPath) + if (route !== undefined) { + await route.handler(req, res) return } - res.writeHead(400) - res.end() - }) - }) - - let closing: Promise<void> | undefined - const close = (): Promise<void> => (closing ??= new Promise((resolveClose) => { - unsubscribeRebuilt?.() - server.close(() => { resolveClose() }) - server.closeAllConnections() - })) - - return new Promise((resolveListen, rejectListen) => { - server.once('error', rejectListen) - server.listen(port, host, () => { - server.off('error', rejectListen) - server.on('error', onError) - resolveListen({ port: (server.address() as AddressInfo).port, close }) - }) - }) -} - -/** - * Inject the boot entry graph into index.html: `window.__DSH_BOOT__` as the - * first script in <head> (before the shell bundle reads it). `<` is escaped in - * the JSON so plugin-controlled strings cannot break out of the script element. - * @param html - the index.html source. - * @param graph - the composed entry graph from the registry. - * @returns the html with the graph script injected. - */ -export function injectBootManifest(html: string, graph: WebBootGraph): string { - const json = JSON.stringify(graph).replaceAll('<', '\\u003c') - const script = `<script>window.__DSH_BOOT__ = ${json}</script>` - const head = html.indexOf('<head>') - if (head !== -1) return `${html.slice(0, head + 6)}${script}${html.slice(head + 6)}` - // Headless fixture pages may lack <head>; prepending keeps the read-before-shell ordering. - return `${script}${html}` -} - -/** - * Serve one plugin client bundle from the registry table (unknown id = 404; - * the id may contain a scope slash). The `?rev=` query is a cache-busting - * parameter only — serving ignores it; `no-cache` makes the browser revalidate - * so a stale rev never sticks. - */ -async function servePluginBundle( - pathname: string, res: ServerResponse, webPlugins: Pick<HostWebPluginRegistry, 'clientPath'>, -): Promise<void> { - const id = pathname.slice('/plugins/'.length, -'/client.js'.length) - const path = webPlugins.clientPath(id) - if (path === undefined) { - res.writeHead(404) - res.end() - return - } - try { - const body = await readFile(path) - res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-cache' }) - res.end(body) - } catch { - // Registered but unreadable (bundle not built yet): loud 404 beats a silent SPA-fallback HTML page. - res.writeHead(404) - res.end() - } -} - -/** Bridge one node:http request to the WHATWG fetch handler (client close aborts; SSE bodies stream out chunk by chunk). */ -async function bridge(req: IncomingMessage, res: ServerResponse, apiHandler: { fetch: typeof fetch }): Promise<void> { - const abort = new AbortController() - // Client-disconnect detection MUST hang off the response, not the request: - // since Node 16, IncomingMessage 'close' fires as soon as the request body is - // fully consumed (immediately for a bodyless GET), which would abort every SSE - // stream right after open. ServerResponse 'close' fires on connection teardown; - // writableEnded distinguishes a normal end() from the client going away. - res.on('close', () => { - if (!res.writableEnded) abort.abort() - }) - const chunks: Buffer[] = [] - for await (const chunk of req) chunks.push(chunk as Buffer) - /* v8 ignore next 3 -- `??` arms: node:http always sets url/method on server - requests; the fields are only optional on the client-side IncomingMessage type */ - const request = new Request(new URL(req.url ?? '/', 'http://dsh.internal'), { - method: req.method ?? 'GET', - headers: Object.fromEntries(Object.entries(req.headers).filter(([, v]) => typeof v === 'string') as [string, string][]), - ...chunks.length > 0 ? { body: Buffer.concat(chunks) } : {}, - signal: abort.signal, - }) - const response = await apiHandler.fetch(request) - res.writeHead(response.status, Object.fromEntries(response.headers.entries())) - if (response.body === null) { - res.end() - return - } - for await (const chunk of response.body) { - // Backpressure: a false return means the socket buffer is full — wait for drain - // instead of buffering unboundedly (slow/suspended SSE consumers). 'close' also - // resolves so a mid-wait disconnect can't park this loop forever; the close - // handler above aborts the handler stream, which then ends the iteration. - if (!res.write(chunk)) { - await new Promise<void>((resolve) => { - const done = (): void => { - res.off('drain', done) - res.off('close', done) - resolve() - } - res.once('drain', done) - res.once('close', done) - }) + // Static fallback keeps the pre-plugin semantics: non-GET/HEAD is 405, + // traversal 403, miss falls back to index.html 200 (SPA routing). + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405) + res.end() + return + } + await serveStatic(decodeURIComponent(rawPath), res, this.distRoot, this.distIndex, () => this.renderIndex()) } + // Last-resort guard: handle() rejecting would otherwise be an unhandled + // rejection killing the process on one malformed request (bad %-escape, + // client dropping mid-body). Per-request failures log and answer 400 — + // never a process exit. + this.server = createServer((req, res) => { + handle(req, res).catch((err: unknown) => { + this.ctx.logger.warn(err instanceof Error ? err : new Error(String(err))) + if (res.headersSent) { + res.destroy() + return + } + res.writeHead(400) + res.end() + }) + }) + + await new Promise<void>((resolve, reject) => { + this.server.once('error', reject) + this.server.listen(this.config.port, this.config.host, () => { + this.server.off('error', reject) + this.server.on('error', (err) => { this.ctx.logger.error(err) }) + this.listenedPort = (this.server.address() as AddressInfo).port + resolve() + }) + }) + + // close + closeAllConnections: held-open responses (SSE) never end on + // their own; without the force-close, close() would hang teardown. + this.ctx.effect(() => () => new Promise<void>((resolve) => { + this.server.close(() => { resolve() }) + this.server.closeAllConnections() + }), 'httpServer.listen') + } + + /** Longest-prefix-wins over the prefix table after an exact-table miss. */ + private match(pathname: string): WebRoute | undefined { + const exact = this.exact.get(pathname) + if (exact !== undefined) return exact + let best: WebRoute | undefined + for (const [prefix, route] of this.prefixes) { + if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) continue + if (best === undefined || prefix.length > best.path.length) best = route + } + return best + } + + /** Index body: dist index.html through the registered taps in order. */ + private async renderIndex(): Promise<string> { + let html = await readFile(this.distIndex, 'utf8') + for (const transform of this.indexTaps) html = transform(html) + return html } - res.end() } + +export default HttpServerService diff --git a/packages/host/webserver/src/invariant.ts b/packages/host/webserver/src/invariant.ts index a204c93775..b5c8492566 100644 --- a/packages/host/webserver/src/invariant.ts +++ b/packages/host/webserver/src/invariant.ts @@ -15,28 +15,30 @@ export const name = 'host-webserver-invariant' export const inject = ['invariants'] /** - * Owned relation: the web plugin registry's boot entry graph must stay - * self-consistent — every row must resolve a clientPath under the same id - * (the /plugins/<id>/client.js URL it advertises would otherwise 404 on a - * browser that just received the graph). Checked synchronously on every - * rescan trigger (cordis 'internal/plugin'): graph() and clientPath() read - * the same table object, so the relation is self-consistent at any instant — - * no need to wait out the registry's own debounced rescan. The registry - * arrives through the context key the assembly publishes it under. + * Owned relation: route registrations and their disposers must stay + * symmetric — after the owning fiber of a registered route unloads, the + * route table must no longer answer for its path (a stale route would keep + * serving a disposed plugin's handler). Checked on every fiber teardown + * (cordis 'internal/plugin'): the service's own registry state is compared + * against the set of live fibers' registrations indirectly, by probing that + * dispose really removed the entry — the register() disposer contract. */ const install: InvariantInstaller = (ctx, fail) => { ctx.on('internal/plugin', () => { - const registry = ctx.get('webPlugins') as - | { - graph(): { entries: { id: string; url: string }[] } - clientPath(id: string): string | undefined - } + const server = ctx.get('httpServer') as + | { register(route: { kind: 'exact'; path: string; handler: () => void }): () => void } | undefined - if (registry === undefined) return // carrier-only deployments never publish the registry - for (const row of registry.graph().entries) { - if (registry.clientPath(row.id) === undefined) { - fail(`web plugin graph row "${row.id}" advertises ${row.url} but resolves no client bundle path — the served __DSH_BOOT__ would 404 on fetch`) - } + if (server === undefined) return // no webserver row in this composition + // Register/dispose probe on a reserved path: if dispose leaves the route + // behind, a second register throws the duplicate error — the asymmetry. + // Each register(probe)() is one register+dispose cycle, so the probe never + // leaves residue; a leftover from the first cycle makes the second throw. + const probe = { kind: 'exact' as const, path: '/__dsh_invariant_probe__', handler: () => {} } + try { + server.register(probe)() + server.register(probe)() + } catch { + fail('httpServer.register() disposer left the route registered — route table and fiber lifecycles diverged') } }, { global: true }) } diff --git a/packages/host/webserver/src/plugin-events.ts b/packages/host/webserver/src/plugin-events.ts deleted file mode 100644 index b438edf948..0000000000 --- a/packages/host/webserver/src/plugin-events.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** - * `/plugins/events` SSE channel: the system-side push surface for the client - * entry graph (connect → current graph frame; dev rebuild → rebuilt frame). - * Presentation-only wire — frames never enter the session log (distinct from - * the /api/* session SSE, which is api-contract territory). Connections are - * plain node:http responses held in a set; the server's closeAllConnections - * tears them down on shutdown. - */ - -import type { ServerResponse } from 'node:http' -import type { WebBootGraph } from './web-plugins.ts' - -/** One `/plugins/events` frame: the full graph on connect, or one rebuilt bundle notice. */ -export type PluginEventFrame = - | { type: 'graph'; graph: WebBootGraph } - | { type: 'rebuilt'; id: string; rev: string } - -/** Broadcast surface owned by the webserver routing layer. */ -export interface PluginEventChannel { - /** Adopt one incoming SSE request: writes the SSE preamble and the current-graph frame, then keeps the response open. */ - connect(res: ServerResponse, graph: WebBootGraph): void - /** Push one frame to every open connection. */ - broadcast(frame: PluginEventFrame): void -} - -/** Serialize one frame as an SSE data line. */ -function sseData(frame: PluginEventFrame): string { - return `data: ${JSON.stringify(frame)}\n\n` -} - -/** - * Create the channel (one per running server). - * @returns the connect/broadcast surface. - */ -export function createPluginEventChannel(): PluginEventChannel { - const connections = new Set<ServerResponse>() - return { - connect(res, graph) { - res.writeHead(200, { - 'content-type': 'text/event-stream', - 'cache-control': 'no-cache', - 'connection': 'keep-alive', - }) - // Comment line on open so clients/proxies see a live channel even when - // no rebuild ever happens; EventSource frame parsing skips it naturally. - res.write(': connected\n\n') - res.write(sseData({ type: 'graph', graph })) - connections.add(res) - res.on('close', () => { connections.delete(res) }) - }, - broadcast(frame) { - const line = sseData(frame) - for (const res of connections) res.write(line) - }, - } -} diff --git a/packages/host/webserver/src/web-plugins.ts b/packages/host/webserver/src/web-plugins.ts deleted file mode 100644 index 9e32cfc012..0000000000 --- a/packages/host/webserver/src/web-plugins.ts +++ /dev/null @@ -1,321 +0,0 @@ -/** - * HostWebPluginRegistry: composes the client entry graph served as - * `window.__DSH_BOOT__` ({rev, entries}). Every row is discovered among the - * host Loader's loaded entries by its package.json `dshClient` declaration - * (all client plugin packages arrive by fetch — one uniform bundle shape), - * resolving each one's client bundle path from `exports["./client"]` and - * hashing the bundle content into a `rev` (cache busting + HMR diff anchor). - * `inject` edges and the `immediately` prefetch mark come from the manifest - * (dshClient — the package owns its dependency edges and its boot tier); the - * composition layer contributes only the roster. The webserver consumes the - * table to emit the boot graph and to serve `GET /plugins/<id>/client.js`; - * in dev mode the registry additionally stat-polls each scanned bundle file - * and re-hashes + notifies `onRebuilt` subscribers on change (the rebuild - * signal is the registry's own observation — no builder protocol exists). - * - * The vendored loader emits no "entry loaded" event (only `loader/entry-init`, - * which fires at Entry construction before import/apply), so the registry - * scans `loader.entries()` and rescans on cordis `internal/plugin` (fiber - * create/dispose), microtask-debounced. Plugin-set changes take effect on - * restart per the config-source ruling; the subscription only keeps the table - * fresh within a process lifetime. - */ - -import { createHash } from 'node:crypto' -import { readFileSync, unwatchFile, watchFile } from 'node:fs' -import type { Stats } from 'node:fs' -import { dirname, join } from 'node:path' -import type { Context } from 'cordis' - -/** One composed client entry (`window.__DSH_BOOT__.entries` row). */ -export interface WebBootEntry { - /** Entry name == package name. */ - id: string - /** Bundle URL served by this webserver (`/plugins/<id>/client.js?rev=<rev>`). */ - url: string - /** Bundle content hash (sha1, shortened). */ - rev: string - /** Package-name dependency edges from the manifest (dshClient.inject), informational (preflight/HMR display). */ - inject?: string[] - /** Boot phase-one prefetch tier: the shell fetches these bundles in parallel before creating entries. */ - immediately?: boolean -} - -/** The composed entry graph: injected into index.html and pushed on /plugins/events connect. */ -export interface WebBootGraph { - /** Consistency anchor over all rows: changes whenever any entry row changes. */ - rev: string - /** All composed entries (order carries no semantics; governance ordering is the client Loader's job). */ - entries: WebBootEntry[] -} - -/** The web plugin table consumed by the boot injection, the bundle endpoint, and the rebuild channel. */ -export interface HostWebPluginRegistry { - /** Current composed entry graph (stable object between changes). */ - graph(): WebBootGraph - /** - * Absolute path of an entry's client bundle. - * @param id - entry id (package name). - * @returns the path, or undefined for an unknown id. - */ - clientPath(id: string): string | undefined - /** - * Re-hash one entry's bundle: updates the row's rev/url and the graph rev. - * The dev bundle watch calls this on every observed file change. - * @param id - entry id (package name). - * @returns the new bundle rev, or undefined for an unknown id. - */ - rebuilt(id: string): string | undefined - /** - * Subscribe to bundle rebuilds observed by the dev watch (only fires when - * the re-hash produced a different rev — an unchanged bundle is silent). - * @param listener - receives the entry id and its new bundle rev. - * @returns the unsubscriber. - */ - onRebuilt(listener: (id: string, rev: string) => void): () => void - /** Remove the loader subscription, all bundle watches, and all rebuild listeners. */ - dispose(): void -} - -/** Structural view of a loader entry (webserver keeps zero workspace dependencies; cordis stays a type-only peer). */ -export interface LoaderEntryView { - options: { name: string } - /** Present once the entry's plugin fiber exists (import succeeded and apply ran/started). */ - fiber?: unknown - /** True when the entry or an owning group is disabled. */ - disabled: boolean -} - -/** Structural view of the host Loader (entry enumeration is all the registry needs). */ -export interface LoaderView { - entries(): Iterable<LoaderEntryView> -} - -/** Dependencies injected by the assembly layer. */ -export interface WebPluginRegistryDeps { - /** Host root context; used only to subscribe `internal/plugin` for rescans. */ - ctx: Context - /** The host Loader owning the plugin entries. */ - loader: LoaderView - /** - * Resolve a package specifier to its package.json absolute path (assembly - * passes `createRequire(...).resolve(`${name}/package.json`)`); injected so - * the registry makes no module-resolution assumptions of its own. - */ - resolvePkgJson: (name: string) => string - /** Sink for rescan failures (the initial scan throws instead — misconfiguration fails loud at load). */ - onError: (err: Error) => void - /** - * Dev-mode bundle watching: stat-poll every scanned row's client bundle - * (fs.watchFile — polling by design: network mounts deliver no inotify - * events) and re-hash + notify onRebuilt subscribers on change. Absent = - * no watching (prod composition). - */ - watch?: { - /** Stat-poll interval in milliseconds; default 500 (the build-side watcher's polling default). */ - intervalMs?: number - } -} - -/** package.json `dshClient` declaration shape (file boundary — validated field by field). */ -interface DshClientDeclaration { - inject?: string[] - platform: string - /** Boot phase-one prefetch mark; absent means lazy (fetched on demand). */ - immediately?: boolean -} - -interface WebPluginRecord { - entry: WebBootEntry - clientPath: string -} - -/** Narrow an unknown parsed JSON value to the dshClient declaration, throwing on malformed fields. */ -function parseDshClient(name: string, value: unknown): DshClientDeclaration | undefined { - if (value === undefined) return undefined - if (typeof value !== 'object' || value === null) { - throw new Error(`web-plugins: ${name} has a non-object dshClient declaration`) - } - const decl = value as Record<string, unknown> - if (typeof decl.platform !== 'string') { - throw new Error(`web-plugins: ${name} dshClient.platform must be a string`) - } - if (decl.inject !== undefined && (!Array.isArray(decl.inject) || decl.inject.some(i => typeof i !== 'string'))) { - throw new Error(`web-plugins: ${name} dshClient.inject must be a string array`) - } - if (decl.immediately !== undefined && typeof decl.immediately !== 'boolean') { - throw new Error(`web-plugins: ${name} dshClient.immediately must be a boolean`) - } - return { - platform: decl.platform, - ...(decl.inject !== undefined ? { inject: decl.inject as string[] } : {}), - ...(decl.immediately !== undefined ? { immediately: decl.immediately } : {}), - } -} - -/** Resolve `exports["./client"]` to a relative path, accepting the string and one-level conditional forms. */ -function clientExportOf(name: string, exportsField: unknown): string | undefined { - if (typeof exportsField !== 'object' || exportsField === null) return undefined - const client = (exportsField as Record<string, unknown>)['./client'] - if (client === undefined) return undefined - if (typeof client === 'string') return client - if (typeof client === 'object' && client !== null) { - const fallback = (client as Record<string, unknown>).default - if (typeof fallback === 'string') return fallback - } - throw new Error(`web-plugins: ${name} exports["./client"] has an unsupported shape`) -} - -/** sha1 content hash shortened to 12 hex chars (bundle rev / graph rev). */ -function shortHash(input: string | Buffer): string { - return createHash('sha1').update(input).digest('hex').slice(0, 12) -} - -/** Graph row for one bundle rev (url carries the rev as its cache-busting query). */ -function graphRow(id: string, rev: string, inject: string[] | undefined, immediately: boolean): WebBootEntry { - return { - id, - url: `/plugins/${id}/client.js?rev=${rev}`, - rev, - ...(inject !== undefined ? { inject } : {}), - ...(immediately ? { immediately: true } : {}), - } -} - -/** Compose the graph value from the current table. */ -function composeGraph(table: Map<string, WebPluginRecord>): WebBootGraph { - const entries = [...table.values()].map(record => record.entry) - return { rev: shortHash(JSON.stringify(entries)), entries } -} - -/** - * Build the web plugin registry: scan once synchronously (a malformed - * declaration, an unbuilt bundle, or an invalid watch interval throws here — - * load-time fail loud), then rescan on `internal/plugin`, microtask-debounced - * (failures go to `deps.onError`). With `deps.watch`, every scanned bundle - * file is stat-polled and a content change re-hashes the row and notifies - * `onRebuilt` subscribers. - * @param deps - loader view, resolution hook, error sink, and optional dev watch (see {@link WebPluginRegistryDeps}). - * @returns the registry handle. - */ -export function createHostWebPluginRegistry(deps: WebPluginRegistryDeps): HostWebPluginRegistry { - const watchInterval = deps.watch === undefined ? undefined : deps.watch.intervalMs ?? 500 - if (watchInterval !== undefined && (!Number.isInteger(watchInterval) || watchInterval <= 0)) { - throw new Error(`web-plugins: watch.intervalMs must be a positive integer (got ${String(deps.watch?.intervalMs)})`) - } - - let table = scan(deps) - let graph = composeGraph(table) - const rebuildListeners = new Set<(id: string, rev: string) => void>() - - const rebuilt = (id: string): string | undefined => { - const record = table.get(id) - if (record === undefined) return undefined - const rev = shortHash(readFileSync(record.clientPath)) - record.entry = graphRow(id, rev, record.entry.inject, record.entry.immediately === true) - graph = composeGraph(table) - return rev - } - - // Dev bundle watch: one fs.watchFile stat poll per table row. A torn read - // of a half-written bundle self-heals — the ongoing write keeps changing - // the stats, so the next poll tick re-hashes the completed file. - const watched = new Map<string, { path: string; listener: (curr: Stats, prev: Stats) => void }>() - const syncWatches = (): void => { - if (watchInterval === undefined) return - for (const [id, watch] of watched) { - if (table.get(id)?.clientPath === watch.path) continue - unwatchFile(watch.path, watch.listener) - watched.delete(id) - } - for (const [id, record] of table) { - if (watched.has(id)) continue - const listener = (curr: Stats, prev: Stats): void => { - // fs.watchFile fires on any stat delta (atime included); only content - // signals count. An all-zero curr means the file vanished mid-rebuild - // — the completing write fires the next tick, so skipping is safe. - if (curr.mtimeMs === prev.mtimeMs && curr.size === prev.size) return - if (curr.mtimeMs === 0) return - const before = table.get(id)?.entry.rev - let rev: string | undefined - try { - rev = rebuilt(id) - } catch (error) { - const code = (error as NodeJS.ErrnoException).code - if (code === 'ENOENT') return // mid-rename window; the completed write fires the next poll tick - deps.onError(error instanceof Error ? error : new Error(String(error))) - return - } - if (rev === undefined || rev === before) return - for (const notify of rebuildListeners) { - // A throwing subscriber must not escape the fs.watchFile callback - // (that would skip later subscribers and can kill the process). - try { - notify(id, rev) - } catch (error) { - deps.onError(error instanceof Error ? error : new Error(String(error))) - } - } - } - watchFile(record.clientPath, { interval: watchInterval, persistent: false }, listener) - watched.set(id, { path: record.clientPath, listener }) - } - } - syncWatches() - - let pending = false - const unsubscribe = deps.ctx.on('internal/plugin', () => { - if (pending) return - pending = true - queueMicrotask(() => { - pending = false - try { - table = scan(deps) - graph = composeGraph(table) - syncWatches() - } catch (error) { - // Keep serving the previous graph: a mid-flight rescan failure must not - // take down the boot manifest for plugins that were fine. - deps.onError(error instanceof Error ? error : new Error(String(error))) - } - }) - }) - - return { - graph: () => graph, - clientPath: id => table.get(id)?.clientPath, - rebuilt, - onRebuilt: (listener) => { - rebuildListeners.add(listener) - return () => { rebuildListeners.delete(listener) } - }, - dispose: () => { - unsubscribe() - for (const { path, listener } of watched.values()) unwatchFile(path, listener) - watched.clear() - rebuildListeners.clear() - }, - } -} - -/** One full table build from the loader's current entries (bundle content is hashed here — an unreadable bundle throws). */ -function scan(deps: WebPluginRegistryDeps): Map<string, WebPluginRecord> { - const table = new Map<string, WebPluginRecord>() - for (const entry of deps.loader.entries()) { - if (entry.fiber === undefined || entry.disabled) continue - const name = entry.options.name - if (table.has(name)) continue - const pkgPath = deps.resolvePkgJson(name) - const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as Record<string, unknown> - const decl = parseDshClient(name, pkg.dshClient) - if (decl === undefined || decl.platform !== 'web') continue - const clientRel = clientExportOf(name, pkg.exports) - if (clientRel === undefined) { - throw new Error(`web-plugins: ${name} declares dshClient but exports no "./client" bundle`) - } - const clientPath = join(dirname(pkgPath), clientRel) - const rev = shortHash(readFileSync(clientPath)) - table.set(name, { entry: graphRow(name, rev, decl.inject, decl.immediately === true), clientPath }) - } - return table -} diff --git a/packages/host/webserver/tests/invariant.spec.ts b/packages/host/webserver/tests/invariant.spec.ts deleted file mode 100644 index f9d5ba4490..0000000000 --- a/packages/host/webserver/tests/invariant.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Webserver invariant companion: the boot-graph consistency audit — every - * fetch-arrival graph row must resolve a clientPath, checked on fiber - * lifecycle events against the assembly-published 'webPlugins' context key. - */ -import { Context } from 'cordis' -import { describe, expect, it } from 'vitest' -import InvariantService from '@deepseek-ai/dsh-invariants' -import * as WebserverInvariant from '../src/invariant.ts' - -interface RegistryStub { - graph(): { entries: { id: string; url: string }[] } - clientPath(id: string): string | undefined -} - -async function setup(registry?: RegistryStub): Promise<Context> { - const ctx = new Context() - await ctx.plugin(InvariantService, { enabled: true }) - await ctx.plugin(WebserverInvariant).await() - if (registry !== undefined) ctx.reflect.provide('webPlugins', registry) - return ctx -} - -/** Fire the audit trigger directly (same technique as the scope invariant - * spec): a synchronous emit propagates the fail() throw to the caller. */ -function trigger(ctx: Context): void { - ;(ctx.emit as (event: string, ...args: unknown[]) => void)('internal/plugin', ctx.fiber) -} - -describe('webserver manifest invariant', () => { - it('stays silent without a registry (carrier-only deployment) and with a consistent table', async () => { - const bare = await setup() - expect(() => { trigger(bare) }).not.toThrow() // no 'webPlugins' key published - - const consistent = await setup({ - graph: () => ({ entries: [{ id: 'p1', url: '/plugins/p1/client.js?rev=abc' }] }), - clientPath: id => id === 'p1' ? '/tmp/p1/lib/client.js' : undefined, - }) - expect(() => { trigger(consistent) }).not.toThrow() - }) - - it('throws on a graph row whose bundle path no longer resolves', async () => { - const ctx = await setup({ - graph: () => ({ entries: [{ id: 'ghost', url: '/plugins/ghost/client.js?rev=abc' }] }), - clientPath: () => undefined, - }) - expect(() => { trigger(ctx) }) - .toThrow(/graph row "ghost".*resolves no client bundle path/) - }) -}) diff --git a/packages/host/webserver/tests/web-plugins.spec.ts b/packages/host/webserver/tests/web-plugins.spec.ts deleted file mode 100644 index b9efb1c5c9..0000000000 --- a/packages/host/webserver/tests/web-plugins.spec.ts +++ /dev/null @@ -1,265 +0,0 @@ -import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { Context } from 'cordis' -import { describe, expect, it, vi } from 'vitest' -import { createHostWebPluginRegistry, injectBootManifest } from '../src/index.ts' -import type { LoaderEntryView, WebPluginRegistryDeps } from '../src/index.ts' - -/** Write a fake installed package (package.json + optional client bundle) and return its package.json path. */ -function makePkg(root: string, name: string, pkg: Record<string, unknown>, withBundle = true): string { - const dir = join(root, name.replaceAll('/', '__')) - mkdirSync(join(dir, 'lib'), { recursive: true }) - writeFileSync(join(dir, 'package.json'), JSON.stringify({ name, ...pkg })) - if (withBundle) writeFileSync(join(dir, 'lib', 'client.js'), `// bundle of ${name}`) - return join(dir, 'package.json') -} - -const webDecl = (extra: Record<string, unknown> = {}): Record<string, unknown> => ({ - dshClient: { inject: [], platform: 'web', ...extra }, - exports: { '.': './lib/index.js', './client': './lib/client.js' }, -}) - -interface Fixture { - deps: WebPluginRegistryDeps - entries: LoaderEntryView[] - errors: Error[] - ctx: Context - root: string -} - -function makeDeps( - specs: { name: string; pkg: Record<string, unknown>; loaded?: boolean; disabled?: boolean; withBundle?: boolean }[], -): Fixture { - const root = mkdtempSync(join(tmpdir(), 'dsh-webplugins-')) - const paths = new Map<string, string>() - const entries: LoaderEntryView[] = specs.map((spec) => { - paths.set(spec.name, makePkg(root, spec.name, spec.pkg, spec.withBundle ?? true)) - return { options: { name: spec.name }, fiber: spec.loaded === false ? undefined : {}, disabled: spec.disabled ?? false } - }) - const ctx = new Context() - const errors: Error[] = [] - const deps: WebPluginRegistryDeps = { - ctx, - loader: { entries: () => entries }, - resolvePkgJson: (name) => { - const path = paths.get(name) - if (path === undefined) throw new Error(`unresolvable ${name}`) - return path - }, - onError: err => void errors.push(err), - } - return { deps, entries, errors, ctx, root } -} - -describe('createHostWebPluginRegistry', () => { - it('discovers dshClient rows with rev-stamped urls, manifest inject edges, and the declared immediately mark', () => { - const { deps } = makeDeps([ - { name: '@deepseek-ai/dsh-client-connection', pkg: webDecl({ immediately: true }) }, - { name: '@deepseek-ai/dsh-client-ui-layout', pkg: webDecl({ inject: ['@deepseek-ai/dsh-client-runtime'] }) }, - { name: '@deepseek-ai/dsh-agent', pkg: { exports: { '.': './lib/index.js' } } }, // no dshClient: skipped - ]) - const registry = createHostWebPluginRegistry(deps) - const graph = registry.graph() - expect(graph.rev).toMatch(/^[0-9a-f]{12}$/) - const connection = graph.entries[0] - expect(connection?.id).toBe('@deepseek-ai/dsh-client-connection') - expect(connection?.rev).toMatch(/^[0-9a-f]{12}$/) - expect(connection?.url).toBe(`/plugins/@deepseek-ai/dsh-client-connection/client.js?rev=${connection?.rev ?? ''}`) - expect(connection?.immediately).toBe(true) - const layout = graph.entries[1] - expect(layout?.id).toBe('@deepseek-ai/dsh-client-ui-layout') - expect(layout?.inject).toEqual(['@deepseek-ai/dsh-client-runtime']) - expect(layout?.immediately).toBeUndefined() - expect(graph.entries).toHaveLength(2) - expect(registry.clientPath('@deepseek-ai/dsh-client-ui-layout')).toMatch(/lib[/\\]client\.js$/) - expect(registry.clientPath('@deepseek-ai/dsh-agent')).toBeUndefined() - registry.dispose() - }) - - it('skips entries that are unloaded, disabled, or declare another platform', () => { - const { deps } = makeDeps([ - { name: 'not-loaded', pkg: webDecl(), loaded: false }, - { name: 'disabled', pkg: webDecl(), disabled: true }, - { name: 'electron-only', pkg: { dshClient: { platform: 'electron' }, exports: { './client': './lib/client.js' } } }, - ]) - const registry = createHostWebPluginRegistry(deps) - expect(registry.graph().entries).toEqual([]) - registry.dispose() - }) - - it('fails loud at build time on a dshClient declaration without a "./client" export', () => { - const { deps } = makeDeps([ - { name: 'broken', pkg: { dshClient: { platform: 'web' }, exports: { '.': './lib/index.js' } } }, - ]) - expect(() => createHostWebPluginRegistry(deps)).toThrow(/declares dshClient but exports no/) - }) - - it('fails loud at build time on a registered bundle that is not built (rev hashing reads the file)', () => { - const { deps } = makeDeps([{ name: 'unbuilt', pkg: webDecl(), withBundle: false }]) - expect(() => createHostWebPluginRegistry(deps)).toThrow(/ENOENT/) - }) - - it('fails loud on malformed declaration fields', () => { - for (const dshClient of [42, { platform: 7 }, { platform: 'web', inject: 'nope' }, { platform: 'web', immediately: 'yes' }]) { - const { deps } = makeDeps([{ name: 'bad', pkg: { dshClient, exports: { './client': './lib/client.js' } } }]) - expect(() => createHostWebPluginRegistry(deps)).toThrow(/dshClient/) - } - }) - - it('rebuilt(id) re-hashes the bundle, updates the row and graph rev, and keeps the immediately mark', () => { - const { deps, root } = makeDeps([{ name: 'hot', pkg: webDecl({ immediately: true }) }]) - const registry = createHostWebPluginRegistry(deps) - const before = registry.graph() - const beforeRow = before.entries.find(e => e.id === 'hot') - writeFileSync(join(root, 'hot', 'lib', 'client.js'), '// rebuilt bundle contents') - const rev = registry.rebuilt('hot') - expect(rev).toMatch(/^[0-9a-f]{12}$/) - expect(rev).not.toBe(beforeRow?.rev) - const after = registry.graph() - const afterRow = after.entries.find(e => e.id === 'hot') - expect(afterRow?.rev).toBe(rev) - expect(afterRow?.url).toBe(`/plugins/hot/client.js?rev=${rev ?? ''}`) - expect(afterRow?.immediately).toBe(true) - expect(after.rev).not.toBe(before.rev) - // Unknown ids are not rebuildable. - expect(registry.rebuilt('nope')).toBeUndefined() - registry.dispose() - }) - - it('watch mode: a bundle content change re-hashes the row and notifies onRebuilt; dispose stops the watch', async () => { - const { deps, root } = makeDeps([{ name: 'watched', pkg: webDecl() }]) - deps.watch = { intervalMs: 20 } - const registry = createHostWebPluginRegistry(deps) - const before = registry.graph().entries[0]?.rev - const rebuilds: { id: string; rev: string }[] = [] - registry.onRebuilt((id, rev) => rebuilds.push({ id, rev })) - - writeFileSync(join(root, 'watched', 'lib', 'client.js'), '// new bundle contents') - await vi.waitFor(() => { expect(rebuilds).toHaveLength(1) }, { timeout: 5000 }) - expect(rebuilds[0]?.id).toBe('watched') - expect(rebuilds[0]?.rev).not.toBe(before) - expect(registry.graph().entries[0]?.rev).toBe(rebuilds[0]?.rev) - - registry.dispose() - writeFileSync(join(root, 'watched', 'lib', 'client.js'), '// post-dispose contents') - await new Promise((resolve) => { setTimeout(resolve, 100) }) - expect(rebuilds).toHaveLength(1) - }) - - it('rejects a non-positive or non-integer watch interval at build time', () => { - for (const intervalMs of [0, -5, 1.5]) { - const { deps } = makeDeps([{ name: 'p', pkg: webDecl() }]) - deps.watch = { intervalMs } - expect(() => createHostWebPluginRegistry(deps)).toThrow(/watch\.intervalMs/) - } - }) - - it('rescans on internal/plugin (debounced) and keeps the old graph when a rescan fails', async () => { - const { deps, entries, errors, ctx } = makeDeps([ - { name: 'late-loader', pkg: webDecl(), loaded: false }, - ]) - const registry = createHostWebPluginRegistry(deps) - expect(registry.graph().entries).toEqual([]) - - // Entry finishes loading; a fiber lifecycle event triggers the debounced rescan. - ;(entries[0] as { fiber?: unknown }).fiber = {} - ctx.emit('internal/plugin', ctx.fiber) - ctx.emit('internal/plugin', ctx.fiber) // debounce: two emissions, one rescan - await Promise.resolve() - expect(registry.graph().entries.map(row => row.id)).toEqual(['late-loader']) - - // A failing rescan reports the error and keeps serving the previous graph. - entries.push({ options: { name: 'ghost' }, fiber: {}, disabled: false }) - ctx.emit('internal/plugin', ctx.fiber) - await Promise.resolve() - expect(errors).toHaveLength(1) - expect(registry.graph().entries.map(row => row.id)).toEqual(['late-loader']) - - // After dispose, further fiber events no longer rescan. - registry.dispose() - entries.pop() - ctx.emit('internal/plugin', ctx.fiber) - await Promise.resolve() - expect(errors).toHaveLength(1) - }) -}) - -describe('injectBootManifest', () => { - it('injects the graph as the first script inside <head> and escapes </script> breakouts', () => { - const html = '<html><head><script src="app.js"></script></head><body></body></html>' - const out = injectBootManifest(html, { - rev: 'r1', - entries: [{ id: 'x</script><script>alert(1)', url: '/plugins/x/client.js?rev=r2', rev: 'r2' }], - }) - expect(out.indexOf('window.__DSH_BOOT__')).toBeLessThan(out.indexOf('app.js')) - expect(out).not.toContain('</script><script>alert(1)') - expect(out).toContain('\\u003c/script') - }) - - it('prepends when the page has no <head>', () => { - const out = injectBootManifest('<body>x</body>', { rev: 'r0', entries: [] }) - expect(out.startsWith('<script>window.__DSH_BOOT__')).toBe(true) - }) -}) - -describe('clientExportOf shapes (through the registry build)', () => { - it('accepts the conditional {types, default} export form', () => { - const { deps } = makeDeps([{ - name: 'conditional', - pkg: { - dshClient: { platform: 'web' }, - exports: { './client': { types: './lib/types/client/index.d.ts', default: './lib/client.js' } }, - }, - }]) - const registry = createHostWebPluginRegistry(deps) - expect(registry.clientPath('conditional')).toMatch(/lib[/\\]client\.js$/) - registry.dispose() - }) - - it('rejects a conditional form without a string default, an array form, and a non-object exports field', () => { - for (const exportsField of [ - { './client': { types: './x.d.ts' } }, - { './client': ['./a.js'] }, - ]) { - const { deps } = makeDeps([{ name: 'bad-shape', pkg: { dshClient: { platform: 'web' }, exports: exportsField } }]) - expect(() => createHostWebPluginRegistry(deps)).toThrow(/unsupported shape/) - } - // Non-object exports: treated as "no ./client export" → the declares-but-no-bundle throw. - const { deps } = makeDeps([{ name: 'no-exports', pkg: { dshClient: { platform: 'web' }, exports: './single.js' } }]) - expect(() => createHostWebPluginRegistry(deps)).toThrow(/declares dshClient but exports no/) - }) - - it('skips duplicate loader entries for the same package name (first wins)', () => { - const { deps, entries } = makeDeps([{ name: 'dup-entry', pkg: webDecl() }]) - const first = entries[0] as LoaderEntryView - entries.push({ options: { name: 'dup-entry' }, fiber: {}, disabled: false }) - void first - const registry = createHostWebPluginRegistry(deps) - expect(registry.graph().entries.filter(r => r.id === 'dup-entry')).toHaveLength(1) - registry.dispose() - }) - - it('rejects a null conditional form and wraps a non-Error rescan throw', async () => { - // client: null → the object-form branch's null guard. - const nulled = makeDeps([{ name: 'null-client', pkg: { dshClient: { platform: 'web' }, exports: { './client': null } } }]) - expect(() => createHostWebPluginRegistry(nulled.deps)).toThrow(/unsupported shape/) - - // Non-Error rescan throw: resolvePkgJson throws a string; onError must get a wrapped Error. - const { deps, entries, errors, ctx } = makeDeps([{ name: 'ok-one', pkg: webDecl() }]) - const registry = createHostWebPluginRegistry(deps) - entries.push({ options: { name: 'ghost-two' }, fiber: {}, disabled: false }) - const original = deps.resolvePkgJson - deps.resolvePkgJson = (name) => { - - if (name === 'ghost-two') throw 'string failure' - return original(name) - } - ctx.emit('internal/plugin', ctx.fiber) - await Promise.resolve() - expect(errors[0]).toBeInstanceOf(Error) - expect(String(errors[0])).toContain('string failure') - registry.dispose() - }) - -}) diff --git a/packages/host/webserver/tests/webserver.spec.ts b/packages/host/webserver/tests/webserver.spec.ts deleted file mode 100644 index a4921f1b3e..0000000000 --- a/packages/host/webserver/tests/webserver.spec.ts +++ /dev/null @@ -1,400 +0,0 @@ -import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs' -import { Server as NetServer } from 'node:net' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { startWebServer, type RunningWebServer } from '../src/index.ts' - -/** dist fixture: index.html + one asset of each MIME class + a subdir. */ -function makeDist(): { distIndex: string; distRoot: string } { - const distRoot = mkdtempSync(join(tmpdir(), 'dsh-webserver-')) - writeFileSync(join(distRoot, 'index.html'), '<html>INDEX</html>') - writeFileSync(join(distRoot, 'app.js'), 'console.log(1)') - writeFileSync(join(distRoot, 'app.css'), 'body{}') - writeFileSync(join(distRoot, 'logo.svg'), '<svg/>') - writeFileSync(join(distRoot, 'data.json'), '{}') - writeFileSync(join(distRoot, 'app.js.map'), '{}') - writeFileSync(join(distRoot, 'blob.bin'), 'BIN') - mkdirSync(join(distRoot, 'sub')) - writeFileSync(join(distRoot, 'sub', 'page.html'), '<html>SUB</html>') - return { distIndex: join(distRoot, 'index.html'), distRoot } -} - -const echoingApi = { - fetch: async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => { - const req = input instanceof Request ? input : new Request(input, init) - if (req.url.endsWith('/api/echo')) { - return Response.json({ method: req.method, body: await req.text(), header: req.headers.get('x-probe') }) - } - if (req.url.endsWith('/api/empty')) return new Response(null, { status: 204 }) - if (req.url.endsWith('/api/big')) { - // Chunks far above any socket highWaterMark force res.write to return false. - const big = new Uint8Array(4 * 1024 * 1024).fill(65) - const stream = new ReadableStream<Uint8Array>({ - start(controller) { - controller.enqueue(big) - controller.enqueue(big) - controller.close() - }, - }) - return new Response(stream, { headers: { 'content-type': 'application/octet-stream' } }) - } - if (req.url.endsWith('/api/sse')) { - const encoder = new TextEncoder() - const stream = new ReadableStream<Uint8Array>({ - start(controller) { - controller.enqueue(encoder.encode('data: one\n\n')) - controller.enqueue(encoder.encode('data: two\n\n')) - controller.close() - }, - }) - return new Response(stream, { headers: { 'content-type': 'text/event-stream' } }) - } - if (req.url.endsWith('/api/throw-string')) { - // Non-Error rejection: the guard must wrap it for onError. - throw 'string failure' - } - if (req.url.endsWith('/api/explode-mid-stream')) { - // Headers go out with the first chunk, then the source errors: the - // guard's headersSent leg must destroy the socket, not writeHead again. - // The error is deferred a tick so the 200 + first chunk actually flush - // to the client before the teardown. - const stream = new ReadableStream<Uint8Array>({ - start(controller) { - controller.enqueue(new TextEncoder().encode('data: first\n\n')) - setTimeout(() => { controller.error(new Error('stream exploded')) }, 20) - }, - }) - return new Response(stream, { headers: { 'content-type': 'text/event-stream' } }) - } - if (req.url.endsWith('/api/abort-probe')) { - // Endless SSE that only ends when the request signal aborts. - const stream = new ReadableStream<Uint8Array>({ - start(controller) { - req.signal.addEventListener('abort', () => { - try { - controller.close() - } catch { /* already closed by teardown: nothing else can reach this */ } - }, { once: true }) - controller.enqueue(new TextEncoder().encode('data: open\n\n')) - }, - }) - return new Response(stream, { headers: { 'content-type': 'text/event-stream' } }) - } - return new Response('nope', { status: 404 }) - }, -} - -let server: RunningWebServer | undefined - -afterEach(async () => { - await server?.close() - server = undefined -}) - -async function boot(onError: (err: Error) => void = () => undefined): Promise<string> { - const { distIndex } = makeDist() - server = await startWebServer({ host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi }, onError) - return `http://127.0.0.1:${String(server.port)}` -} - -describe('startWebServer', () => { - it('reports the listening port and closes idempotently', async () => { - const { distIndex } = makeDist() - server = await startWebServer({ host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi }, () => undefined) - expect(server.port).toBeGreaterThan(0) - const first = server.close() - const second = server.close() - expect(second).toBe(first) - await first - server = undefined - }) - - it.each(['127.0.0.1', '0.0.0.0'])('forwards bind address %s without opening a socket', async (host) => { - const { distIndex } = makeDist() - const port = 3080 - const listen = vi.spyOn(NetServer.prototype, 'listen').mockImplementation(function ( - this: NetServer, ...args: unknown[] - ): NetServer { - const callback = args.at(-1) - if (typeof callback !== 'function') throw new TypeError('listen callback missing') - queueMicrotask(callback as () => void) - return this - }) - const address = vi.spyOn(NetServer.prototype, 'address').mockReturnValue({ address: host, family: 'IPv4', port }) - try { - const inertServer = await startWebServer({ host, port, distIndex, apiHandler: echoingApi }, () => undefined) - expect(listen).toHaveBeenCalledWith(port, host, expect.any(Function)) - await inertServer.close() - } finally { - address.mockRestore() - listen.mockRestore() - } - }) - - it('rejects when the port is already taken', async () => { - const { distIndex } = makeDist() - server = await startWebServer({ host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi }, () => undefined) - const { port } = server - await expect(startWebServer({ host: '127.0.0.1', port, distIndex, apiHandler: echoingApi }, () => undefined)) - .rejects.toMatchObject({ code: 'EADDRINUSE' }) - }) -}) - -describe.skipIf(process.platform === 'win32')('static serving', () => { - it('serves index at /, subpaths by MIME, octet-stream for unknown, SPA fallback on miss', async () => { - const base = await boot() - const index = await fetch(`${base}/`) - expect(index.status).toBe(200) - expect(index.headers.get('content-type')).toBe('text/html; charset=utf-8') - expect(await index.text()).toBe('<html>INDEX</html>') - - expect((await fetch(`${base}/app.js`)).headers.get('content-type')).toBe('text/javascript; charset=utf-8') - expect((await fetch(`${base}/app.css`)).headers.get('content-type')).toBe('text/css; charset=utf-8') - expect((await fetch(`${base}/logo.svg`)).headers.get('content-type')).toBe('image/svg+xml') - expect((await fetch(`${base}/data.json`)).headers.get('content-type')).toBe('application/json') - expect((await fetch(`${base}/app.js.map`)).headers.get('content-type')).toBe('application/json') - expect((await fetch(`${base}/blob.bin`)).headers.get('content-type')).toBe('application/octet-stream') - expect(await (await fetch(`${base}/sub/page.html`)).text()).toBe('<html>SUB</html>') - - const miss = await fetch(`${base}/routes/deep/link`) - expect(miss.status).toBe(200) - expect(await miss.text()).toBe('<html>INDEX</html>') - }) - - it('403s traversal outside the dist root and 405s non-GET/HEAD', async () => { - const base = await boot() - // %2e%2e would be dot-collapsed by WHATWG URL parsing on both ends; an - // encoded slash keeps the segment intact until the server's decodeURIComponent. - const traversal = await fetch(`${base}/..%2f..%2fetc%2fpasswd`) - expect(traversal.status).toBe(403) - const put = await fetch(`${base}/index.html`, { method: 'PUT', body: 'x' }) - expect(put.status).toBe(405) - }) - - it('answers HEAD like GET (no 405)', async () => { - const base = await boot() - const head = await fetch(`${base}/`, { method: 'HEAD' }) - expect(head.status).toBe(200) - }) -}) - -describe.skipIf(process.platform === 'win32')('web plugin surfaces (boot injection + bundle endpoint + events channel)', () => { - const FETCH_ID = '@deepseek-ai/dsh-client-ui-layout' - const graphValue = { - rev: 'graphrev00001', - entries: [ - { id: '@deepseek-ai/dsh-client-connection', url: '/plugins/@deepseek-ai/dsh-client-connection/client.js?rev=eeee2222ffff', rev: 'eeee2222ffff', immediately: true }, - { id: FETCH_ID, url: `/plugins/${FETCH_ID}/client.js?rev=aaaa0000bbbb`, rev: 'aaaa0000bbbb', inject: [] }, - ], - } - - /** Captures the server's onRebuilt subscription so tests can fire registry notifications by hand. */ - interface RebuiltHarness { - notify: (id: string, rev: string) => void - unsubscribed: boolean - } - - async function bootWithPlugins(harness?: RebuiltHarness): Promise<string> { - const { distIndex, distRoot } = makeDist() - writeFileSync(join(distRoot, 'bundle.js'), 'window.DSHClientProxy.loadPlugin({})') - const webPlugins = { - graph: () => graphValue, - clientPath: (id: string) => id === FETCH_ID ? join(distRoot, 'bundle.js') : undefined, - onRebuilt: (listener: (id: string, rev: string) => void) => { - if (harness !== undefined) harness.notify = listener - return () => { - if (harness !== undefined) harness.unsubscribed = true - } - }, - } - server = await startWebServer( - { host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi, webPlugins }, () => undefined, - ) - return `http://127.0.0.1:${String(server.port)}` - } - - it('injects the window.__DSH_BOOT__ graph into / and SPA fallbacks; asset requests stay verbatim', async () => { - const base = await bootWithPlugins() - const index = await (await fetch(`${base}/`)).text() - expect(index).toContain('window.__DSH_BOOT__') - const manifest = /window\.__DSH_BOOT__ = (.*?)<\/script>/.exec(index)?.[1] - expect(JSON.parse(manifest ?? '')).toEqual(graphValue) - - const fallback = await (await fetch(`${base}/routes/deep/link`)).text() - expect(fallback).toContain('window.__DSH_BOOT__') - const direct = await (await fetch(`${base}/index.html`)).text() - expect(direct).toContain('window.__DSH_BOOT__') - - expect(await (await fetch(`${base}/app.js`)).text()).toBe('console.log(1)') - }) - - it('serves registered client bundles with no-cache (rev query ignored) and 404s unknown ids (no SPA fallback)', async () => { - const base = await bootWithPlugins() - const bundle = await fetch(`${base}/plugins/${FETCH_ID}/client.js?rev=whatever`) - expect(bundle.status).toBe(200) - expect(bundle.headers.get('content-type')).toBe('text/javascript; charset=utf-8') - expect(bundle.headers.get('cache-control')).toBe('no-cache') - expect(await bundle.text()).toContain('DSHClientProxy') - - expect((await fetch(`${base}/plugins/unknown/client.js`)).status).toBe(404) - }) - - it('404s a registered id whose bundle file is unreadable (unbuilt dist must fail loud, not fall back to HTML)', async () => { - const { distIndex } = makeDist() - const webPlugins = { - graph: () => graphValue, - clientPath: () => '/nonexistent/lib/client.js', - onRebuilt: () => () => undefined, - } - server = await startWebServer( - { host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi, webPlugins }, () => undefined, - ) - const res = await fetch(`http://127.0.0.1:${String(server.port)}/plugins/${FETCH_ID}/client.js`) - expect(res.status).toBe(404) - }) - - it('keeps all plugin surfaces off without the webPlugins option', async () => { - const base = await boot() - expect(await (await fetch(`${base}/`)).text()).toBe('<html>INDEX</html>') - // No plugin routes: fall through to static SPA fallback semantics. - const res = await fetch(`${base}/plugins/x/client.js`) - expect(res.status).toBe(200) - expect(await res.text()).toBe('<html>INDEX</html>') - const events = await fetch(`${base}/plugins/events`) - expect(await events.text()).toBe('<html>INDEX</html>') - }) - - it('GET /plugins/events opens SSE with the current graph frame; a registry rebuild notification broadcasts', async () => { - const harness: RebuiltHarness = { notify: () => { throw new Error('onRebuilt never subscribed') }, unsubscribed: false } - const base = await bootWithPlugins(harness) - const events = await fetch(`${base}/plugins/events`) - expect(events.status).toBe(200) - expect(events.headers.get('content-type')).toBe('text/event-stream') - const reader = events.body?.getReader() - const decoder = new TextDecoder() - let buffer = '' - async function readUntil(marker: string): Promise<void> { - while (!buffer.includes(marker)) { - const chunk = await reader?.read() - if (chunk?.done !== false) throw new Error('SSE stream ended early') - buffer += decoder.decode(chunk.value, { stream: true }) - } - } - await readUntil('"type":"graph"') - expect(buffer).toContain(': connected') - const graphLine = /data: (.*)\n\n/.exec(buffer)?.[1] - expect(JSON.parse(graphLine ?? '')).toEqual({ type: 'graph', graph: graphValue }) - - // The registry's bundle watch observed a rebuild: the server relays it as an SSE frame. - harness.notify(FETCH_ID, 'cccc1111dddd') - await readUntil('"type":"rebuilt"') - expect(buffer).toContain(JSON.stringify({ type: 'rebuilt', id: FETCH_ID, rev: 'cccc1111dddd' })) - await reader?.cancel() - - // Shutdown unsubscribes the relay (no broadcast into a closed channel). - await server?.close() - server = undefined - expect(harness.unsubscribed).toBe(true) - }) -}) - -describe('request-handling guard (one bad request must not kill the process)', () => { - it('400s malformed %-escapes, reports to onError, and stays alive', async () => { - const errors: Error[] = [] - const base = await boot(err => errors.push(err)) - for (const path of ['/%', '/%c0', '/%zz%']) { - expect((await fetch(`${base}${path}`)).status).toBe(400) - } - expect(errors.length).toBe(3) - expect(errors[0]?.name).toBe('URIError') - // The barrage left the server serving. - expect((await fetch(`${base}/`)).status).toBe(200) - }) - - it('wraps a non-Error throw for onError and still answers 400', async () => { - const errors: Error[] = [] - const base = await boot(err => errors.push(err)) - expect((await fetch(`${base}/api/throw-string`, { method: 'POST' })).status).toBe(400) - expect(errors[0]).toBeInstanceOf(Error) - expect(errors[0]?.message).toBe('string failure') - }) - - it('destroys the socket when the failure lands after headers went out', async () => { - const errors: Error[] = [] - const base = await boot(err => errors.push(err)) - const response = await fetch(`${base}/api/explode-mid-stream`) - expect(response.status).toBe(200) // headers made it out before the explosion - await expect(response.text()).rejects.toThrow() // then the socket is torn down - expect(errors.length).toBe(1) - expect((await fetch(`${base}/`)).status).toBe(200) - }) -}) - -describe('/api bridge', () => { - it('forwards method, headers, and body; relays status and body back', async () => { - const base = await boot() - const response = await fetch(`${base}/api/echo`, { - method: 'POST', - headers: { 'content-type': 'application/json', 'x-probe': 'p1' }, - body: JSON.stringify({ n: 1 }), - }) - expect(response.status).toBe(200) - expect(await response.json()).toEqual({ method: 'POST', body: '{"n":1}', header: 'p1' }) - }) - - it('relays a bodyless response', async () => { - const base = await boot() - const response = await fetch(`${base}/api/empty`, { method: 'POST' }) - expect(response.status).toBe(204) - expect(await response.text()).toBe('') - }) - - it('streams SSE frames through chunk by chunk', async () => { - const base = await boot() - const response = await fetch(`${base}/api/sse`) - expect(response.headers.get('content-type')).toBe('text/event-stream') - expect(await response.text()).toBe('data: one\n\ndata: two\n\n') - }) - - it('waits for drain when a streamed chunk overfills the socket buffer', async () => { - // 4 MiB chunks dwarf the socket highWaterMark, so res.write returns false - // and the bridge parks on 'drain'; reading the body to completion proves - // the loop resumed instead of dropping the remainder. - const base = await boot() - const response = await fetch(`${base}/api/big`) - const body = new Uint8Array(await response.arrayBuffer()) - expect(body.length).toBe(8 * 1024 * 1024) - expect(body[0]).toBe(65) - expect(body[body.length - 1]).toBe(65) - }) - - it('releases a drain wait when the client disconnects mid-chunk', async () => { - // The 'close' leg of the drain race: abort while the socket buffer is - // still full so the parked write wakes via 'close', not 'drain'. - const base = await boot() - const ac = new AbortController() - const response = await fetch(`${base}/api/big`, { signal: ac.signal }) - const reader = response.body?.getReader() - const first = await reader?.read() - expect(first?.value?.length).toBeGreaterThan(0) - ac.abort() - // afterEach close() completing is the leak assertion, same as abort-probe. - await new Promise((resolve) => { setTimeout(resolve, 50) }) - }) - - it('aborts the bridged request when the client disconnects mid-SSE', async () => { - const base = await boot() - const ac = new AbortController() - const response = await fetch(`${base}/api/abort-probe`, { signal: ac.signal }) - const reader = response.body?.getReader() - expect(reader).toBeDefined() - const first = await reader?.read() - expect(new TextDecoder().decode(first?.value)).toContain('open') - ac.abort() - // server-side abort propagation has no client-observable handshake beyond - // the closed connection; close() would hang on a leaked live SSE socket, - // so afterEach completing IS the assertion that the bridge released it. - await new Promise((resolve) => { setTimeout(resolve, 50) }) - }) -}) diff --git a/packages/host/webserver/tsconfig.json b/packages/host/webserver/tsconfig.json index e1c893a8fc..8aaa97516f 100644 --- a/packages/host/webserver/tsconfig.json +++ b/packages/host/webserver/tsconfig.json @@ -11,6 +11,9 @@ { "path": "../../../vendor/cordis" }, + { + "path": "../../../vendor/schemastery" + }, { "path": "../../support/invariants" } diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 5a9a1bfdbc..628c9d8b1c 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -26,7 +26,7 @@ The package root exposes the Cordis plugin contract and `DeepSeekAdapter`; wire contextWindow: 64000 ``` -The plugin registers the single provider route `deepseek`. A request selects it with `provider: deepseek`; its `model` is passed through as the wire `model` string, so changing DeepSeek models does not require lifecycle-time registration. Omitting `models` advertises `deepseek-v4-flash` and `deepseek-v4-pro`, each with a 128,000-token context window; an explicit list replaces those defaults, while `models: []` advertises none. Catalog entries are exposed through `ctx.llm.listModels('deepseek')` for clients such as ACP editors, but remain advisory: unlisted model ids still pass through unchanged. An omitted entry name defaults to its id. +The plugin registers the single provider route `deepseek`. A request selects it with `provider: deepseek`; its `model` is passed through as the wire `model` string, so changing DeepSeek models does not require lifecycle-time registration. Omitting `models` advertises `deepseek-v4-flash` and `deepseek-v4-pro`, each with a 128,000-token context window; an explicit list replaces those defaults, while `models: []` advertises none. Catalog entries are exposed through `ctx.llm.listModels('deepseek')` for UI selectors and deployment introspection, but remain advisory: unlisted model ids still pass through unchanged. An omitted entry name defaults to its id. `contextWindow` is optional per configured model and is not exposed through the advisory catalog. `ctx.llm.resolveModelContext('deepseek', model)` returns an exact model value first, then `defaultContextWindow` for an entry without capacity or an unlisted pass-through id. When neither value exists it returns `undefined` without invalidating routing. Pressure-sensitive plugins therefore get deployment-owned capacity without treating the model selector as authoritative. Registering another adapter for `deepseek` throws `LlmError('DUPLICATE_ADAPTER')`. diff --git a/packages/lsp/tool-lsp/README.md b/packages/lsp/tool-lsp/README.md index e2f15ba79a..e1817a0ff7 100644 --- a/packages/lsp/tool-lsp/README.md +++ b/packages/lsp/tool-lsp/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-tool-lsp -The model-facing **`lsp` tool** over `ctx.lsp`: one read-only tool with four operations for precise code navigation. It owns the model schema, prompt guidance, coordinate conversion, result limits and formatting, and ACP presentation; it imports no provider. +The model-facing **`lsp` tool** over `ctx.lsp`: one read-only tool with four operations for precise code navigation. It owns the model schema, prompt guidance, coordinate conversion, result limits and formatting, and UI presentation; it imports no provider. Namespace plugin (`name` / `inject` / `Config` / `apply`, no default export). Injects `tools`, `lsp`, and `systemPrompt`. @@ -68,7 +68,7 @@ Capped per tool result by `maxResultChars`, with `maxLocations` additionally bou Tool results append after the cached request prefix and do not directly invalidate it. -### ACP presentation +### UI presentation #### What the model sees @@ -80,7 +80,7 @@ Zero direct token effect because rendering is client-side only. #### KV Cache effect -None; ACP presentation is outside the model request. +None; UI presentation is outside the model request. ## Known Limitations and Deferred Work diff --git a/packages/lsp/tool-lsp/src/render.ts b/packages/lsp/tool-lsp/src/render.ts index b6341ae407..215dfb60e6 100644 --- a/packages/lsp/tool-lsp/src/render.ts +++ b/packages/lsp/tool-lsp/src/render.ts @@ -1,7 +1,7 @@ /** * Pure formatting and coordinate conversion for the `lsp` tool: one-based↔zero-based UTF-16 cursor * conversion, workspace-grouped location rendering with `file:`-URI resolution, complete-result - * capping, and ACP presentation. No I/O — a UI may call the presenter on live streaming and on + * capping, and UI presentation. No I/O — a UI may call the presenter on live streaming and on * replay, so it depends only on the tool arguments. * @module @deepseek-ai/dsh-tool-lsp/render */ @@ -152,9 +152,9 @@ export function renderUri(uri: string, workspaceRoot: string): string { } /** - * ACP presentation for a pending `lsp` call. Uses a generic search card; the title carries the - * operation and one-based cursor, and `locations` focuses the queried line (ACP `FileLocation` has - * no character, so the title preserves the column). + * UI presentation for a pending `lsp` call. Uses a generic search card; the title carries the + * operation and one-based cursor, and `locations` focuses the queried line. The shared location + * shape has no character, so the title preserves the column. * @param args - the raw tool arguments. * @returns the generic call view. */ diff --git a/packages/plan/README.md b/packages/plan/README.md index f90d16ab51..4aedb8c9aa 100644 --- a/packages/plan/README.md +++ b/packages/plan/README.md @@ -6,4 +6,4 @@ Plan mode is one logged, per-agent collaboration state. It is a single **product |---|---|---| | `plan-mode/` | `plan/mode` vocabulary + fold, boundary-applied state, the `plan:policy` guidance section, `/plan [message]` entry and `/plan off` exit, and the model-facing `exit_plan_mode` review tool | `ctx.planMode` | -The active state is a pure function of the session log, so resume and fork restore it without extra machinery. The deployment supplies plan instructions through Cordis config, while `exit_plan_mode` stays registered when planning is inactive to keep the request tool catalog stable. ACP maps this capability onto its generic `default` / `plan` picker; sandbox mode and approval policy remain independent enforcement settings. Design: [plan-mode Agent Note](../../.agents/notes/implemented/feature/2026-07-07-plan-mode.md) and [plan-specific state simplification](../../.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.md). +The active state is a pure function of the session log, so resume and fork restore it without extra machinery. The deployment supplies plan instructions through Cordis config, while `exit_plan_mode` stays registered when planning is inactive to keep the request tool catalog stable. Interactive adapters use the plugin-owned `/plan` command; sandbox mode and approval policy remain independent enforcement settings. Design: [plan-mode Agent Note](../../.agents/notes/implemented/feature/2026-07-07-plan-mode.md) and [plan-specific state simplification](../../.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.md). diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 0f24508d14..8032e83c4c 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -14,7 +14,7 @@ While active, `plan:policy` renders the configured `section`. The plugin always When `ctx.commands` is composed, the package registers `/plan [message]` and reserves the exact argument `off` for direct exit. Bare `/plan` selects plan mode; any other non-empty argument selects it first and is then submitted through `agent.steer()`, so it becomes the next step's ordinary logged user message under plan guidance. `/plan off` selects inactive without sending model input; it also cancels a pending entry before plan mode reaches a request. -ACP is an adapter, not the owner of this vocabulary: it advertises the fixed wire ids `default` and `plan`, maps `session/set_mode` to the boolean service, and translates committed `plan/mode` events back to `current_mode_update`. +The TUI consumes the plugin-owned `/plan` command; other front doors may drive the same service directly without defining a second mode vocabulary. ## Configuration @@ -86,3 +86,4 @@ Mode transitions do not change the tool catalog; plan arguments and review resul - Plan mode guides rather than enforces; deployments needing a hard boundary must combine independent sandbox and approval controls. - A pending selection made while idle is lost if the process exits before the next boundary, so the UI must reapply it. - Forked agents inherit logged plan state, while newly spawned agents begin inactive; there is no creation-time plan option. +- The `exit_plan_mode` review arc (submit → human review → approved flip or rejected feedback) is covered by package tests only; its assembled-application snapshot left with the retired ACP UI scenarios ([automation-only ACP](../../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md)) and the TUI keyless scenarios exercise only `/plan` entry and `/plan off` exit. diff --git a/packages/plan/plan-mode/tests/integration.spec.ts b/packages/plan/plan-mode/tests/integration.spec.ts index e195ed54b2..f5ec5f2727 100644 --- a/packages/plan/plan-mode/tests/integration.spec.ts +++ b/packages/plan/plan-mode/tests/integration.spec.ts @@ -71,8 +71,8 @@ describe('plan mode through the agent loop', () => { ]) const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('it-plan-seed'), { provider: 'mock', model: 'mock' }) - // Selected while idle (the ACP picker shape): the pending intent flushes at - // the first prompt-submit, BEFORE the first assembly. + // Selected while idle: the pending intent flushes at the first + // prompt-submit, BEFORE the first assembly. ctx.planMode.set(agent, true) agent.followup([{ type: 'text', text: 'explore the repo' }]) diff --git a/packages/pty/pty-local/README.md b/packages/pty/pty-local/README.md index 2167f91f85..a2b3aec391 100644 --- a/packages/pty/pty-local/README.md +++ b/packages/pty/pty-local/README.md @@ -1,12 +1,12 @@ # @deepseek-ai/dsh-pty-local -Local `node-pty` backend for `ctx.pty`. It starts an interactive shell under the shared `ctx.sandboxPolicy`, strips credential-shaped ambient environment variables, retains bounded line-oriented output, detects readiness, and tears down the captured process tree rooted at the `node-pty` child. +Local Linux/macOS `node-pty` backend for `ctx.pty`; loading it on another platform fails as unsupported. It starts an interactive shell under the shared `ctx.sandboxPolicy`, strips credential-shaped ambient environment variables, retains bounded line-oriented output, detects readiness, and tears down the captured process tree rooted at the `node-pty` child. ## Plugin (`pty-local`) The plugin injects `pty`, `sandbox`, and `sandboxPolicy`, then registers the configured backend type (`shell`). `danger-full-access` starts the shell directly; confined modes wrap the exact shell argv through `ctx.sandbox`. The effective session mode is resolved at spawn. A change to a different effective mode is rejected before its `sandbox/mode` event commits while that owner has an open PTY or a spawn in progress; the fence is attached to the exact owner and therefore outlives a local-provider reload that retains existing sessions. Wait for creation to settle and close the sessions before changing modes, so a terminal opened with wider access cannot survive a downgrade. -Linux readiness combines a foreground-verified private bash prompt marker, foreground-process-group syscall inspection, silence fallback, and absolute timeout. macOS uses the verified prompt marker plus silence/timeout because it has no `/proc` syscall surface. A marker is not ready until printable prompt text arrives, including when the OSC marker and `PS1` are split across data callbacks. Unrecognized or unreadable process state is never a positive exact-idle signal. During unpublished startup, a fallback requires observed output; zero-output silence cannot publish an empty session, and timeout rejects the spawn. Cancellation closes the unpublished shell and rejects with the caller's exact abort reason even when its foreground process group is not observable yet; if that close fails, `PtyBackendCleanupError` separately preserves the cleanup failure for registry disposal. Incomplete terminal-control sequences are bounded by `maxReadBytes` and discarded through their terminator after crossing that limit; a trailing carriage return is carried across callbacks so split CRLF becomes one newline. +Linux readiness combines a foreground-verified private bash prompt marker, foreground-process-group syscall inspection, silence fallback, and absolute timeout. macOS uses the verified prompt marker plus silence/timeout because it has no `/proc` syscall surface. A marker is not ready until printable prompt text arrives, including when the OSC marker and `PS1` are split across data callbacks; when bash prints the marker before the kernel publishes its return to the foreground process group, polling retains the candidate until bash ownership is observable or the ordinary silence bound expires. An interactive child that inherits `PROMPT_COMMAND` therefore cannot suppress inferred-idle readiness until the absolute timeout. Unrecognized or unreadable process state is never a positive exact-idle signal. During unpublished startup, a fallback requires observed output; zero-output silence cannot publish an empty session, and timeout rejects the spawn. Cancellation closes the unpublished shell and rejects with the caller's exact abort reason even when its foreground process group is not observable yet; if that close fails, `PtyBackendCleanupError` separately preserves the cleanup failure for registry disposal. Incomplete terminal-control sequences are bounded by `maxReadBytes` and discarded through their terminator after crossing that limit; a trailing carriage return is carried across callbacks so split CRLF becomes one newline. Send cancellation resolves the current foreground process group and delivers a real `SIGINT`; it never emulates interruption by writing `\x03`, so raw-mode programs remain cancellable. Close sends `SIGTERM` to descendants, waits, then sends `SIGKILL` to the union of captured survivors and newly scanned descendants so reparenting cannot hide a process from teardown. It verifies that every retained identity is gone or, on Linux, a non-executing zombie before stopping the shell; zombie entries are quiescent and are reaped as the shell exits. A survivor failure does not cache a permanently rejected close; a later close retries the teardown. diff --git a/packages/pty/pty-local/src/session.ts b/packages/pty/pty-local/src/session.ts index 20cd013dcf..4b1faccc94 100644 --- a/packages/pty/pty-local/src/session.ts +++ b/packages/pty/pty-local/src/session.ts @@ -288,11 +288,12 @@ export class LocalPtySession implements PtyBackendSession { if (sanitized.prompt) { const foregroundPgid = this.inspector.foregroundPgid(this.pid) if (this.shellPgid === undefined) this.shellPgid = foregroundPgid - if (foregroundPgid !== undefined && foregroundPgid === this.shellPgid) { - this.promptSeen = true - this.promptTextSeen = sanitized.promptText === true - this.lastOutputAt = Date.now() - } + // Bash can print PROMPT_COMMAND before the kernel publishes its return + // to the foreground process group. Retain the marker; polling below is + // the authority that accepts it only after bash owns the foreground. + this.promptSeen = true + this.promptTextSeen = sanitized.promptText === true + this.lastOutputAt = Date.now() } else if (this.promptSeen && sanitized.promptText === true) { this.promptTextSeen = true } @@ -312,8 +313,11 @@ export class LocalPtySession implements PtyBackendSession { return } if (this.promptSeen && this.promptTextSeen && Date.now() - this.lastOutputAt >= this.config.pollIntervalMs) { - this.settleActive('stdin_read') - return + const pgid = this.inspector.foregroundPgid(this.pid) + if (this.shellPgid !== undefined && pgid === this.shellPgid) { + this.settleActive('stdin_read') + return + } } const elapsed = Date.now() - operation.startedAt const startupHasOutput = !this.initializing || this.scrollback.snapshot().text.length > 0 @@ -324,6 +328,10 @@ export class LocalPtySession implements PtyBackendSession { return } } + // A prompt candidate can race bash's foreground handoff, but an interactive + // child also inherits PROMPT_COMMAND. Silence therefore remains the bound + // on waiting for shell ownership instead of letting a child marker suppress + // readiness until the absolute timeout. if (startupHasOutput && Date.now() - this.lastOutputAt >= this.config.idleSilenceMs) { this.settleActive('inferred_idle') return diff --git a/packages/pty/pty-local/tests/index.spec.ts b/packages/pty/pty-local/tests/index.spec.ts index 26f4ddcc11..8fe6d9d4ae 100644 --- a/packages/pty/pty-local/tests/index.spec.ts +++ b/packages/pty/pty-local/tests/index.spec.ts @@ -187,7 +187,12 @@ describe('LocalPtyBackend startup rollback', () => { kill() { exitListener?.({ exitCode: 0, signal: 15 }) }, resize() {}, clear() {}, pause() {}, resume() {}, } as IPty - const backend = new LocalPtyBackend(ctx, config(), inspector, () => terminal) + const backend = new LocalPtyBackend( + ctx, + config(), + { ...inspector, foregroundPgid: () => terminal.pid }, + () => terminal, + ) const session = await backend.spawn(spec(agent(ctx))) expect(session.motd).toBe('dsh> ') await session.close('test complete') diff --git a/packages/pty/pty-local/tests/session.spec.ts b/packages/pty/pty-local/tests/session.spec.ts index 6f7144f409..4be21c79a6 100644 --- a/packages/pty/pty-local/tests/session.spec.ts +++ b/packages/pty/pty-local/tests/session.spec.ts @@ -286,7 +286,7 @@ describe('LocalPtySession readiness and output', () => { expect(session.motd).toBe('dsh> ') }) - it('trusts prompt markers only while the startup shell owns the foreground group', async () => { + it('retains a prompt marker until the startup shell regains the foreground group', async () => { vi.useFakeTimers() const terminal = new FakeTerminal() const inspector = new FakeInspector() @@ -297,15 +297,30 @@ describe('LocalPtySession readiness and output', () => { let settled = false void operation.done.then(() => { settled = true }) inspector.pgid = 789 - terminal.emitData('\x1b]133;D;0\x07spoofed') - await vi.advanceTimersByTimeAsync(10) + terminal.emitData('\x1b]133;D;0\x07dsh> ') + await vi.advanceTimersByTimeAsync(40) expect(settled).toBe(false) inspector.pgid = 456 - terminal.emitData('\x1b]133;D;0\x07dsh> ') await vi.advanceTimersByTimeAsync(10) + expect(settled).toBe(true) expect((await operation.done).waitReason).toBe('stdin_read') }) + + it('falls back to inferred idle when a foreground child emits an inherited prompt marker', async () => { + vi.useFakeTimers() + const terminal = new FakeTerminal() + const inspector = new FakeInspector() + const session = new LocalPtySession(terminal.asPty(), inspector, config()) + await initialize(session, terminal) + + const operation = session.startSend({ text: 'bash -i', submit: true }) + inspector.pgid = 789 + terminal.emitData('\x1b]133;D;0\x07child> ') + await vi.advanceTimersByTimeAsync(100) + + expect((await operation.done).waitReason).toBe('inferred_idle') + }) }) describe('LocalPtySession bounds, signals, and teardown', () => { diff --git a/packages/pty/tool-pty/README.md b/packages/pty/tool-pty/README.md index 3f9733496a..f4f1e7af7e 100644 --- a/packages/pty/tool-pty/README.md +++ b/packages/pty/tool-pty/README.md @@ -2,7 +2,7 @@ Six model-facing tools over `ctx.pty`: `terminal_open`, `terminal_send`, `terminal_read`, `terminal_signal`, `terminal_close`, and `terminal_list`. Every operation requires the exact initiating `Agent`, so a model cannot address another agent's terminal even if it learns the id. -`terminal_send(run_in_background: true)` reuses `ctx.tasks`; task preflight and the PTY service's exclusive per-session send reservation occur before the task id is returned, completion is collected with `task_output`, and `task_kill` delivers `SIGINT` to the foreground process group. Foreground sends use terminal ACP call/result cards. Background sends use a generic execute card; open, read, signal, close, and list use generic `execute`, `read`, `execute`, `delete`, and `read` cards respectively. None declares source locations. +`terminal_send(run_in_background: true)` reuses `ctx.tasks`; task preflight and the PTY service's exclusive per-session send reservation occur before the task id is returned, completion is collected with `task_output`, and `task_kill` delivers `SIGINT` to the foreground process group. Foreground sends use terminal call/result cards. Background sends use a generic execute card; open, read, signal, close, and list use generic `execute`, `read`, `execute`, `delete`, and `read` cards respectively. None declares source locations. ## Config diff --git a/packages/pty/tool-pty/src/render.ts b/packages/pty/tool-pty/src/render.ts index 361de1eab5..6fe8a1880f 100644 --- a/packages/pty/tool-pty/src/render.ts +++ b/packages/pty/tool-pty/src/render.ts @@ -1,4 +1,4 @@ -/** Model and ACP rendering for persistent terminal tool results. */ +/** Model and UI rendering for persistent terminal tool results. */ import { TextRetainer } from '@deepseek-ai/dsh-retention' diff --git a/packages/sandbox/sandbox-policy/README.md b/packages/sandbox/sandbox-policy/README.md index 783b338acf..bb43a555d6 100644 --- a/packages/sandbox/sandbox-policy/README.md +++ b/packages/sandbox/sandbox-policy/README.md @@ -23,7 +23,7 @@ The optional `./invariant` companion rejects a forged durable `sandbox/mode` eve ## The per-session store -A runtime switch (an ACP `session/set_config_option`, a test scenario) is one log-only `sandbox/mode` event on the session it applies to. `effective = explicit grant ?? fold(events) ?? deployment default`, so an override survives restart by replay and two sessions never see each other's state. Workspace identity does not need another event: the immutable `SessionHeader.cwd` recorded at creation is the root for every call in that session. The event is log-only (the `approval/*` precedent): the model learns the mode from the enforcing tools' denial markers, never from the event. +A runtime switch is one log-only `sandbox/mode` event on the session it applies to. `effective = explicit grant ?? fold(events) ?? deployment default`, so an override survives restart by replay and two sessions never see each other's state. Workspace identity does not need another event: the immutable `SessionHeader.cwd` recorded at creation is the root for every call in that session. The event is log-only (the `approval/*` precedent): the model learns the mode from the enforcing tools' denial markers, never from the event. ## Model Experience diff --git a/packages/sandbox/sandbox-policy/src/session-mode.ts b/packages/sandbox/sandbox-policy/src/session-mode.ts index ad7fe0ef29..a97532b29b 100644 --- a/packages/sandbox/sandbox-policy/src/session-mode.ts +++ b/packages/sandbox/sandbox-policy/src/session-mode.ts @@ -1,7 +1,7 @@ /** * Per-session sandbox-mode override: the session log as the store. A runtime - * switch (an ACP `session/set_config_option`, a test scenario) is recorded as - * one `sandbox/mode` event on the session it applies to; + * switch (a UI policy control or test scenario) is recorded as one + * `sandbox/mode` event on the session it applies to; * `effective = fold(events) ?? the deployment default`, so an override * survives restart by replay, two sessions can never see each other's state, * and there is no external config store. The event is log-only (the diff --git a/packages/sandbox/sandbox-policy/tests/policy.spec.ts b/packages/sandbox/sandbox-policy/tests/policy.spec.ts index cd81caa6b4..9e3eae4605 100644 --- a/packages/sandbox/sandbox-policy/tests/policy.spec.ts +++ b/packages/sandbox/sandbox-policy/tests/policy.spec.ts @@ -69,7 +69,7 @@ describe('SandboxPolicyService', () => { }) }) - it('resolves a symlink-sensitive session cwd with filesystem semantics', async () => { + it.skipIf(process.platform === 'win32')('resolves a symlink-sensitive session cwd with POSIX component semantics', async () => { const root = mkdtempSync(join(tmpdir(), 'dsh-policy-cwd-')) try { const lexical = join(root, 'lexical') @@ -78,7 +78,7 @@ describe('SandboxPolicyService', () => { mkdirSync(lexical) mkdirSync(child, { recursive: true }) const link = join(lexical, 'link') - symlinkSync(child, link, process.platform === 'win32' ? 'junction' : 'dir') + symlinkSync(child, link, 'dir') const cwd = `${link}${sep}..` const ctx = await mounted({ mode: 'workspace-write', workspaceRoot: '/fallback' }) diff --git a/packages/sandbox/sandbox/tests/roots.spec.ts b/packages/sandbox/sandbox/tests/roots.spec.ts index fd0d2cd7bd..49fdc03816 100644 --- a/packages/sandbox/sandbox/tests/roots.spec.ts +++ b/packages/sandbox/sandbox/tests/roots.spec.ts @@ -14,7 +14,7 @@ import { canonicalPath, writableRoots } from '@deepseek-ai/dsh-sandbox' describe('canonicalPath', () => { it('resolves symlinks (an existing path realpaths)', () => { const dir = mkdtempSync(join(tmpdir(), 'dsh-roots-')) - expect(canonicalPath(dir)).toBe(realpathSync(dir)) + expect(canonicalPath(dir)).toBe(realpathSync.native(dir)) }) it('returns the spelling as-is when the path cannot be resolved (conservative — matches nothing until it exists)', () => { @@ -30,9 +30,9 @@ describe('writableRoots', () => { it('workspace-write grants the workspace root plus the platform temp areas, canonical and deduplicated', () => { const ws = mkdtempSync(join(tmpdir(), 'dsh-ws-')) const roots = writableRoots({ mode: 'workspace-write', workspaceRoot: ws }) - expect(roots).toContain(realpathSync(ws)) + expect(roots).toContain(realpathSync.native(ws)) expect(roots).toContain(canonicalPath('/tmp')) - expect(roots).toContain(realpathSync(tmpdir())) + expect(roots).toContain(realpathSync.native(tmpdir())) // Deduplicated after canonicalization (/tmp and os.tmpdir() may coincide). expect(new Set(roots).size).toBe(roots.length) }) diff --git a/packages/sdk/create-sdk/src/create-questions.ts b/packages/sdk/create-sdk/src/create-questions.ts index 193f1fdc25..236385e45c 100644 --- a/packages/sdk/create-sdk/src/create-questions.ts +++ b/packages/sdk/create-sdk/src/create-questions.ts @@ -168,7 +168,7 @@ const PROJECT_QUESTION_STEPS: readonly WizardStep<ProjectAnswerState>[] = [ id: 'interface', message: 'Run interface', options: [ - { value: 'acp', label: 'ACP server' }, + { value: 'acp', label: 'ACP automation server' }, { value: 'tui', label: 'Terminal TUI' }, { value: 'embed', label: 'Embedded context' }, ], diff --git a/packages/sdk/create-sdk/tests/create.snapshot.ts b/packages/sdk/create-sdk/tests/create.snapshot.ts index 83a1f74932..941c8cbb7f 100644 --- a/packages/sdk/create-sdk/tests/create.snapshot.ts +++ b/packages/sdk/create-sdk/tests/create.snapshot.ts @@ -183,7 +183,7 @@ describe.skipIf(process.platform === 'win32')('create-sdk terminal contract', () "kind": "select", "message": "Run interface", "options": [ - "ACP server", + "ACP automation server", "Terminal TUI", "Embedded context", ], @@ -287,12 +287,6 @@ describe.skipIf(process.platform === 'win32')('create-sdk terminal contract', () "label": "Tool timeout policy", "required": false, }, - { - "choices": undefined, - "default": false, - "label": "Ask the user from the model loop", - "required": false, - }, ], }, { diff --git a/packages/sdk/create-sdk/tests/link-workspace.e2e.ts b/packages/sdk/create-sdk/tests/link-workspace.e2e.ts index 6e0b404dc6..0fefefdffa 100644 --- a/packages/sdk/create-sdk/tests/link-workspace.e2e.ts +++ b/packages/sdk/create-sdk/tests/link-workspace.e2e.ts @@ -1,7 +1,7 @@ import { execFile } from 'node:child_process' import { existsSync } from 'node:fs' import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' +import { homedir, tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { promisify } from 'node:util' @@ -20,6 +20,15 @@ const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url)) const builtScripts = join(repoRoot, 'packages/sdk/scripts/lib/bin.js') const temporary: string[] = [] +function resolveCorepackHome(): string { + return process.env.COREPACK_HOME ?? join( + process.env.XDG_CACHE_HOME + ?? process.env.LOCALAPPDATA + ?? join(homedir(), process.platform === 'win32' ? 'AppData/Local' : '.cache'), + 'node/corepack', + ) +} + afterEach(async () => { await Promise.all(temporary.splice(0).map(path => rm(path, { recursive: true, force: true }))) }) @@ -71,13 +80,16 @@ describe.skipIf(!existsSync(builtScripts))('live-linked generated projects', () } `) const cacheRoot = join(tmpdir(), 'dsh-sdk-link-cache', name) + const pnpmStore = name === 'pnpm' + ? (await execFileAsync(name, ['store', 'path', '--silent'], { encoding: 'utf8' })).stdout.trim() + : undefined const commandEnvironment = { ...scrubEnvironment(), - COREPACK_HOME: join(cacheRoot, 'corepack'), - XDG_CACHE_HOME: join(cacheRoot, 'cache'), + COREPACK_HOME: resolveCorepackHome(), + ...name === 'pnpm' ? {} : { XDG_CACHE_HOME: join(cacheRoot, 'cache') }, XDG_DATA_HOME: join(cacheRoot, 'data'), npm_config_cache: join(cacheRoot, 'npm'), - pnpm_config_store_dir: join(cacheRoot, 'pnpm-store'), + ...pnpmStore === undefined ? {} : { pnpm_config_store_dir: pnpmStore }, } await execFileAsync(name, manager.installCommand(), { cwd: root, diff --git a/packages/sdk/helper/README.md b/packages/sdk/helper/README.md index 89ca897d31..bfe5d31d3f 100644 --- a/packages/sdk/helper/README.md +++ b/packages/sdk/helper/README.md @@ -6,7 +6,7 @@ The package owns the builtin typed-spec catalog, provider/app behavior entities, All business and document validation completes before commit writes any affected file. Commit detects external edits made after the session opened, but deliberately provides no cross-file rollback after writing starts. -Builtin features are provider, bash, app, persistence, HMR, filesystem, todo, skill, web, subagent, workflow, compaction, hooks, repeat-tool guard, timeout policy, and ask-user. The catalog owns feature options, required and non-default Cordis plugin config, feature requirements, resource contribution, and round-trip markers; create and config use the same registry and configurator. The ACP app option contributes the human-command and user-interaction services before the bridge. +Builtin features are provider, bash, app, persistence, HMR, filesystem, todo, skill, web, subagent, workflow, compaction, hooks, repeat-tool guard, timeout policy, and ask-user. The catalog owns feature options, required and non-default Cordis plugin config, feature requirements, resource contribution, and round-trip markers; create and config use the same registry and configurator. The ACP app option contributes only the automation bridge; interactive services belong to TUI or Web compositions. `SdkProject.open()` requires only readable root `package.json` and `cordis.yml`. A Cordis config entry anchors feature installation; a package present only through a linked NPM dependency closure leaves the feature absent. Once an owned Cordis config entry exists, an incomplete resource shape is `inconsistent` and cannot be modified automatically. diff --git a/packages/sdk/helper/src/features/builtin/app.ts b/packages/sdk/helper/src/features/builtin/app.ts index 835a9a8710..ed4050bf11 100644 --- a/packages/sdk/helper/src/features/builtin/app.ts +++ b/packages/sdk/helper/src/features/builtin/app.ts @@ -73,14 +73,6 @@ class AppOption extends FeatureOption { case 'acp': return new ProjectContribution([ ...appProjectResources(profile, this.id), - ...npmCordisConfigEntry(ID, { - id: 'commands', - name: '@deepseek-ai/dsh-commands', - }), - ...npmCordisConfigEntry(ID, { - id: 'user-interaction', - name: '@deepseek-ai/dsh-user-interaction', - }), ...npmCordisConfigEntry(ID, { id: 'acp', name: '@deepseek-ai/dsh-acp', @@ -119,7 +111,7 @@ export class AppFeature extends ExclusiveOptionFeature { override readonly required = true override readonly requires = [featureId('spine')] override readonly options = [ - new AppOption('acp', 'ACP server'), + new AppOption('acp', 'ACP automation server'), new AppOption('tui', 'Terminal TUI'), new AppOption('embed', 'Embedded context'), ] diff --git a/packages/sdk/helper/src/features/builtin/index.ts b/packages/sdk/helper/src/features/builtin/index.ts index 29889b438e..48b50977f8 100644 --- a/packages/sdk/helper/src/features/builtin/index.ts +++ b/packages/sdk/helper/src/features/builtin/index.ts @@ -347,7 +347,7 @@ config: id: 'ask-user', summary: 'Ask the user from the model loop', mode: 'single', - supportedInterfaces: ['acp', 'tui'], + supportedInterfaces: ['tui'], options: [{ id: 'default', label: 'ask_user_question tool', diff --git a/packages/sdk/helper/src/templates/assets/README.md.tpl b/packages/sdk/helper/src/templates/assets/README.md.tpl index bdaef06c4e..c9843a2d15 100644 --- a/packages/sdk/helper/src/templates/assets/README.md.tpl +++ b/packages/sdk/helper/src/templates/assets/README.md.tpl @@ -5,9 +5,9 @@ Built with the DeepSeek Harness SDK using the {{model}} model. {{#if isAcp}} -## Run as an ACP server +## Run as an ACP automation server -Run `{{packageManager}} start` and configure your ACP client to launch this project. Standard output is reserved for ACP JSON-RPC. +Run `{{packageManager}} start` and configure a programmatic ACP client to launch this project. Standard output is reserved for ACP JSON-RPC. {{else}} {{#if isTui}} ## Run in a terminal diff --git a/packages/sdk/helper/tests/project.spec.ts b/packages/sdk/helper/tests/project.spec.ts index bc3e5ebe12..f1216d2768 100644 --- a/packages/sdk/helper/tests/project.spec.ts +++ b/packages/sdk/helper/tests/project.spec.ts @@ -289,12 +289,13 @@ describe('SdkProject and ProjectEditSession', () => { edit.configureFeature(registry.get(featureId('app')), selection('app', ['acp'])) const acp = (await edit.commit()).project expect(acp.profile.runInterface).toBe('acp') - expect(acp.cordis.entry('commands')).toMatchObject({ name: '@deepseek-ai/dsh-commands' }) + expect(acp.cordis.entry('commands')).toBeUndefined() + expect(acp.cordis.entry('user-interaction')).toBeUndefined() expect(acp.packageManifest().scripts).toMatchObject({ dev: 'dsh-sdk dev index.ts', start: 'dsh-sdk start index.js', }) - expect(await readFile(join(acp.root, 'README.md'), 'utf8')).toContain('Run as an ACP server') + expect(await readFile(join(acp.root, 'README.md'), 'utf8')).toContain('Run as an ACP automation server') expect(await readFile(join(acp.root, 'index.ts'), 'utf8')).not.toContain('agents.create') const acpRegistry = createBuiltinRegistry(acp.profile) @@ -324,12 +325,16 @@ describe('SdkProject and ProjectEditSession', () => { .toContain('missing package.json script dev') }) - it('rejects enabled features that do not apply to the target app interface', async () => { + it('rejects ask-user on non-interactive app interfaces', async () => { const project = await createCommitted([selection('ask-user', ['default'])]) const registry = createBuiltinRegistry(project.profile) - const edit = project.edit(registry) - edit.configureFeature(registry.get(featureId('app')), selection('app', ['embed'])) - await expect(edit.commit()).rejects.toThrow('feature ask-user is not available for embed') + const embed = project.edit(registry) + embed.configureFeature(registry.get(featureId('app')), selection('app', ['embed'])) + await expect(embed.commit()).rejects.toThrow('feature ask-user is not available for embed') + + const acp = project.edit(registry) + acp.configureFeature(registry.get(featureId('app')), selection('app', ['acp'])) + await expect(acp.commit()).rejects.toThrow('feature ask-user is not available for acp') }) it('supports disabled feature reconfiguration and rejects invalid state operations', async () => { diff --git a/packages/sdk/scripts/tests/__snapshots__/config.snapshot.ts.snap b/packages/sdk/scripts/tests/__snapshots__/config.snapshot.ts.snap index 14f74b0f85..f3d6867225 100644 --- a/packages/sdk/scripts/tests/__snapshots__/config.snapshot.ts.snap +++ b/packages/sdk/scripts/tests/__snapshots__/config.snapshot.ts.snap @@ -85,7 +85,7 @@ Change file: package.json "choices": [ { "default": false, - "label": "ACP server", + "label": "ACP automation server", "value": "acp", }, { diff --git a/packages/sdk/scripts/tests/scripts.spec.ts b/packages/sdk/scripts/tests/scripts.spec.ts index fa8eb00d41..74c450025f 100644 --- a/packages/sdk/scripts/tests/scripts.spec.ts +++ b/packages/sdk/scripts/tests/scripts.spec.ts @@ -542,23 +542,23 @@ describe('ConfigWorkflow', () => { expect(result.commit?.project.cordis.entry('agent-core')).toBeUndefined() }) - it('disables ask-user when switching its app interface to embed', async () => { + it('disables ask-user when switching its app interface to ACP', async () => { const project = await committedProject([ { id: featureId('ask-user'), options: ['default'] }, - ], [], 'acp') + ], [], 'tui') const registry = createBuiltinRegistry(project.profile) const output = outputBuffer() const workflow = new ConfigWorkflow(new QueuePort([ [ { value: 'feature:provider', choices: ['deepseek'] }, - { value: 'feature:app', choices: ['embed'] }, + { value: 'feature:app', choices: ['acp'] }, { value: 'feature:persistence', choices: ['jsonl'] }, { value: 'feature:ask-user', choices: ['default'] }, ], true, ]), output.stream, async () => {}) const result = await workflow.run(project, registry) - expect(result.commit?.project.profile.runInterface).toBe('embed') + expect(result.commit?.project.profile.runInterface).toBe('acp') expect(result.commit?.project.cordis.entry('tool-ask-user')?.disabled).toBe(true) expect(output.read()).toContain('Disable feature: ask-user') }) diff --git a/packages/session-persistence/session-persistence-jsonl/src/format.ts b/packages/session-persistence/session-persistence-jsonl/src/format.ts index 2a34a1ce80..48f99e6610 100644 --- a/packages/session-persistence/session-persistence-jsonl/src/format.ts +++ b/packages/session-persistence/session-persistence-jsonl/src/format.ts @@ -84,6 +84,9 @@ function isHeaderLine(value: unknown): value is HeaderLine { && typeof (value as { version?: unknown }).version === 'number' && typeof (value as { id?: unknown }).id === 'string' && typeof (value as { createdAt?: unknown }).createdAt === 'number' + && Number.isSafeInteger((value as { createdAt: number }).createdAt) + && (value as { createdAt: number }).createdAt >= 0 + && !Object.is((value as { createdAt: number }).createdAt, -0) && typeof (value as { delegationDepth?: unknown }).delegationDepth === 'number' && Number.isSafeInteger((value as { delegationDepth: number }).delegationDepth) && (value as { delegationDepth: number }).delegationDepth >= 0 diff --git a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts index bc5142f1cb..32a854ba5e 100644 --- a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts +++ b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts @@ -251,17 +251,15 @@ describe('SessionPersistenceJsonl: durability and crash semantics', () => { }) it('surfaces non-ENOENT snapshot stat failures after discovery', async () => { - const blocker = join(root, 'snapshot-not-a-directory') - await writeFile(blocker, 'x') const persistence = ctx.sessionPersistence as unknown as { listArtifacts(): Promise<Array<{ header: SessionHeader; path: string }>> } const discovery = vi.spyOn(persistence, 'listArtifacts').mockResolvedValue([{ header: meta('snapshot-stat-failure'), - path: join(blocker, 'session.jsonl'), + path: `${root}\0snapshot-stat-failure`, }]) - await expect(ctx.sessionPersistence.listSnapshots()).rejects.toThrow(/ENOTDIR/) + await expect(ctx.sessionPersistence.listSnapshots()).rejects.toThrow(/null bytes/) discovery.mockRestore() }) @@ -609,6 +607,26 @@ describe('SessionPersistenceJsonl: scanLog unit', () => { expect(() => scanLog(Buffer.from('{"type":"event"}\n'))).toThrow(/session header/) }) + it.each([ + ['fractional', 1.5], + ['negative', -1], + ['unsafe', Number.MAX_SAFE_INTEGER + 1], + ])('rejects a session header with a %s createdAt', (_label, createdAt) => { + const log = JSON.stringify({ + type: 'session', + version: 0, + id: 'invalid-created-at', + createdAt, + delegationDepth: 0, + }) + '\n' + expect(() => scanLog(Buffer.from(log))).toThrow(/session header/) + }) + + it('rejects a session header with negative-zero createdAt', () => { + const log = '{"type":"session","version":0,"id":"invalid-created-at","createdAt":-0,"delegationDepth":0}\n' + expect(() => scanLog(Buffer.from(log))).toThrow(/session header/) + }) + it.each([ ['missing', undefined], ['a string', '1'], diff --git a/packages/session-persistence/session-persistence-sqlite/README.md b/packages/session-persistence/session-persistence-sqlite/README.md index dda164fc33..04091e6e21 100644 --- a/packages/session-persistence/session-persistence-sqlite/README.md +++ b/packages/session-persistence/session-persistence-sqlite/README.md @@ -8,9 +8,9 @@ A SQLite durable session-persistence backend — a second `SessionPersistence` i ## Storage model -Each `SessionEvent` maps 1:1 onto a row in an `events` table `(session_id, seq, type, time, data, source_event_seqs, surface_op)` — `data` is the event payload as JSON text, so the row shape is the event verbatim (including `assistant/chunk`, keeping `seq` contiguous). The two `TEXT` columns `source_event_seqs` and `surface_op` are nullable; they store the event's optional surface-metadata fields (see [session surface](../../../.agents/notes/implemented/architecture/2026-06-18-session-surface.md)). Out-of-log metadata (`SessionHeader`), a per-materialization incarnation id, and a monotonic per-log revision live in a `sessions` row; a singleton state row carries the immutable store id. A `sessions` row is written only by the first `append` — its existence is the lazy-materialization signal (`list` reports exactly the sessions that have a row). +Each `SessionEvent` maps 1:1 onto a row in an `events` table `(session_id, seq, type, time, data, source_event_seqs, surface_op)` — `data` is the event payload as JSON text, so the row shape is the event verbatim (including `assistant/chunk`, keeping `seq` contiguous). The two `TEXT` columns `source_event_seqs` and `surface_op` are nullable; they store the event's optional surface-metadata fields (see [session surface](../../../.agents/notes/implemented/architecture/2026-06-18-session-surface.md)). Out-of-log metadata (`SessionHeader`), a per-materialization incarnation id, and a monotonic per-log revision live in a `sessions` row; `createdAt` is a non-negative safe integer stored in a strict `INTEGER` column. A singleton state row carries the immutable store id. A `sessions` row is written only by the first `append` — its existence is the lazy-materialization signal (`list` reports exactly the sessions that have a row). -The repository's Node range supports unflagged `node:sqlite`. The database enables foreign keys and uses the configured journal mode (`wal` by default; use a rollback mode where WAL shared-memory files are unsuitable). `PRAGMA user_version` stores the table-layout version; databases with any other version are rejected because this unreleased format has no migrations. +The repository's Node range supports unflagged `node:sqlite`. The database enables foreign keys and uses the configured journal mode (`wal` by default; use a rollback mode where WAL shared-memory files are unsuitable). `PRAGMA application_id` identifies the canonical persistence database, and `PRAGMA user_version` stores its layout version. A fresh database must have no application identity or user-defined schema objects; initialization creates every table and stamps both pragmas in one transaction. Non-pristine unversioned databases, foreign application identities, and every non-current version reject before journal-mode mutation because this unreleased format has no migrations. On filesystems with POSIX modes, the backend requests mode `0700` for missing directories and exclusively creates a missing database with mode `0600` before SQLite opens it; the process umask may further restrict both. New WAL, shared-memory, and persistent rollback-journal sidecars receive the database's resulting owner-only mode. Existing directories, database files, and sidecars keep their modes; filesystem setup errors other than an existing database fail initialization. These defaults prevent incidental exposure through a permissive process umask, but do not protect database confidentiality or integrity when another principal can replace the database entry in its parent directory. @@ -55,5 +55,5 @@ SQLite storage does not mutate live request prefixes. A resumed loop can reuse p - **`DatabaseSync` is synchronous** — every append transaction blocks the event loop for its duration; acceptable for local stores, a throughput ceiling for busy multi-session servers. - **Write contention has no wait or retry policy** — the backend sets no busy timeout and retries no locked-database error, so another connection holding a write transaction makes the operation reject immediately. -- **Only the current `SCHEMA_VERSION` opens** — a database with any other schema version is rejected rather than migrated (unreleased software; no persisted user data to preserve). +- **Only a pristine new database or the current owned `SCHEMA_VERSION` opens** — unversioned schema objects, foreign application identities, and every other schema version are rejected rather than migrated (unreleased software; no persisted user data to preserve). - **Nothing deletes stored sessions** — rows accumulate until removed externally (the seam has no deletion surface; `ON DELETE CASCADE` is wired for such out-of-band cleanup). diff --git a/packages/session-persistence/session-persistence-sqlite/src/schema.ts b/packages/session-persistence/session-persistence-sqlite/src/schema.ts index 8b8dcd78e0..754d9d7e63 100644 --- a/packages/session-persistence/session-persistence-sqlite/src/schema.ts +++ b/packages/session-persistence/session-persistence-sqlite/src/schema.ts @@ -17,7 +17,10 @@ import type { SessionEvent, SessionId, SessionHeader, SurfaceOp } from '@deepsee * layout; orthogonal to a session's own `version` (which versions the EVENT * vocabulary, stored per session in the `sessions` row). */ -export const SCHEMA_VERSION = 8 +export const SCHEMA_VERSION = 10 + +/** SQLite application id protecting unrelated databases from persistence writes. */ +export const SESSION_PERSISTENCE_SQLITE_APPLICATION_ID = 0x44534850 /** * A row of the `sessions` table — the out-of-log metadata ({@link SessionHeader}). @@ -63,9 +66,10 @@ export interface EventRow { export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' /** - * Open the database and apply its schema and pragmas. A zero `user_version` is - * stamped with {@link SCHEMA_VERSION}; every other non-current version rejects - * rather than being migrated in place. + * Open the database and apply its schema and pragmas. An empty database with a + * zero `user_version` is initialized at {@link SCHEMA_VERSION}; a nonempty + * unversioned database and every other non-current version reject rather than + * being migrated in place. * @param path - the SQLite database file to open (created when absent). * @param journalMode - validated journal pragma. * @returns the open handle with pragmas applied and all three tables ensured. @@ -83,51 +87,81 @@ export function openDatabase(path: string, journalMode: JournalMode): DatabaseSy function configureDatabase(db: DatabaseSync, path: string, journalMode: JournalMode): void { db.exec('PRAGMA foreign_keys = ON') + let began = false + try { + db.exec('BEGIN IMMEDIATE') + began = true + // Validate while holding the write lock so no other connection can change + // schema ownership between inspection and initialization. + const { user_version: onDisk } = db.prepare('PRAGMA user_version').get() as { user_version: number } + const { application_id: applicationId } = db.prepare('PRAGMA application_id').get() as { application_id: number } + const { count: userObjectCount } = db.prepare( + "SELECT COUNT(*) AS count FROM sqlite_schema WHERE name NOT GLOB 'sqlite_*'", + ).get() as { count: number } + if (onDisk === 0 && (applicationId !== 0 || userObjectCount > 0)) { + throw new Error(`session database at "${path}" has an unversioned schema or application identity`) + } + if (onDisk !== 0 && onDisk !== SCHEMA_VERSION) { + throw new Error(`session database at "${path}" has schema version ${onDisk}, incompatible with this build (${SCHEMA_VERSION})`) + } + if (onDisk === SCHEMA_VERSION && applicationId !== SESSION_PERSISTENCE_SQLITE_APPLICATION_ID) { + throw new Error( + `session database at "${path}" has application id ${applicationId}, expected ${SESSION_PERSISTENCE_SQLITE_APPLICATION_ID}`, + ) + } + db.exec(` + CREATE TABLE IF NOT EXISTS persistence_state ( + singleton INTEGER PRIMARY KEY CHECK (singleton = 1), + store_id TEXT NOT NULL + ) STRICT; + + CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + version INTEGER NOT NULL, + created_at INTEGER NOT NULL, + cwd TEXT, + parent_session TEXT, + seed_length INTEGER, + delegation_depth INTEGER, + incarnation TEXT NOT NULL, + revision INTEGER NOT NULL + ) STRICT; + + CREATE TABLE IF NOT EXISTS events ( + session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + seq INTEGER NOT NULL, + type TEXT NOT NULL, + time INTEGER NOT NULL, + data TEXT NOT NULL, + source_event_seqs TEXT, + surface_op TEXT, + PRIMARY KEY (session_id, seq) + ) STRICT + `) + db.prepare( + 'INSERT OR IGNORE INTO persistence_state (singleton, store_id) VALUES (1, ?)', + ).run(randomUUID()) + if (onDisk === 0) { + db.exec(`PRAGMA application_id = ${SESSION_PERSISTENCE_SQLITE_APPLICATION_ID}`) + db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`) + } + db.exec('COMMIT') + began = false + } catch (error: unknown) { + /* v8 ignore next -- a BEGIN failure leaves no transaction to roll back. */ + if (began) { + /* v8 ignore next 5 -- preserve the original schema failure if SQLite also refuses rollback. */ + try { + db.exec('ROLLBACK') + } catch { + // The original SQLite failure remains the actionable cause. + } + } + throw error + } // The validated union is safe to interpolate into a non-bindable PRAGMA. + // Apply it only after ownership validation and initialization commit. db.exec(`PRAGMA journal_mode = ${journalMode.toUpperCase()}`) - // `PRAGMA user_version` always returns exactly one row { user_version }. - const { user_version: onDisk } = db.prepare('PRAGMA user_version').get() as { user_version: number } - if (onDisk !== 0 && onDisk !== SCHEMA_VERSION) { - throw new Error(`session database at "${path}" has schema version ${onDisk}, incompatible with this build (${SCHEMA_VERSION})`) - } - if (onDisk === 0) { - // Stamp fresh or pre-versioning databases. - db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`) - } - db.exec(` - CREATE TABLE IF NOT EXISTS persistence_state ( - singleton INTEGER PRIMARY KEY CHECK (singleton = 1), - store_id TEXT NOT NULL - ) STRICT - `) - db.prepare( - 'INSERT OR IGNORE INTO persistence_state (singleton, store_id) VALUES (1, ?)', - ).run(randomUUID()) - db.exec(` - CREATE TABLE IF NOT EXISTS sessions ( - id TEXT PRIMARY KEY, - version INTEGER NOT NULL, - created_at INTEGER NOT NULL, - cwd TEXT, - parent_session TEXT, - seed_length INTEGER, - delegation_depth INTEGER, - incarnation TEXT NOT NULL, - revision INTEGER NOT NULL - ) STRICT - `) - db.exec(` - CREATE TABLE IF NOT EXISTS events ( - session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, - seq INTEGER NOT NULL, - type TEXT NOT NULL, - time INTEGER NOT NULL, - data TEXT NOT NULL, - source_event_seqs TEXT, - surface_op TEXT, - PRIMARY KEY (session_id, seq) - ) STRICT - `) } /** @@ -136,6 +170,9 @@ function configureDatabase(db: DatabaseSync, path: string, journalMode: JournalM * @returns the header, `NULL` columns mapped to omitted optional fields. */ export function rowToMeta(row: SessionRow): SessionHeader { + if (!Number.isSafeInteger(row.created_at) || row.created_at < 0) { + throw new Error('stored session createdAt must be a non-negative safe integer') + } return { version: row.version, id: row.id as SessionId, diff --git a/packages/session-persistence/session-persistence-sqlite/tests/sqlite.spec.ts b/packages/session-persistence/session-persistence-sqlite/tests/sqlite.spec.ts index e70c041bca..09d43d0c7f 100644 --- a/packages/session-persistence/session-persistence-sqlite/tests/sqlite.spec.ts +++ b/packages/session-persistence/session-persistence-sqlite/tests/sqlite.spec.ts @@ -4,10 +4,18 @@ import { existsSync } from 'node:fs' import { chmod, mkdtemp, rm, stat, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' +import { DatabaseSync } from 'node:sqlite' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, SurfaceEvent, SurfaceEventType } from '@deepseek-ai/dsh-session' import SessionPersistenceSqlite, { SCHEMA_VERSION } from '@deepseek-ai/dsh-session-persistence-sqlite' -import { openDatabase, rowToEvent, scanRows, type EventRow } from '../src/schema.ts' +import { + openDatabase, + rowToEvent, + rowToMeta, + scanRows, + SESSION_PERSISTENCE_SQLITE_APPLICATION_ID, + type EventRow, +} from '../src/schema.ts' import { runPersistenceContract, meta, oneTurnLog, appendLog } from '../../session-persistence/tests/contract.ts' import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts' @@ -150,6 +158,22 @@ describe('scanRows', () => { }) }) +describe('rowToMeta', () => { + it('rejects fractional stored creation metadata', () => { + expect(() => rowToMeta({ + id: 'fractional', + version: 0, + created_at: 1.5, + cwd: null, + parent_session: null, + seed_length: null, + incarnation: 'fractional', + revision: 1, + delegation_depth: null, + })).toThrow('stored session createdAt must be a non-negative safe integer') + }) +}) + describe('SessionPersistenceSqlite: durability and crash semantics', () => { it('rejects a stored v0 log containing a legacy request/header-delta event', async () => { const path = await freshDbPath() @@ -304,6 +328,121 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => { expect(() => openDatabase(olderPath, 'wal')).toThrow(/incompatible with this build/) }) + it('rejects a table-backed unversioned database before stamping or changing journal mode', async () => { + const path = await freshDbPath() + const legacy = new DatabaseSync(path) + legacy.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY)') + legacy.close() + + expect(() => openDatabase(path, 'wal')).toThrow(/unversioned schema or application identity/) + + const unchanged = new DatabaseSync(path) + expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 }) + expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' }) + expect(unchanged.prepare( + "SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'sessions'", + ).get()).toEqual({ name: 'sessions' }) + unchanged.close() + }) + + it('counts a sqliteX table as user-owned instead of mistaking it for SQLite metadata', async () => { + const path = await freshDbPath() + const unrelated = new DatabaseSync(path) + unrelated.exec('CREATE TABLE sqliteX (value TEXT)') + unrelated.exec("INSERT INTO sqliteX VALUES ('safe')") + unrelated.close() + + expect(() => openDatabase(path, 'wal')).toThrow(/unversioned schema or application identity/) + + const unchanged = new DatabaseSync(path) + expect(unchanged.prepare('SELECT value FROM sqliteX').get()).toEqual({ value: 'safe' }) + expect(unchanged.prepare('PRAGMA application_id').get()).toEqual({ application_id: 0 }) + expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 }) + expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' }) + unchanged.close() + }) + + it('rejects view-only and foreign-application unversioned databases without mutation', async () => { + const viewPath = await freshDbPath() + const viewOnly = new DatabaseSync(viewPath) + viewOnly.exec('CREATE VIEW foreign_view AS SELECT 1 AS value') + viewOnly.close() + + expect(() => openDatabase(viewPath, 'wal')).toThrow(/unversioned schema or application identity/) + const unchangedView = new DatabaseSync(viewPath) + expect(unchangedView.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' }) + expect(unchangedView.prepare( + "SELECT type FROM sqlite_schema WHERE name = 'foreign_view'", + ).get()).toEqual({ type: 'view' }) + unchangedView.close() + + const applicationPath = await freshDbPath() + const foreignApplication = new DatabaseSync(applicationPath) + foreignApplication.exec('PRAGMA application_id = 12345') + foreignApplication.close() + + expect(() => openDatabase(applicationPath, 'wal')).toThrow(/unversioned schema or application identity/) + const unchangedApplication = new DatabaseSync(applicationPath) + expect(unchangedApplication.prepare('PRAGMA application_id').get()).toEqual({ application_id: 12345 }) + expect(unchangedApplication.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 }) + expect(unchangedApplication.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' }) + unchangedApplication.close() + }) + + it('rejects a current-version database with a foreign application identity', async () => { + const path = await freshDbPath() + const foreign = new DatabaseSync(path) + foreign.exec('PRAGMA application_id = 12345') + foreign.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`) + foreign.close() + + expect(() => openDatabase(path, 'wal')).toThrow(/has application id 12345/) + + const unchanged = new DatabaseSync(path) + expect(unchanged.prepare('PRAGMA application_id').get()).toEqual({ application_id: 12345 }) + expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: SCHEMA_VERSION }) + expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' }) + unchanged.close() + }) + + it('rolls back schema objects and identity stamps when initialization fails', async () => { + const path = await freshDbPath() + const conflicting = new DatabaseSync(path) + conflicting.exec(`PRAGMA application_id = ${SESSION_PERSISTENCE_SQLITE_APPLICATION_ID}`) + conflicting.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`) + conflicting.exec("CREATE VIEW persistence_state AS SELECT 1 AS singleton, 'foreign' AS store_id") + conflicting.close() + + expect(() => openDatabase(path, 'wal')).toThrow() + + const unchanged = new DatabaseSync(path) + expect(unchanged.prepare( + "SELECT type FROM sqlite_schema WHERE name = 'persistence_state'", + ).get()).toEqual({ type: 'view' }) + expect(unchanged.prepare( + "SELECT type FROM sqlite_schema WHERE name = 'sessions'", + ).get()).toBeUndefined() + expect(unchanged.prepare( + "SELECT type FROM sqlite_schema WHERE name = 'events'", + ).get()).toBeUndefined() + expect(unchanged.prepare('PRAGMA application_id').get()) + .toEqual({ application_id: SESSION_PERSISTENCE_SQLITE_APPLICATION_ID }) + expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: SCHEMA_VERSION }) + expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' }) + unchanged.close() + }) + + it('stamps the persistence application identity with the schema version', async () => { + const path = await freshDbPath() + openDatabase(path, 'wal').close() + + const db = new DatabaseSync(path) + expect(db.prepare('PRAGMA application_id').get()) + .toEqual({ application_id: SESSION_PERSISTENCE_SQLITE_APPLICATION_ID }) + expect(db.prepare('PRAGMA user_version').get()).toEqual({ user_version: SCHEMA_VERSION }) + db.close() + }) + it('rejects a sibling v3 database (the merge-collided version) rather than opening it against missing columns', async () => { // Version 3 identified two incompatible sibling layouts, so it is always rejected. const path = await freshDbPath() @@ -467,7 +606,7 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => { }) it('exposes the schema version constant', () => { - expect(SCHEMA_VERSION).toBe(8) + expect(SCHEMA_VERSION).toBe(10) }) it('keeps the revision stable for an empty repair hook', async () => { diff --git a/packages/session-persistence/session-persistence/src/coordinator.ts b/packages/session-persistence/session-persistence/src/coordinator.ts index 442011bd2c..c252957db7 100644 --- a/packages/session-persistence/session-persistence/src/coordinator.ts +++ b/packages/session-persistence/session-persistence/src/coordinator.ts @@ -183,6 +183,9 @@ export class PersistenceCoordinator<TornMarker = unknown> { if (snapshot === undefined) { return Promise.reject(new TypeError('session metadata must be losslessly JSON-serializable')) } + if (!Number.isSafeInteger(snapshot.createdAt) || snapshot.createdAt < 0) { + return Promise.reject(new TypeError('session metadata createdAt must be a non-negative safe integer')) + } return this.serialize(snapshot.id, () => this.createCore(snapshot)) } diff --git a/packages/session-persistence/session-persistence/tests/contract.ts b/packages/session-persistence/session-persistence/tests/contract.ts index e61fe65bb7..88d1eef68e 100644 --- a/packages/session-persistence/session-persistence/tests/contract.ts +++ b/packages/session-persistence/session-persistence/tests/contract.ts @@ -84,6 +84,22 @@ export function runPersistenceContract(name: string, make: () => Promise<Contrac } }) + it('rejects a fractional creation timestamp without reserving its session id', async () => { + const { persistence, dispose } = await make() + try { + const m = { ...meta('fractional-created-at'), createdAt: 1.5 } + await expect(persistence.create(m)) + .rejects.toThrow('session metadata createdAt must be a non-negative safe integer') + + const valid = meta('fractional-created-at') + await persistence.create(valid) + await persistence.append(valid.id, oneTurnLog()) + expect((await persistence.load(valid.id)).meta.createdAt).toBe(valid.createdAt) + } finally { + await dispose() + } + }) + it('crash recovery: load preserves an interrupted (unclosed) turn and closes it with turn/end {interrupted}', async () => { const { persistence, dispose } = await make() try { diff --git a/packages/session-query/session-query-sqlite/src/schema.ts b/packages/session-query/session-query-sqlite/src/schema.ts index b88e04b536..47f6374ba6 100644 --- a/packages/session-query/session-query-sqlite/src/schema.ts +++ b/packages/session-query/session-query-sqlite/src/schema.ts @@ -5,7 +5,7 @@ import { mkdir, open } from 'node:fs/promises' import { dirname, resolve } from 'node:path' /** Current derived-index schema version. Incompatible versions reset in place. */ -export const SESSION_QUERY_SQLITE_SCHEMA_VERSION = 3 +export const SESSION_QUERY_SQLITE_SCHEMA_VERSION = 5 /** SQLite application id protecting unrelated databases from derived resets. */ export const SESSION_QUERY_SQLITE_APPLICATION_ID = 0x44534851 @@ -78,7 +78,7 @@ export async function openSearchDatabase(path: string, journalMode: JournalMode) function listUserTables(db: DatabaseSync): string[] { const rows = db.prepare( - "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", + "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT GLOB 'sqlite_*' ORDER BY name", ).all() as Array<{ name: string }> return rows.map(row => row.name) } diff --git a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts index d39c82f336..2fdd0b1e89 100644 --- a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts +++ b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts @@ -1186,6 +1186,26 @@ describe('SQLite schema, cancellation, and real persistence integration', () => expect(stillForeign.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' }) stillForeign.close() + const wildcardPath = await temporaryPath('sqlite-wildcard.db') + const wildcard = new DatabaseSync(wildcardPath) + wildcard.exec('PRAGMA journal_mode = WAL') + wildcard.exec('CREATE TABLE sqliteX(value TEXT)') + wildcard.exec("INSERT INTO sqliteX VALUES ('safe')") + wildcard.close() + const wildcardCtx = new Context() + await wildcardCtx.plugin(SessionStore) + await expect(wildcardCtx.plugin(SessionQuerySqlite, { + path: wildcardPath, + journalMode: 'delete', + })).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED')) + expect(wildcardCtx.sessionQuery).toBeUndefined() + const stillWildcard = new DatabaseSync(wildcardPath) + expect(stillWildcard.prepare('SELECT value FROM sqliteX').get()).toEqual({ value: 'safe' }) + expect(stillWildcard.prepare('PRAGMA application_id').get()).toEqual({ application_id: 0 }) + expect(stillWildcard.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 }) + expect(stillWildcard.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' }) + stillWildcard.close() + const otherAppPath = await temporaryPath('other-app.db') const otherApp = new DatabaseSync(otherAppPath) otherApp.exec('PRAGMA application_id = 123') diff --git a/packages/storage/README.md b/packages/storage/README.md new file mode 100644 index 0000000000..f112cdb5a0 --- /dev/null +++ b/packages/storage/README.md @@ -0,0 +1,12 @@ +# storage/ — non-session storage family + +The storage family persists everything that is not a session event log: a hub where named backends and typed data forms meet. Design record: [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md). + +| Package | Role | ctx key | +|---|---|---| +| `storage/` | The hub: named backend registry + merge-extensible data-form mounts, backend facet vocabulary, shared conformance suite | `ctx.storage` | +| `storage-json/` | JSON backend: one human-readable file per unit, atomic whole-file rewrite | registers backend `json` | +| `storage-sqlite/` | SQLite backend: one database hosting all routed units, document-per-row | registers backend `sqlite` | +| `domain/` | Domain data form: zod-validated records, per-domain write chain, `domain/changed` events, backend routing by configuration | mounts `ctx.storage.domain` | + +Backends own one medium each and expose data-shape **facets** (`kv` today; an append-log facet is reserved for the future session-backend migration). Consumers never touch backends directly — they open declared domains through the domain form. diff --git a/packages/storage/storage-domain/README.md b/packages/storage/storage-domain/README.md new file mode 100644 index 0000000000..e89c2f1d5b --- /dev/null +++ b/packages/storage/storage-domain/README.md @@ -0,0 +1,33 @@ +# @deepseek-ai/dsh-storage-domain + +Domain data form for the DeepSeek Harness storage hub: mounts `ctx.storage.domain`, opening schema-validated KV domains over configured storage backends. A domain is declared once with `defineDomain` (zod record schemas, `z.infer`-derived types), opened through `DomainFacility.open`, and served from authoritative in-memory state — reads are synchronous, writes serialize on one per-domain chain, reach durability on the routed backend first, then update memory and emit `domain/changed`. The opening consumer owns the handle's lifecycle and releases it with `Domain.close()` (idempotent; typically its own `ctx.effect` disposer); domains still open when the plugin unmounts are closed by the facility. + +Design rationale, open semantics, and the storage/domain layer split live in the [Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md). + +## Configuration + +| key | meaning | +| --- | --- | +| `backend` | Default backend name for every domain (required; no universally correct medium exists). | +| `routes` | Per-domain overrides: domain name → backend name. | + +## Model Experience + +### Durable domain state + +#### What the model sees + +Nothing. The package registers no tools, injects no prompts, and appends no session events; it stores non-session data (workspace records, future session sidecars) behind `ctx.storage.domain` and emits only the in-process `domain/changed` event, which reaches a model only if a consumer package renders it through its own documented surface. + +#### Token effect + +Zero. No text from this package enters any model request. + +#### KV Cache effect + +Independent: domain reads and writes never touch request prefixes, so nothing here can invalidate provider cache reuse. + +## Known Limitations and Deferred Work + +- **Single-process change visibility** — `domain/changed` is an in-process event; a second host process or a reconnecting GUI observes no changes until the cross-process revision pattern deferred in the Agent Note lands. +- **No cross-table transactions, secondary indexes, or multi-segment keys** — each write touches one record; triggers and rework points for these extensions are tabled in the Agent Note's deferred-work list. diff --git a/packages/storage/storage-domain/package.json b/packages/storage/storage-domain/package.json new file mode 100644 index 0000000000..1dffd143a9 --- /dev/null +++ b/packages/storage/storage-domain/package.json @@ -0,0 +1,43 @@ +{ + "name": "@deepseek-ai/dsh-storage-domain", + "description": "Domain data form (ctx.storage.domain): schema-validated, event-emitting KV domains over storage backends for the DeepSeek Harness", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-storage": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "dependencies": { + "schemastery": "^3.18.0", + "zod": "^4.4.3" + }, + "devDependencies": { + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-storage": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/storage/storage-domain/src/domain.ts b/packages/storage/storage-domain/src/domain.ts new file mode 100644 index 0000000000..7327580630 --- /dev/null +++ b/packages/storage/storage-domain/src/domain.ts @@ -0,0 +1,357 @@ +/** + * Runtime of one open domain: authoritative in-memory state, the single + * per-domain write chain, and change-event emission. Reads are synchronous + * from memory; every write queues on the chain, awaits backend durability + * FIRST, then mutates memory, then emits `domain/changed` — a rejected + * backend write leaves memory untouched (no divergence between reads and the + * medium), and events carry values that equal the in-memory state at + * emission, in write order. + * @module @deepseek-ai/dsh-storage-domain/src/domain + */ + +import type { Context } from 'cordis' +import type { KvUnit } from '@deepseek-ai/dsh-storage' +import { DomainError } from './error.ts' +import type { DomainSpec, DomainGlobalSpec, TableKeyOf, TableValueOf } from './spec.ts' +import type { DomainChanged } from './events.ts' + +/** Handle on a domain's global singleton. */ +export interface DomainGlobal<G> { + /** + * Current value, synchronously from the authoritative in-memory state. + * Before the first `set` this is the spec's `initial`. + * @returns the current global value. + */ + get(): G + + /** + * Replace the value durably. Queued on the domain's write chain; the first + * `set` is what materializes the global on the medium. + * @param value - New value; must satisfy the spec's schema (not re-checked + * here — validation happens at the durable read boundary). + * @returns resolution after durability and event emission. + */ + set(value: G): Promise<void> +} + +/** + * Handle on one declared table. Records are plain immutable data: returned + * values are the stored objects themselves (no defensive copies) and must not + * be mutated in place — replace via `put`/`update`. + */ +export interface KvTable<K extends string, V> { + /** + * Read one record, synchronously from memory. + * @param key - Record key. + * @returns the record, or `undefined` when absent. + */ + get(key: K): V | undefined + + /** + * Snapshot iterator over `[key, record]` pairs. A snapshot, not a live + * view: iteration stays stable while queued writes land. + * @returns the pair iterator. + */ + entries(): IterableIterator<[K, V]> + + /** + * Snapshot iterator over keys. + * @returns the key iterator. + */ + keys(): IterableIterator<K> + + /** Current record count. */ + readonly size: number + + /** + * Insert or overwrite one record durably. + * @param key - Record key. + * @param value - The full new record (no partial merge). + * @returns resolution after durability and event emission. + */ + put(key: K, value: V): Promise<void> + + /** + * Delete one record durably. + * @param key - Record key. + * @returns `true` when the record existed, `false` when it was already + * absent (no write and no event in that case). + */ + delete(key: K): Promise<boolean> + + /** + * Atomic read-modify-write on the domain's write chain: `fn` sees the + * value current at its queue slot, so concurrent updates never interleave. + * @param key - Record key; a missing key rejects with `missing-key`. + * @param fn - Synchronous pure transform from current to next record. + * @returns the stored next record. + */ + update(key: K, fn: (current: V) => V): Promise<V> +} + +/** Global handle of a spec: typed when declared, `never` (inaccessible) when not. */ +export type DomainGlobalHandleOf<S extends DomainSpec> = + S extends { readonly global: DomainGlobalSpec<infer G> } ? DomainGlobal<G> : never + +/** One open domain, typed by its spec. */ +export interface Domain<S extends DomainSpec> { + /** Domain name from the spec. */ + readonly name: string + /** Global singleton handle; a spec without `global` has no usable handle (`never`). */ + readonly global: DomainGlobalHandleOf<S> + /** + * Resolve one declared table handle. Handles are stable — repeated calls + * return the same instance. + * @param name - Declared table name. + * @returns the typed table handle. + */ + table<N extends keyof S['tables'] & string>(name: N): KvTable<TableKeyOf<S, N>, TableValueOf<S, N>> + + /** + * Close this domain: reject new writes immediately, drain already-queued + * writes (their events still emit), release the backend unit, then free + * the domain name for a later open. Idempotent — repeated calls share one + * teardown. The consumer owns this call (typically as its own `ctx.effect` + * disposer); the facility closes any domain left open when it unmounts. + * @returns resolution after the unit is released. + */ + close(): Promise<void> +} + +/** Internal seam handing table handles their domain-owned write machinery. */ +interface TableHost { + readonly domainName: string + readonly unit: KvUnit + /** Queue one job on the domain's single write chain. */ + enqueue<T>(job: () => Promise<T>): Promise<T> + /** Throw `closed` once the domain has fully closed (reads stay valid while draining). */ + assertReadable(): void + /** Emit `domain/changed` for one durably landed write. */ + emitChanged(change: DomainChanged): void +} + +const noop = () => {} + +/** + * The single domain implementation behind the {@link Domain} interface. The + * facility constructs it from a validated `loadAll` snapshot and erases it to + * `Domain<S>`; nothing outside this package constructs one. + */ +export class DomainImpl { + /** Domain name from the spec. */ + readonly name: string + + private readonly tables = new Map<string, KvTableImpl<string, unknown>>() + private globalValue: unknown + private readonly globalHandle?: DomainGlobal<unknown> + + /** Tail of the write chain; every link settles (rejections are observed by the caller's slice). */ + private chain: Promise<void> = Promise.resolve() + /** Set when close begins: new writes reject while already-queued writes drain. */ + private disposing = false + /** Set when close finishes (chain drained, unit closed): reads reject from here on. */ + private closed = false + private disposal?: Promise<void> + + /** + * @param ctx - Context that carries `domain/changed` emissions. + * @param spec - The domain declaration. + * @param unit - The opened backend unit; this instance owns its lifecycle. + * @param records - Validated records from the unit's `loadAll`, one entry + * per declared table (empty maps included) — the facility builds it from + * the spec, so the entry set IS the table set. + * @param globalValue - Validated stored global, or the spec's `initial` + * when the medium held none; `undefined` when the spec declares no global. + * @param onClosed - Facility hook run once after teardown completes; frees + * the domain name for a later open. + */ + constructor( + private readonly ctx: Context, + spec: DomainSpec, + private readonly unit: KvUnit, + records: Map<string, Map<string, unknown>>, + globalValue: unknown, + private readonly onClosed: () => void, + ) { + this.name = spec.name + const host: TableHost = { + domainName: spec.name, + unit, + enqueue: job => this.enqueue(job), + assertReadable: () => { this.assertReadable() }, + emitChanged: (change) => { this.emitChanged(change) }, + } + for (const [table, tableRecords] of records) { + this.tables.set(table, new KvTableImpl(host, table, tableRecords)) + } + if (spec.global !== undefined) { + this.globalValue = globalValue + this.globalHandle = { + get: () => { + this.assertReadable() + return this.globalValue + }, + set: value => this.enqueue(async () => { + await this.unit.setGlobal(value) + this.globalValue = value + this.emitChanged({ domain: this.name, table: '', key: '', operation: 'put', value }) + }), + } + } + } + + /** Global singleton handle; accessing it on a spec that declares no global is a caller bug and throws. */ + get global(): DomainGlobal<unknown> { + if (this.globalHandle === undefined) { + throw new Error(`domain '${this.name}' declares no global`) + } + return this.globalHandle + } + + /** + * Resolve one declared table handle; an undeclared name is a caller bug + * and throws. + * @param name - Declared table name. + * @returns the stable table handle. + */ + table(name: string): KvTable<string, unknown> { + const table = this.tables.get(name) + if (table === undefined) { + throw new Error(`domain '${this.name}' declares no table '${name}'`) + } + return table + } + + /** + * Close this domain: reject new writes immediately, drain already-queued + * writes (their events still emit), close the unit, then free the name via + * the facility hook. Idempotent — repeated calls share one teardown. + * @returns resolution after the unit is released. + */ + close(): Promise<void> { + this.disposal ??= this.runClose() + return this.disposal + } + + private async runClose(): Promise<void> { + this.disposing = true + // Chain links never reject (each is settled via then(noop, noop)), so + // this await is a pure drain barrier. + await this.chain + await this.unit.close() + this.closed = true + this.onClosed() + } + + /** + * Dispatch one post-durability change notification, containing observer + * failures: the write is already committed (medium and memory both hold + * the new state), so a throwing listener must not retroactively reject it. + */ + private emitChanged(change: DomainChanged): void { + try { + this.ctx.emit('domain/changed', change) + } catch (error) { + // Swallows synchronous observer exceptions only: emit dispatches + // listeners inline and nothing else runs in the try. The event is a + // notification, not a transaction participant — the commit point has + // passed, so containment (with a log) is the only correct outcome. + this.ctx.logger.warn(`domain '${this.name}': domain/changed listener failed: ${String(error)}`) + } + } + + private enqueue<T>(job: () => Promise<T>): Promise<T> { + if (this.disposing) { + return Promise.reject(new DomainError('closed', `domain '${this.name}' is closed`)) + } + const result = this.chain.then(job) + this.chain = result.then(noop, noop) + return result + } + + private assertReadable(): void { + if (this.closed) { + throw new DomainError('closed', `domain '${this.name}' is closed`) + } + } +} + +/** Table handle bound to one in-memory record map and its domain's write chain. */ +class KvTableImpl<K extends string, V> implements KvTable<K, V> { + constructor( + private readonly host: TableHost, + private readonly tableName: string, + private readonly records: Map<string, unknown>, + ) {} + + get(key: K): V | undefined { + this.host.assertReadable() + return this.records.get(key) as V | undefined + } + + entries(): IterableIterator<[K, V]> { + this.host.assertReadable() + return ([...this.records.entries()] as [K, V][])[Symbol.iterator]() + } + + keys(): IterableIterator<K> { + this.host.assertReadable() + return ([...this.records.keys()] as K[])[Symbol.iterator]() + } + + get size(): number { + this.host.assertReadable() + return this.records.size + } + + put(key: K, value: V): Promise<void> { + return this.host.enqueue(async () => { + await this.host.unit.putRecord(this.tableName, key, value) + this.records.set(key, value) + this.emitPut(key, value) + }) + } + + delete(key: K): Promise<boolean> { + return this.host.enqueue(async () => { + // Existence is decided at this job's chain slot, not at call time: an + // earlier queued put of the same key makes this delete observe it. + if (!this.records.has(key)) return false + await this.host.unit.deleteRecord(this.tableName, key) + this.records.delete(key) + this.host.emitChanged({ + domain: this.host.domainName, + table: this.tableName, + key, + operation: 'deleted', + }) + return true + }) + } + + update(key: K, fn: (current: V) => V): Promise<V> { + return this.host.enqueue(async () => { + if (!this.records.has(key)) { + throw new DomainError( + 'missing-key', + `domain '${this.host.domainName}' table '${this.tableName}' has no record '${key}' to update`, + ) + } + const next = fn(this.records.get(key) as V) + await this.host.unit.putRecord(this.tableName, key, next) + this.records.set(key, next) + this.emitPut(key, next) + return next + }) + } + + private emitPut(key: K, value: V): void { + this.host.emitChanged({ + domain: this.host.domainName, + table: this.tableName, + key, + operation: 'put', + value, + }) + } +} diff --git a/packages/storage/storage-domain/src/error.ts b/packages/storage/storage-domain/src/error.ts new file mode 100644 index 0000000000..b768c2af35 --- /dev/null +++ b/packages/storage/storage-domain/src/error.ts @@ -0,0 +1,53 @@ +/** + * Error vocabulary of the domain data form. + * @module @deepseek-ai/dsh-storage-domain/src/error + */ + +/** Discriminant codes carried by every {@link DomainError}. */ +export type DomainErrorCode = + | 'already-open' + | 'facet-unsupported' + | 'invalid-record' + | 'missing-key' + | 'closed' + +/** Location of the record that failed schema validation at the durable boundary. */ +export interface InvalidRecordDetail { + /** Table holding the rejected record; `''` for the global singleton. */ + readonly table: string + /** Key of the rejected record; `''` for the global singleton. */ + readonly key: string +} + +/** Construction options: standard `cause` plus the `invalid-record` location. */ +export interface DomainErrorOptions extends ErrorOptions { + /** Present exactly when `code` is `invalid-record`. */ + readonly detail?: InvalidRecordDetail +} + +/** + * Error thrown by the domain layer. The `code` is the stable contract + * consumers may switch on; `message` is diagnostic prose. Backend failures + * (`backend-not-found`, `version-mismatch`, …) pass through as + * `StorageError` — the domain layer does not rewrap them. + */ +export class DomainError extends Error { + override readonly name = 'DomainError' + + /** Present exactly when `code` is `invalid-record`. */ + readonly detail?: InvalidRecordDetail + + /** + * @param code - Stable discriminant for the failure class. + * @param message - Human-readable diagnostic detail. + * @param options - Standard error options plus the `invalid-record` location. + */ + constructor( + readonly code: DomainErrorCode, + message: string, + options?: DomainErrorOptions, + ) { + super(message, options) + if (options?.detail) this.detail = options.detail + } +} diff --git a/packages/storage/storage-domain/src/events.ts b/packages/storage/storage-domain/src/events.ts new file mode 100644 index 0000000000..f70095e5d5 --- /dev/null +++ b/packages/storage/storage-domain/src/events.ts @@ -0,0 +1,48 @@ +/** + * Change-event vocabulary of the domain data form. Every durable write emits + * one event after the backend resolves durability, carrying the new snapshot + * and an operation discriminant — never the old value (a diffing consumer + * keeps its own previous snapshot). This is the event source for cross-process + * change push (RPC frames) in a later phase. + * @module @deepseek-ai/dsh-storage-domain/src/events + */ + +/** Shared location fields of one durable domain change. */ +export interface DomainChangedBase { + /** Owning domain name. */ + readonly domain: string + /** Table name; `''` for a global-singleton write. */ + readonly table: string + /** Record key; `''` for a global-singleton write. */ + readonly key: string +} + +/** A record (or the global singleton) was inserted or overwritten. */ +export interface DomainChangedPut extends DomainChangedBase { + readonly operation: 'put' + /** The new snapshot. */ + readonly value: unknown +} + +/** A record was deleted; tombstones carry no value. */ +export interface DomainChangedDeleted extends DomainChangedBase { + readonly operation: 'deleted' + readonly value?: never +} + +/** One durable domain change; a closed union — switch on `operation`. */ +export type DomainChanged = DomainChangedPut | DomainChangedDeleted + +declare module 'cordis' { + interface Events { + /** + * A domain record or the global singleton changed, emitted once per write + * strictly after the backend acknowledged durability. Events of one + * domain arrive in its write-chain order. + * @param change - domain, table (`''` for global), key (`''` for global), + * operation discriminant, and on `put` the new snapshot. + * @mode emit + */ + 'domain/changed'(change: DomainChanged): void + } +} diff --git a/packages/storage/storage-domain/src/index.ts b/packages/storage/storage-domain/src/index.ts new file mode 100644 index 0000000000..974fcadc16 --- /dev/null +++ b/packages/storage/storage-domain/src/index.ts @@ -0,0 +1,203 @@ +/** + * Domain data form (`ctx.storage.domain`): schema-validated, change-emitting + * KV domains over storage backends. The single implementation of the domain + * layer — consumers depend on this package and never touch backends directly. + * Plugin `Config` is schemastery; record schemas inside domain specs are zod + * (see `src/spec.ts` for the split rationale). + * @module @deepseek-ai/dsh-storage-domain + */ + +import type { Context } from 'cordis' +import z from 'schemastery' +import { DomainError } from './error.ts' +import { descriptorOf } from './spec.ts' +import type { DomainSpec } from './spec.ts' +import { DomainImpl } from './domain.ts' +import type { Domain } from './domain.ts' + +export { DomainError } from './error.ts' +export type { DomainErrorCode, DomainErrorOptions, InvalidRecordDetail } from './error.ts' +export { defineDomain, domainTable, descriptorOf } from './spec.ts' +export type { + DomainSpec, DomainGlobalSpec, DomainTableSpec, + TableKeyOf, TableValueOf, GlobalValueOf, +} from './spec.ts' +export type { DomainChanged } from './events.ts' +export type { Domain, DomainGlobal, DomainGlobalHandleOf, KvTable } from './domain.ts' + +declare module '@deepseek-ai/dsh-storage' { + interface StorageForms { + domain: DomainFacility + } +} + +/** Cordis plugin name. */ +export const name = 'storage-domain' +/** The storage hub must be present before the form can mount. */ +export const inject = ['storage'] + +/** + * Plugin config. Which backend serves which domain is decided here, not + * globally on the hub: `backend` is the default route and `routes` overrides + * it per domain name. A route naming an unregistered backend fails loud at + * `open` with `backend-not-found`. + */ +export interface Config { + /** Default backend name for every domain without an explicit route. Required: there is no universally correct medium. */ + backend: string + /** Per-domain overrides: domain name → backend name. */ + routes?: Record<string, string> +} + +export const Config: z<Config> = z.object({ + backend: z.string().required(), + routes: z.dict(z.string()).default({}), +}) + +/** + * The mounted domain facility. Opens declared domains over routed backends; + * one facility instance owns the open-domain table and enforces single-open + * per domain name. + */ +export class DomainFacility { + private readonly domains = new Map<string, DomainImpl>() + /** Names reserved by an in-flight or completed open, so concurrent opens of one name fail loud. */ + private readonly reserved = new Set<string>() + + /** + * @param ctx - Context of the domain plugin; open-domain effects and change + * events attach here. + * @param config - Validated plugin config. + */ + constructor( + private readonly ctx: Context, + private readonly config: Config, + ) {} + + /** + * Open one declared domain. Steps, each failing the whole call: reject a + * name that is already open (`already-open`); resolve the backend route + * (`backend-not-found` passes through from the hub); require its `kv` facet + * (`facet-unsupported`); open the unit projected from the spec (backend + * `version-mismatch`/`malformed-medium` pass through); load and validate + * every stored record against the spec's zod schemas (`invalid-record` + * with the offending table and key); construct the domain. + * + * Lifecycle: the CALLER owns the returned handle and closes it via + * `Domain.close()` (typically as its own `ctx.effect` disposer) — the + * facility does not tie the domain to any consumer fiber. Domains still + * open when the facility unmounts are closed by the plugin disposer. + * @param spec - The domain declaration, typically from `defineDomain`. + * @returns the opened domain handle, typed by the spec. + */ + async open<S extends DomainSpec>(spec: S): Promise<Domain<S>> { + if (this.reserved.has(spec.name)) { + throw new DomainError('already-open', `domain '${spec.name}' is already open`) + } + this.reserved.add(spec.name) + try { + const backendName = this.config.routes?.[spec.name] ?? this.config.backend + const backend = this.ctx.storage.backend.get(backendName) + if (!backend.kv) { + throw new DomainError( + 'facet-unsupported', + `backend '${backendName}' routed for domain '${spec.name}' has no kv facet`, + ) + } + const unit = await backend.kv.open(descriptorOf(spec)) + try { + const snapshot = await unit.loadAll() + const tables = new Map<string, Map<string, unknown>>() + for (const [table, tableSpec] of Object.entries(spec.tables)) { + const records = new Map<string, unknown>() + for (const [key, raw] of Object.entries(snapshot.tables[table] ?? {})) { + records.set(key, parseRecord(spec.name, table, key, () => tableSpec.valueSchema.parse(raw))) + } + tables.set(table, records) + } + // A null stored global means "never written": serve `initial` without + // materializing it — the first `set` writes. + const globalSpec = spec.global + const globalValue = globalSpec === undefined + ? undefined + : snapshot.global === null + ? globalSpec.initial + : parseRecord(spec.name, '', '', () => globalSpec.schema.parse(snapshot.global)) + // The onClosed hook runs strictly after teardown completes: writes + // landing during the drain still emit domain/changed, and the domain + // stays resolvable (the package invariant cross-checks each event) + // until fully closed — only then does the name free up for reopening. + const domain: DomainImpl = new DomainImpl(this.ctx, spec, unit, tables, globalValue, () => { + this.domains.delete(spec.name) + this.reserved.delete(spec.name) + }) + this.domains.set(spec.name, domain) + // The single type-erasure point: DomainImpl is the untyped runtime, + // Domain<S> the spec-typed view; the unknown hop is required because + // S's conditional global-handle type stays unresolved here. + return domain as unknown as Domain<S> + } catch (error) { + await unit.close() + throw error + } + } catch (error) { + // Any failure means the domain never registered (nothing can throw + // after it), so releasing the name reservation is unconditional. + this.reserved.delete(spec.name) + throw error + } + } + + /** + * Look up an open domain by name, untyped. Diagnostic surface (the package + * invariant cross-checks change events against live domain state); typed + * consumers hold the handle returned by {@link open}. + * @param name - Domain name. + * @returns the open domain runtime, or `undefined` when not open. + */ + get(name: string): DomainImpl | undefined { + return this.domains.get(name) + } + + /** + * Close every domain still open on this facility. The unmount path for + * consumers that never called `Domain.close()` themselves; closing is + * idempotent, so double-closing an already-closed domain is harmless. + * @returns resolution after every unit is released. + */ + async closeAll(): Promise<void> { + await Promise.all([...this.domains.values()].map(domain => domain.close())) + } +} + +/** Run one zod parse, translating failure to `invalid-record` with its location. */ +function parseRecord<T>(domain: string, table: string, key: string, parse: () => T): T { + try { + return parse() + } catch (error) { + const slot = table === '' ? 'global' : `record '${key}' in table '${table}'` + throw new DomainError( + 'invalid-record', + `domain '${domain}': stored ${slot} does not match its schema`, + { detail: { table, key }, cause: error }, + ) + } +} + +/** + * Mount the domain data form on the storage hub. + * @param ctx - Plugin context. + * @param config - Validated plugin config. + */ +export function apply(ctx: Context, config: Config) { + const facility = new DomainFacility(ctx, config) + ctx.effect(() => { + const unmount = ctx.storage.mount('domain', facility) + return async () => { + // Close leftovers before unmounting: draining writes still emit + // domain/changed, whose invariant resolves the facility through the hub. + await facility.closeAll() + unmount() + } + }) +} diff --git a/packages/storage/storage-domain/src/invariant.ts b/packages/storage/storage-domain/src/invariant.ts new file mode 100644 index 0000000000..b2da8bebe4 --- /dev/null +++ b/packages/storage/storage-domain/src/invariant.ts @@ -0,0 +1,67 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-storage-domain`: every + * `domain/changed` event must agree with the emitting domain's authoritative + * in-memory state (the owned event-stream ↔ mutable-data relationship of this + * package). Writes emit strictly after mutating memory and the write chain + * serializes them, so at emission time the event's snapshot equals the + * current read — any divergence means a write path skipped the chain or + * emitted a stale value. + * @module @deepseek-ai/dsh-storage-domain/invariant + */ + +import type { Context } from 'cordis' +import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants' +import type { DomainChanged } from './events.ts' + +const PACKAGE_NAME = '@deepseek-ai/dsh-storage-domain' + +/** Cordis companion plugin name. */ +export const name = 'storage-domain-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** Install the change-event ↔ memory-state agreement check. */ +const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => { + ctx.on('domain/changed', (change: DomainChanged) => { + const domain = ctx.storage.form('domain').get(change.domain) + if (domain === undefined) { + return fail(`domain/changed for '${change.domain}' emitted while that domain is not open`) + } + if (change.table === '') { + // Global write: the event snapshot must be the current global value. + if (domain.global.get() !== change.value) { + return fail(`domain/changed global value for '${change.domain}' differs from the in-memory global`) + } + return + } + const current = domain.table(change.table).get(change.key) + switch (change.operation) { + case 'deleted': + if (current !== undefined) { + return fail( + `domain/changed deletion of '${change.domain}'.'${change.table}'['${change.key}'] ` + + 'emitted while the record is still in memory', + ) + } + return + case 'put': + if (current !== change.value) { + return fail( + `domain/changed value for '${change.domain}'.'${change.table}'['${change.key}'] ` + + 'differs from the in-memory record', + ) + } + return + default: + change satisfies never + } + }, { global: true }) +}, { inject: ['storage'] }) + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) diff --git a/packages/storage/storage-domain/src/spec.ts b/packages/storage/storage-domain/src/spec.ts new file mode 100644 index 0000000000..9e49ef41e3 --- /dev/null +++ b/packages/storage/storage-domain/src/spec.ts @@ -0,0 +1,112 @@ +/** + * Domain declaration vocabulary. A spec object is the single source of a + * domain's identity, layout, and record schemas: the owning package defines + * it once with {@link defineDomain} and both the type surface and the runtime + * (validation, descriptor projection) derive from it. Record schemas are zod + * (`z.infer` keeps types un-duplicated and the same schemas later project to + * RPC wire schemas); plugin `Config` stays schemastery. + * @module @deepseek-ai/dsh-storage-domain/src/spec + */ + +import type { ZodType } from 'zod' +import { UNIT_NAME_RE, type KvUnitDescriptor } from '@deepseek-ai/dsh-storage' + +/** Global singleton declaration: schema plus the value used before the first write. */ +export interface DomainGlobalSpec<G> { + /** Validates the stored global at the durable boundary. */ + readonly schema: ZodType<G> + /** Value served when the medium holds no global yet; not written until the first `set`. */ + readonly initial: G +} + +/** + * One table declaration. `K` is a phantom key type (typically a branded + * string) carried for compile-time projection only; keys are plain strings on + * the medium. + */ +export interface DomainTableSpec<K extends string = string, V = unknown> { + /** Validates every stored record at the durable boundary. */ + readonly valueSchema: ZodType<V> + /** Phantom carrier for the key type; never present at runtime. */ + readonly __key?: K +} + +/** Static declaration of one domain: identity, version, and record layout. */ +export interface DomainSpec { + /** Domain name; must match `UNIT_NAME_RE` (doubles as the backend unit name). */ + readonly name: string + /** Domain format version; a medium stamped with a different version rejects at open. */ + readonly version: number + /** Optional global singleton slot. */ + readonly global?: DomainGlobalSpec<unknown> + /** Table declarations keyed by table name; each name must match `UNIT_NAME_RE`. */ + readonly tables: Record<string, DomainTableSpec> +} + +/** Key type of one declared table, recovered from its phantom carrier. */ +export type TableKeyOf<S extends DomainSpec, N extends keyof S['tables']> = + S['tables'][N] extends DomainTableSpec<infer K> ? K : never + +/** Value type of one declared table. */ +export type TableValueOf<S extends DomainSpec, N extends keyof S['tables']> = + S['tables'][N] extends DomainTableSpec<string, infer V> ? V : never + +/** Global value type of a spec; `never` when the spec declares no global. */ +export type GlobalValueOf<S extends DomainSpec> = + S['global'] extends DomainGlobalSpec<infer G> ? G : never + +/** + * Declare one table. + * @param schema - zod schema validating every stored record of this table. + * @returns the table declaration, key-typed by `K`. + */ +export function domainTable<K extends string, V>(schema: ZodType<V>): DomainTableSpec<K, V> { + return { valueSchema: schema } +} + +/** + * Identity helper that pins a spec's literal types and validates its shape. + * Misconfiguration fails loud at the owning package's module load, before any + * medium is touched: a domain or table name outside `UNIT_NAME_RE`, a version + * that is not a non-negative integer, or a global schema that accepts `null` + * all throw. The `null` rejection guards round-tripping: backends store the + * global as opaque JSON with `null` as the "never written" sentinel, so a + * nullable global would be indistinguishable from an absent one on reopen + * (a stored `null` silently reverts to `initial`). + * @param spec - The domain declaration. + * @returns the same spec, narrowed to its literal type. + */ +export function defineDomain<S extends DomainSpec>(spec: S): S { + if (!UNIT_NAME_RE.test(spec.name)) { + throw new Error(`domain name '${spec.name}' must match ${UNIT_NAME_RE}`) + } + if (!Number.isInteger(spec.version) || spec.version < 0) { + throw new Error(`domain '${spec.name}' version must be a non-negative integer, got ${spec.version}`) + } + for (const table of Object.keys(spec.tables)) { + if (!UNIT_NAME_RE.test(table)) { + throw new Error(`domain '${spec.name}' table name '${table}' must match ${UNIT_NAME_RE}`) + } + } + if (spec.global !== undefined && spec.global.schema.safeParse(null).success) { + throw new Error( + `domain '${spec.name}' global schema must not accept null: ` + + 'null is the medium\'s "never written" sentinel, so a stored null could not round-trip', + ) + } + return spec +} + +/** + * Project a spec onto the backend-facing unit descriptor. + * @param spec - The domain declaration. + * @returns the descriptor handed to `KvFacet.open`. + */ +export function descriptorOf(spec: DomainSpec): KvUnitDescriptor { + return { + name: spec.name, + version: spec.version, + tables: Object.keys(spec.tables), + hasGlobal: spec.global !== undefined, + } +} diff --git a/packages/storage/storage-domain/tests/domain.spec.ts b/packages/storage/storage-domain/tests/domain.spec.ts new file mode 100644 index 0000000000..8d02cd50e5 --- /dev/null +++ b/packages/storage/storage-domain/tests/domain.spec.ts @@ -0,0 +1,326 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { z } from 'zod' +import Storage from '@deepseek-ai/dsh-storage' +import { DomainFacility, defineDomain, domainTable } from '../src/index.ts' +import type { Config } from '../src/index.ts' +import type { DomainChanged } from '../src/events.ts' +import { MemoryMediaPool, MemoryStorageBackend } from './helpers/memory-backend.ts' + +const itemSchema = z.object({ label: z.string(), count: z.number().int() }) +type Item = z.infer<typeof itemSchema> + +const settingsSchema = z.object({ theme: z.string() }) + +const spec = defineDomain({ + name: 'demo', + version: 1, + global: { schema: settingsSchema, initial: { theme: 'plain' } }, + tables: { items: domainTable<string, Item>(itemSchema) }, +}) + +const bareSpec = defineDomain({ + name: 'bare', + version: 1, + tables: { rows: domainTable<string, Item>(itemSchema) }, +}) + +/** Boot a context with the storage hub, one memory backend, and a facility over it. */ +async function harness(options?: { pool?: MemoryMediaPool; config?: Partial<Config> }) { + const ctx = new Context() + await ctx.plugin(Storage) + const backend = new MemoryStorageBackend(options?.pool) + ctx.storage.backend.register('memory', backend) + const facility = new DomainFacility(ctx, { backend: 'memory', routes: {}, ...options?.config }) + // Mounted, not just constructed: the package invariant resolves the form + // through ctx.storage to cross-check every domain/changed emission. + ctx.storage.mount('domain', facility) + const changes: DomainChanged[] = [] + ctx.on('domain/changed', (change) => { changes.push(change) }) + return { ctx, backend, facility, changes } +} + +describe('defineDomain', () => { + it('rejects invalid names and versions loudly', () => { + expect(() => defineDomain({ name: 'Bad-Name', version: 1, tables: {} })).toThrow(/must match/) + expect(() => defineDomain({ name: 'ok', version: 1.5, tables: {} })).toThrow(/non-negative integer/) + expect(() => defineDomain({ + name: 'ok', version: 1, tables: { 'Bad Table': domainTable<string, Item>(itemSchema) }, + })).toThrow(/table name/) + }) + + it('rejects a global schema that accepts null (the never-written sentinel)', () => { + expect(() => defineDomain({ + name: 'ok', + version: 1, + global: { schema: settingsSchema.nullable(), initial: null }, + tables: {}, + })).toThrow(/must not accept null/) + }) +}) + +describe('DomainFacility.open', () => { + it('opens, reads back stored records, and rejects a second open of the same name', async () => { + const { facility } = await harness() + const domain = await facility.open(spec) + await domain.table('items').put('a', { label: 'first', count: 1 }) + await expect(facility.open(spec)).rejects.toMatchObject({ name: 'DomainError', code: 'already-open' }) + expect(domain.table('items').get('a')).toEqual({ label: 'first', count: 1 }) + }) + + it('routes per domain name and fails loud on an unregistered route target', async () => { + const { facility } = await harness({ config: { routes: { demo: 'nonexistent' } } }) + await expect(facility.open(spec)).rejects.toMatchObject({ + name: 'StorageError', + code: 'backend-not-found', + }) + // The failed open releases the name for a later attempt. + const { facility: healthy } = await harness() + await expect(healthy.open(spec)).resolves.toBeDefined() + }) + + it('rejects a backend without the kv facet', async () => { + const { ctx, facility } = await harness({ config: { backend: 'nokv' } }) + ctx.storage.backend.register('nokv', { close: async () => {} }) + await expect(facility.open(spec)).rejects.toMatchObject({ code: 'facet-unsupported' }) + }) + + it('falls back to the default backend when no route table is configured', async () => { + // A second, unmounted facility whose config omits `routes` entirely + // (exactOptionalPropertyTypes forbids an explicit undefined). Opening + // emits no events, so the mounted facility's invariant never consults it. + const { ctx } = await harness() + const routeless = new DomainFacility(ctx, { backend: 'memory' }) + await expect(routeless.open(bareSpec)).resolves.toBeDefined() + }) + + it('treats a table key the backend omitted from loadAll as empty', async () => { + // A sparse backend: loadAll omits declared table keys entirely instead of + // returning them as empty objects. + const { ctx, facility } = await harness({ config: { backend: 'sparse' } }) + ctx.storage.backend.register('sparse', { + kv: { + open: async () => ({ + loadAll: async () => ({ tables: {}, global: null }), + putRecord: async () => {}, + deleteRecord: async () => {}, + setGlobal: async () => {}, + close: async () => {}, + }), + }, + close: async () => {}, + }) + const domain = await facility.open(bareSpec) + expect(domain.table('rows').size).toBe(0) + }) + + it('rejects stored records that fail their schema, naming table and key', async () => { + const pool = new MemoryMediaPool() + { + const { facility } = await harness({ pool }) + await (await facility.open(spec)).table('items').put('bad', { label: 'x', count: 2 }) + } + pool.media.get('demo')!.tables.get('items')!.set('bad', { label: 'x', count: 'NaN' }) + const { facility } = await harness({ pool }) + await expect(facility.open(spec)).rejects.toMatchObject({ + code: 'invalid-record', + detail: { table: 'items', key: 'bad' }, + }) + }) + + it('rejects a stored global that fails its schema with the global marker', async () => { + const pool = new MemoryMediaPool() + pool.versions.set('demo', 1) + pool.media.set('demo', { tables: new Map(), global: { theme: 42 } }) + const { facility } = await harness({ pool }) + await expect(facility.open(spec)).rejects.toMatchObject({ + code: 'invalid-record', + detail: { table: '', key: '' }, + }) + }) + + it('passes through a backend version mismatch', async () => { + const pool = new MemoryMediaPool() + pool.versions.set('demo', 7) + const { facility } = await harness({ pool }) + await expect(facility.open(spec)).rejects.toMatchObject({ + name: 'StorageError', + code: 'version-mismatch', + }) + }) +}) + +describe('plugin apply', () => { + it('mounts the facility as ctx.storage.domain through the plugin effect', async () => { + const ctx = new Context() + await ctx.plugin(Storage) + ctx.storage.backend.register('memory', new MemoryStorageBackend()) + const DomainPlugin = await import('../src/index.ts') + const fiber = await ctx.plugin(DomainPlugin, { backend: 'memory' }) + expect(ctx.storage.domain).toBeInstanceOf(DomainFacility) + await fiber.dispose() + expect(() => ctx.storage.form('domain')).toThrow(/not mounted/) + }) +}) + +describe('table and snapshot reads', () => { + it('serves entries, keys, and size as stable snapshots; unknown table names throw', async () => { + const { facility } = await harness() + const domain = await facility.open(spec) + const table = domain.table('items') + await table.put('a', { label: 'x', count: 1 }) + await table.put('b', { label: 'y', count: 2 }) + expect(table.size).toBe(2) + expect([...table.keys()].sort()).toEqual(['a', 'b']) + expect(new Map(table.entries()).get('a')).toEqual({ label: 'x', count: 1 }) + expect(() => domain.table('nope' as never)).toThrow(/declares no table/) + }) +}) + +describe('KvTable writes', () => { + it('serializes concurrent updates on one key without losing increments', async () => { + const { facility } = await harness() + const table = (await facility.open(spec)).table('items') + await table.put('counter', { label: 'c', count: 0 }) + await Promise.all(Array.from({ length: 50 }, () => + table.update('counter', current => ({ ...current, count: current.count + 1 })))) + expect(table.get('counter')).toEqual({ label: 'c', count: 50 }) + }) + + it('update rejects a missing key; delete reports prior existence', async () => { + const { facility } = await harness() + const table = (await facility.open(spec)).table('items') + await expect(table.update('ghost', v => v)).rejects.toMatchObject({ code: 'missing-key' }) + await table.put('a', { label: 'x', count: 1 }) + await expect(table.delete('a')).resolves.toBe(true) + await expect(table.delete('a')).resolves.toBe(false) + }) + + it('emits domain/changed per durable write, in order, with tombstones and global marker', async () => { + const { facility, changes } = await harness() + const domain = await facility.open(spec) + const table = domain.table('items') + await table.put('a', { label: 'x', count: 1 }) + await table.update('a', current => ({ ...current, count: 2 })) + await table.delete('a') + await table.delete('a') // no event: already absent + await domain.global.set({ theme: 'dark' }) + expect(changes).toEqual([ + { domain: 'demo', table: 'items', key: 'a', operation: 'put', value: { label: 'x', count: 1 } }, + { domain: 'demo', table: 'items', key: 'a', operation: 'put', value: { label: 'x', count: 2 } }, + { domain: 'demo', table: 'items', key: 'a', operation: 'deleted' }, + { domain: 'demo', table: '', key: '', operation: 'put', value: { theme: 'dark' } }, + ]) + }) +}) + +describe('durability failure', () => { + it('leaves memory untouched and emits nothing when the backend rejects a write', async () => { + const pool = new MemoryMediaPool() + const { facility, changes } = await harness({ pool }) + const domain = await facility.open(spec) + const table = domain.table('items') + await table.put('a', { label: 'x', count: 1 }) + const seen = changes.length + + pool.failNextWrites = 3 + await expect(table.put('a', { label: 'x', count: 99 })).rejects.toThrow(/injected/) + await expect(table.update('a', c => ({ ...c, count: c.count + 1 }))).rejects.toThrow(/injected/) + await expect(table.delete('a')).rejects.toThrow(/injected/) + + // Reads still serve the pre-failure record; no events leaked. + expect(table.get('a')).toEqual({ label: 'x', count: 1 }) + expect(pool.media.get('demo')!.tables.get('items')!.get('a')).toEqual({ label: 'x', count: 1 }) + expect(changes).toHaveLength(seen) + + // The chain survives rejections: the next write lands cleanly with no residue. + await table.update('a', c => ({ ...c, count: c.count + 1 })) + expect(table.get('a')).toEqual({ label: 'x', count: 2 }) + }) + + it('keeps serving initial when the first global set fails durability', async () => { + const pool = new MemoryMediaPool() + const { facility } = await harness({ pool }) + const domain = await facility.open(spec) + pool.failNextWrites = 1 + await expect(domain.global.set({ theme: 'dark' })).rejects.toThrow(/injected/) + expect(domain.global.get()).toEqual({ theme: 'plain' }) + expect(pool.media.get('demo')!.global).toBeNull() + }) +}) + +describe('global singleton', () => { + it('serves initial before first set without materializing, then persists the first set', async () => { + const pool = new MemoryMediaPool() + { + const { facility } = await harness({ pool }) + const domain = await facility.open(spec) + expect(domain.global.get()).toEqual({ theme: 'plain' }) + expect(pool.media.get('demo')!.global).toBeNull() // initial never touches the medium + await domain.global.set({ theme: 'dark' }) + expect(pool.media.get('demo')!.global).toEqual({ theme: 'dark' }) + } + const { facility } = await harness({ pool }) + expect((await facility.open(spec)).global.get()).toEqual({ theme: 'dark' }) + }) + + it('throws on access when the spec declares no global', async () => { + const { facility } = await harness() + const domain = await facility.open(bareSpec) + expect(() => (domain as { global: unknown }).global).toThrow(/declares no global/) + }) +}) + +describe('close and lifecycle', () => { + it('close drains queued writes, then rejects reads and writes, and frees the name', async () => { + const pool = new MemoryMediaPool() + const { facility } = await harness({ pool }) + const domain = await facility.open(spec) + const table = domain.table('items') + const pending = Promise.all([ + table.put('a', { label: 'x', count: 1 }), + table.put('b', { label: 'y', count: 2 }), + ]) + await Promise.all([domain.close(), domain.close()]) // idempotent + await pending // queued before close → still landed + // Durability is the drain contract: both queued writes reached the medium. + expect([...pool.media.get('demo')!.tables.get('items')!.keys()].sort()).toEqual(['a', 'b']) + await expect(table.put('c', { label: 'z', count: 3 })).rejects.toMatchObject({ code: 'closed' }) + expect(() => table.get('a')).toThrow(/closed/) + // The name is free again: reopening sees the drained state. + const reopened = await facility.open(spec) + expect([...reopened.table('items').keys()].sort()).toEqual(['a', 'b']) + }) + + it('facility unmount closes domains the consumer never closed', async () => { + const ctx = new Context() + await ctx.plugin(Storage) + ctx.storage.backend.register('memory', new MemoryStorageBackend()) + const DomainPlugin = await import('../src/index.ts') + const fiber = await ctx.plugin(DomainPlugin, { backend: 'memory' }) + const domain = await ctx.storage.domain.open(bareSpec) + const table = domain.table('rows') + await table.put('a', { label: 'x', count: 1 }) + await fiber.dispose() + await expect(table.put('b', { label: 'y', count: 2 })).rejects.toMatchObject({ code: 'closed' }) + expect(() => ctx.storage.form('domain')).toThrow(/not mounted/) + }) + + it('contains a throwing domain/changed listener without rejecting the committed write', async () => { + const pool = new MemoryMediaPool() + const { ctx, facility, changes } = await harness({ pool }) + const domain = await facility.open(spec) + const table = domain.table('items') + ctx.on('domain/changed', () => { + throw new Error('hostile observer') + }) + await expect(table.put('a', { label: 'x', count: 1 })).resolves.toBeUndefined() + // Commit survived intact on both planes, and well-behaved listeners + // (registered before the thrower) still observed the event. + expect(table.get('a')).toEqual({ label: 'x', count: 1 }) + expect(pool.media.get('demo')!.tables.get('items')!.get('a')).toEqual({ label: 'x', count: 1 }) + expect(changes).toHaveLength(1) + // The chain is unpoisoned: subsequent writes proceed normally. + await expect(table.delete('a')).resolves.toBe(true) + }) +}) diff --git a/packages/storage/storage-domain/tests/helpers/memory-backend.ts b/packages/storage/storage-domain/tests/helpers/memory-backend.ts new file mode 100644 index 0000000000..1eb1bffe2d --- /dev/null +++ b/packages/storage/storage-domain/tests/helpers/memory-backend.ts @@ -0,0 +1,160 @@ +/** + * In-memory {@link StorageBackend} test double implementing the full KvUnit + * primitive set. Shared test infrastructure: the domain suite uses it to + * exercise open/route/write semantics without touching disk, and the + * workspace package's tests import it by relative path (it lives under + * `tests/`, never `src/`, so it stays out of the published surface). + * + * Fidelity to the backend contract (`dsh-storage` `src/backend.ts`): version + * stamping and `version-mismatch` on reopen, `malformed` never (memory cannot + * corrupt), per-call atomicity trivially, `closed` after close, delete + * idempotence. Media survive across backends through the shared `media` map + * passed into the constructor, which simulates process restarts; stamp + * `versions` directly to fabricate an on-medium version and force a + * `version-mismatch` without a prior open. + * @module + */ + +import { StorageError } from '@deepseek-ai/dsh-storage' +import type { KvFacet, KvUnit, KvUnitDescriptor, StorageBackend } from '@deepseek-ai/dsh-storage' + +/** One unit's medium: tables of records plus the global slot (`null` = never written). */ +export interface MemoryMedium { + tables: Map<string, Map<string, unknown>> + global: unknown +} + +/** + * Shared media pool. Construct one and hand it to several + * {@link MemoryStorageBackend} instances to simulate reopening the same + * medium after a restart; `versions` holds the stamped unit versions and is + * writable by tests to inject a mismatching on-medium version, and + * `failNextWrites` injects write-primitive failures. + */ +export class MemoryMediaPool { + /** Unit name → its records; a missing entry is a never-materialized unit. */ + readonly media = new Map<string, MemoryMedium>() + /** Unit name → stamped version; tests may pre-stamp to force `version-mismatch`. */ + readonly versions = new Map<string, number>() + /** + * When positive, that many subsequent write primitives (putRecord / + * deleteRecord / setGlobal) reject without touching the medium, decrementing + * per rejection. Negative-path seam: callers assert their state is + * untouched after a durability failure. + */ + failNextWrites = 0 + + /** Consume one injected failure, throwing in a rejected write's place. */ + consumeInjectedFailure(): void { + if (this.failNextWrites > 0) { + this.failNextWrites -= 1 + throw new Error('injected write failure') + } + } +} + +/** In-memory KV unit over one pooled medium. */ +class MemoryKvUnit implements KvUnit { + private closed = false + + constructor( + private readonly pool: MemoryMediaPool, + private readonly medium: MemoryMedium, + private readonly descriptor: KvUnitDescriptor, + private readonly onClose: () => void, + ) {} + + private assertOpen(): void { + if (this.closed) { + throw new StorageError('closed', `memory unit '${this.descriptor.name}' is closed`) + } + } + + async loadAll(): Promise<{ tables: Record<string, Record<string, unknown>>; global: unknown }> { + this.assertOpen() + const tables: Record<string, Record<string, unknown>> = {} + for (const table of this.descriptor.tables) { + tables[table] = Object.fromEntries(this.medium.tables.get(table) ?? []) + } + return { tables, global: this.medium.global } + } + + async putRecord(table: string, key: string, value: unknown): Promise<void> { + this.assertOpen() + this.pool.consumeInjectedFailure() + let records = this.medium.tables.get(table) + if (records === undefined) { + records = new Map() + this.medium.tables.set(table, records) + } + records.set(key, value) + } + + async deleteRecord(table: string, key: string): Promise<void> { + this.assertOpen() + this.pool.consumeInjectedFailure() + this.medium.tables.get(table)?.delete(key) + } + + async setGlobal(value: unknown): Promise<void> { + this.assertOpen() + this.pool.consumeInjectedFailure() + this.medium.global = value + } + + async close(): Promise<void> { + if (this.closed) return + this.closed = true + this.onClose() + } +} + +/** + * In-memory storage backend with a `kv` facet. Pass a shared + * {@link MemoryMediaPool} to let a second instance reopen the same media; + * omit it for a throwaway isolated pool. + */ +export class MemoryStorageBackend implements StorageBackend { + readonly kv: KvFacet + private readonly openUnits = new Set<string>() + private closed = false + + /** + * @param pool - Media shared across instances; a fresh private pool when omitted. + */ + constructor(readonly pool: MemoryMediaPool = new MemoryMediaPool()) { + this.kv = { + open: async (descriptor: KvUnitDescriptor): Promise<KvUnit> => { + if (this.closed) { + throw new StorageError('closed', 'memory backend is closed') + } + // Double-open is a caller bug per the backend contract; no dedicated + // StorageError code exists for it, so a plain Error is correct. + if (this.openUnits.has(descriptor.name)) { + throw new Error(`memory unit '${descriptor.name}' is already open (double-open is a caller bug)`) + } + const stamped = this.pool.versions.get(descriptor.name) + if (stamped === undefined) { + this.pool.versions.set(descriptor.name, descriptor.version) + } else if (stamped !== descriptor.version) { + throw new StorageError( + 'version-mismatch', + `memory unit '${descriptor.name}' is stamped v${stamped}, descriptor wants v${descriptor.version}`, + ) + } + let medium = this.pool.media.get(descriptor.name) + if (medium === undefined) { + medium = { tables: new Map(), global: null } + this.pool.media.set(descriptor.name, medium) + } + this.openUnits.add(descriptor.name) + return new MemoryKvUnit(this.pool, medium, descriptor, () => this.openUnits.delete(descriptor.name)) + }, + } + } + + async close(): Promise<void> { + this.closed = true + this.openUnits.clear() + } +} diff --git a/packages/storage/storage-domain/tests/invariant.spec.ts b/packages/storage/storage-domain/tests/invariant.spec.ts new file mode 100644 index 0000000000..80c7264aae --- /dev/null +++ b/packages/storage/storage-domain/tests/invariant.spec.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { z } from 'zod' +import Storage from '@deepseek-ai/dsh-storage' +import InvariantService, { InvariantError } from '@deepseek-ai/dsh-invariants' +import * as DomainInvariantCompanion from '@deepseek-ai/dsh-storage-domain/invariant' +import { DomainFacility, defineDomain, domainTable } from '../src/index.ts' +import type { DomainChanged } from '../src/events.ts' +import { MemoryStorageBackend } from './helpers/memory-backend.ts' + +const itemSchema = z.object({ n: z.number() }) +type Item = z.infer<typeof itemSchema> + +const spec = defineDomain({ + name: 'inv', + version: 1, + global: { schema: itemSchema, initial: { n: 0 } }, + tables: { rows: domainTable<string, Item>(itemSchema) }, +}) + +async function setup() { + const ctx = new Context() + await ctx.plugin(Storage) + await ctx.plugin(InvariantService, { enabled: true }) + await ctx.plugin(DomainInvariantCompanion) + ctx.storage.backend.register('memory', new MemoryStorageBackend()) + const facility = new DomainFacility(ctx, { backend: 'memory', routes: {} }) + ctx.storage.mount('domain', facility) + return { ctx, facility } +} + +const invariantViolation: unknown = expect.objectContaining<Partial<InvariantError>>({ + code: 'INVARIANT', + packageName: '@deepseek-ai/dsh-storage-domain', +}) + +describe('domain change-event invariants', () => { + it('accepts every write shape emitted by the real write paths', async () => { + const { facility } = await setup() + const domain = await facility.open(spec) + const rows = domain.table('rows') + await rows.put('a', { n: 1 }) + await rows.update('a', current => ({ n: current.n + 1 })) + await expect(rows.delete('a')).resolves.toBe(true) + await domain.global.set({ n: 5 }) + }) + + it('rejects an event for a domain that is not open', async () => { + const { ctx } = await setup() + expect(() => { ctx.emit('domain/changed', { + domain: 'ghost', table: 'rows', key: 'a', operation: 'put', value: { n: 1 }, + }) }).toThrow(invariantViolation) + }) + + it('rejects a put event whose value is not the in-memory record', async () => { + const { ctx, facility } = await setup() + const domain = await facility.open(spec) + await domain.table('rows').put('a', { n: 1 }) + expect(() => { ctx.emit('domain/changed', { + domain: 'inv', table: 'rows', key: 'a', operation: 'put', value: { n: 999 }, + }) }).toThrow(invariantViolation) + }) + + it('rejects a deletion event while the record is still in memory', async () => { + const { ctx, facility } = await setup() + const domain = await facility.open(spec) + await domain.table('rows').put('a', { n: 1 }) + expect(() => { ctx.emit('domain/changed', { + domain: 'inv', table: 'rows', key: 'a', operation: 'deleted', + }) }).toThrow(invariantViolation) + }) + + it('rejects a global event whose value is not the in-memory global', async () => { + const { ctx, facility } = await setup() + await facility.open(spec) + expect(() => { ctx.emit('domain/changed', { + domain: 'inv', table: '', key: '', operation: 'put', value: { n: 42 }, + }) }).toThrow(invariantViolation) + }) + + it('tolerates operations outside the closed union without failing falsely', async () => { + const { ctx, facility } = await setup() + const domain = await facility.open(spec) + await domain.table('rows').put('a', { n: 1 }) + // Merge-hostile input: the closed union's satisfies-never default arm is + // unreachable in typed code; an untyped emit must not crash the check. + expect(() => { ctx.emit('domain/changed', { + domain: 'inv', table: 'rows', key: 'a', operation: 'exotic', + } as unknown as DomainChanged) }).not.toThrow() + }) +}) diff --git a/packages/storage/storage-domain/tsconfig.json b/packages/storage/storage-domain/tsconfig.json new file mode 100644 index 0000000000..5a13b64de8 --- /dev/null +++ b/packages/storage/storage-domain/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../storage" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/storage/storage-json/README.md b/packages/storage/storage-json/README.md new file mode 100644 index 0000000000..5cf0fc9d61 --- /dev/null +++ b/packages/storage/storage-json/README.md @@ -0,0 +1,36 @@ +# @deepseek-ai/dsh-storage-json + +JSON backend for the [storage hub](../storage/README.md): one human-readable `<unit>.json` file per unit under a configured root, registered as backend `json`. Design: [domain KV storage Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md). + +## Model + +- The in-memory unit state is authoritative; every write primitive republishes the whole file via temp-write + fsync + atomic `rename()` replace. A unit file is always the complete current net state — legibility is this backend's reason to exist; scale is the SQLite backend's job. +- A missing file opens as an empty unit and materializes on the first write. A foreign or unparsable file rejects with `malformed-medium`; a stored version differing from the descriptor rejects with `version-mismatch` (no migration, pre-release stance). +- Write ordering across calls belongs to the caller (the domain layer's write chain); each single call is atomic and durable once resolved. + +## Config + +| Key | Type | Default | Meaning | +| --- | --- | --- | --- | +| `root` | string | required — no default (a cwd fallback would scatter files) | Directory holding unit files; created `0o700` on demand | + +## Model Experience + +### Stored domain records + +#### What the model sees + +Nothing. This backend contributes no prompt, tool, or schema; it persists non-session domain data behind `ctx.storage` for host-side consumers only. + +#### Token effect + +Zero live-request tokens. + +#### KV Cache effect + +None — the backend never touches live request prefixes. + +## Known Limitations and Deferred Work + +- Windows durability relies on libuv's `rename()` (`MoveFileExW` with replacement) without an explicit write-through flag; the session-log backend's stricter Win32 write-through publish helper is planned to move down here when the append-log facet lands (see the Agent Note's migration section). +- No cross-process write locking: two processes writing the same root can interleave whole-file replacements (last write wins). Single-host-process deployments are the current consumer; the multi-process story is deferred per the Agent Note's out-of-scope table. diff --git a/packages/storage/storage-json/package.json b/packages/storage/storage-json/package.json new file mode 100644 index 0000000000..bcc20b6ba1 --- /dev/null +++ b/packages/storage/storage-json/package.json @@ -0,0 +1,42 @@ +{ + "name": "@deepseek-ai/dsh-storage-json", + "description": "JSON file KV storage backend for the DeepSeek Harness storage hub", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-storage": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "dependencies": { + "schemastery": "^3.18.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-storage": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/storage/storage-json/src/atomic.ts b/packages/storage/storage-json/src/atomic.ts new file mode 100644 index 0000000000..94691ffbc4 --- /dev/null +++ b/packages/storage/storage-json/src/atomic.ts @@ -0,0 +1,53 @@ +/** + * Atomic whole-file replacement for the JSON backend. + * + * Publish protocol: write a same-directory temp file, fsync it, then + * `rename()` over the target. Rename is an atomic replace on POSIX and on + * Windows (libuv maps it to `MoveFileExW(..., MOVEFILE_REPLACE_EXISTING)`), + * and replacement is the intended semantic here — unlike the session-log + * backend's link()+unlink() no-clobber protocol, a unit file has exactly one + * writer per process and last-write-wins is correct. After the rename the + * parent directory is fsynced on POSIX so the new entry is crash-durable. + * @module @deepseek-ai/dsh-storage-json/src/atomic + */ + +import { open, rename, rm } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { randomUUID } from 'node:crypto' + +/** + * Durably replace `path` with `data`. + * @param path - Absolute target file path. + * @param data - Full new file content. + * @returns resolution after the replacement is crash-durable. + */ +export async function writeAtomic(path: string, data: string): Promise<void> { + const tmp = join(dirname(path), `.${randomUUID()}.tmp`) + try { + const handle = await open(tmp, 'wx', 0o600) + try { + await handle.writeFile(data, 'utf8') + await handle.sync() + } finally { + await handle.close() + } + await rename(tmp, path) + await fsyncDirectory(dirname(path)) + } catch (error) { + await rm(tmp, { force: true }) + throw error + } +} + +/** fsync a POSIX directory so a just-renamed entry is crash-durable. */ +/* v8 ignore start -- Windows rejects O_RDONLY directory opens; POSIX coverage exercises this. */ +async function fsyncDirectory(path: string): Promise<void> { + if (process.platform === 'win32') return + const handle = await open(path, 'r') + try { + await handle.sync() + } finally { + await handle.close() + } +} +/* v8 ignore stop */ diff --git a/packages/storage/storage-json/src/format.ts b/packages/storage/storage-json/src/format.ts new file mode 100644 index 0000000000..55efb830b7 --- /dev/null +++ b/packages/storage/storage-json/src/format.ts @@ -0,0 +1,84 @@ +/** + * On-disk JSON unit format: the file is always the current net state, kept + * human-readable (pretty-printed, stable key order from insertion) — that + * legibility is this backend's reason to exist. + * @module @deepseek-ai/dsh-storage-json/src/format + */ + +import { StorageError } from '@deepseek-ai/dsh-storage' +import type { KvUnitDescriptor } from '@deepseek-ai/dsh-storage' + +/** In-memory authoritative state of one unit; the file is its projection. `global` is `null` until first written. */ +export interface UnitState { + version: number + global: unknown + tables: Map<string, Map<string, unknown>> +} + +/** + * Serialize a unit state to file content. + * @param name - Unit name, stamped into the header. + * @param state - Authoritative in-memory state. + * @returns pretty-printed JSON document with a trailing newline. + */ +export function serialize(name: string, state: UnitState): string { + const tables: Record<string, Record<string, unknown>> = {} + for (const [table, records] of state.tables) { + tables[table] = Object.fromEntries(records) + } + const document = { + unit: { name, version: state.version }, + global: state.global, + tables, + } + return `${JSON.stringify(document, null, 2)}\n` +} + +/** + * Parse file content into unit state, validating shape and version. + * @param text - Raw file content. + * @param descriptor - Expected identity; version mismatch rejects. + * @returns the parsed state. + */ +export function parse(text: string, descriptor: KvUnitDescriptor): UnitState { + let document: unknown + try { + document = JSON.parse(text) + } catch (error) { + throw new StorageError('malformed-medium', `unit '${descriptor.name}': file is not valid JSON`, { cause: error }) + } + if (typeof document !== 'object' || document === null) { + throw new StorageError('malformed-medium', `unit '${descriptor.name}': file is not a JSON object`) + } + const { unit, global: globalValue, tables } = document as Record<string, unknown> + if ( + typeof unit !== 'object' || unit === null || + (unit as Record<string, unknown>)['name'] !== descriptor.name || + typeof (unit as Record<string, unknown>)['version'] !== 'number' + ) { + throw new StorageError('malformed-medium', `unit '${descriptor.name}': missing or foreign unit header`) + } + const version = (unit as Record<string, unknown>)['version'] as number + if (version !== descriptor.version) { + throw new StorageError( + 'version-mismatch', + `unit '${descriptor.name}': stored version ${version} != expected ${descriptor.version}`, + ) + } + if (typeof tables !== 'object' || tables === null) { + throw new StorageError('malformed-medium', `unit '${descriptor.name}': tables is not an object`) + } + const state: UnitState = { version, global: globalValue ?? null, tables: new Map() } + for (const table of descriptor.tables) { + const records = (tables as Record<string, unknown>)[table] + if (records === undefined) { + state.tables.set(table, new Map()) + continue + } + if (typeof records !== 'object' || records === null || Array.isArray(records)) { + throw new StorageError('malformed-medium', `unit '${descriptor.name}': table '${table}' is not an object`) + } + state.tables.set(table, new Map(Object.entries(records as Record<string, unknown>))) + } + return state +} diff --git a/packages/storage/storage-json/src/index.ts b/packages/storage/storage-json/src/index.ts new file mode 100644 index 0000000000..b80185ecf7 --- /dev/null +++ b/packages/storage/storage-json/src/index.ts @@ -0,0 +1,113 @@ +/** + * JSON storage backend: one human-readable file per unit under a configured + * root, published by atomic whole-file rewrite. Registers as backend `json` + * on the storage hub. + * @module @deepseek-ai/dsh-storage-json + */ + +import { mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import type { Context } from 'cordis' +import z from 'schemastery' +import { StorageError, UNIT_NAME_RE } from '@deepseek-ai/dsh-storage' +import type { KvFacet, KvUnit, KvUnitDescriptor, StorageBackend } from '@deepseek-ai/dsh-storage' +import { openJsonUnit } from './unit.ts' + +/** Cordis plugin name. */ +export const name = 'storage-json' +/** The hub must exist before the backend can register. */ +export const inject = ['storage'] + +/** + * Plugin configuration. + * `root` has NO default on purpose: a `process.cwd()` fallback would scatter + * unit files wherever the process happens to start; assemblies state the + * location explicitly. + */ +export interface Config { + /** Directory holding one `<unit>.json` file per unit. */ + root: string +} + +/** Config schema. */ +export const Config: z<Config> = z.object({ + root: z.string().required(), +}) + +/** JSON backend: owns the file-tree root and serves the `kv` facet. */ +export class JsonStorageBackend implements StorageBackend { + private readonly open = new Map<string, KvUnit>() + // Reserved synchronously at open() entry so a concurrent open of the same + // unit fails, and close() can await opens still in flight. + private readonly opening = new Map<string, Promise<KvUnit>>() + private closed = false + + constructor(private readonly root: string) {} + + readonly kv: KvFacet = { + // The body up to the first await runs synchronously, so the opening-slot + // reservation below still excludes a concurrent open of the same unit. + open: async (descriptor: KvUnitDescriptor): Promise<KvUnit> => { + if (this.closed) throw new StorageError('closed', 'json backend is closed') + validateDescriptor(descriptor) + if (this.open.has(descriptor.name) || this.opening.has(descriptor.name)) { + // Double-open is a caller bug, not a medium condition. + throw new Error(`unit '${descriptor.name}' is already open; a unit has exactly one live handle`) + } + const opening = this.openUnit(descriptor) + this.opening.set(descriptor.name, opening) + return opening.finally(() => this.opening.delete(descriptor.name)) + }, + } + + private async openUnit(descriptor: KvUnitDescriptor): Promise<KvUnit> { + await mkdir(this.root, { recursive: true, mode: 0o700 }) + const path = join(this.root, `${descriptor.name}.json`) + const unit = await openJsonUnit(descriptor, path, () => this.open.delete(descriptor.name)) + if (this.closed) { + // The backend closed while this open was in flight: do not hand out a + // live unit past close(). + await unit.close() + throw new StorageError('closed', 'json backend is closed') + } + this.open.set(descriptor.name, unit) + return unit + } + + async close(): Promise<void> { + if (!this.closed) { + this.closed = true + } + await Promise.allSettled([...this.opening.values()]) + for (const unit of [...this.open.values()]) { + await unit.close() + } + } +} + +function validateDescriptor(descriptor: KvUnitDescriptor): void { + if (!UNIT_NAME_RE.test(descriptor.name)) { + throw new StorageError('malformed-medium', `invalid unit name '${descriptor.name}'`) + } + for (const table of descriptor.tables) { + if (!UNIT_NAME_RE.test(table)) { + throw new StorageError('malformed-medium', `invalid table name '${table}' in unit '${descriptor.name}'`) + } + } +} + +/** + * Register the `json` backend on the storage hub. + * @param ctx - Plugin context. + * @param config - Validated configuration. + */ +export function apply(ctx: Context, config: Config) { + const backend = new JsonStorageBackend(config.root) + ctx.effect(() => { + const unregister = ctx.storage.backend.register('json', backend) + return async () => { + unregister() + await backend.close() + } + }) +} diff --git a/packages/storage/storage-json/src/invariant.ts b/packages/storage/storage-json/src/invariant.ts new file mode 100644 index 0000000000..3f3ec4a2d1 --- /dev/null +++ b/packages/storage/storage-json/src/invariant.ts @@ -0,0 +1,32 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-storage-json`. + * @module @deepseek-ai/dsh-storage-json/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-storage-json' + +/** Cordis companion plugin name. */ +export const name = 'storage-json-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: correctness here is write-durability and + * publish-then-reparse equivalence, which require medium round-trip tests + * (the shared backend conformance suite); the backend exposes no continuously + * observable in-process relation. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/storage/storage-json/src/unit.ts b/packages/storage/storage-json/src/unit.ts new file mode 100644 index 0000000000..9591c30573 --- /dev/null +++ b/packages/storage/storage-json/src/unit.ts @@ -0,0 +1,141 @@ +/** + * One opened JSON unit. The in-memory state is authoritative; every write + * primitive mutates it and republishes the whole file atomically. Writes are + * NOT queued here — per the backend contract, write ordering belongs to the + * caller (the domain layer's write chain); this unit only guarantees that + * each single call publishes a complete, durable file. + * @module @deepseek-ai/dsh-storage-json/src/unit + */ + +import { readFile } from 'node:fs/promises' +import { StorageError } from '@deepseek-ai/dsh-storage' +import type { KvUnit, KvUnitDescriptor } from '@deepseek-ai/dsh-storage' +import { writeAtomic } from './atomic.ts' +import { parse, serialize } from './format.ts' +import type { UnitState } from './format.ts' + +/** + * Open (load or lazily create) one unit backed by `path`. + * @param descriptor - Static identity and shape of the unit. + * @param path - Absolute unit file path under the backend root. + * @param onClose - Backend callback releasing the unit's open-slot. + * @returns the opened unit. + */ +export async function openJsonUnit( + descriptor: KvUnitDescriptor, + path: string, + onClose: () => void, +): Promise<KvUnit> { + let text: string | undefined + try { + text = await readFile(path, 'utf8') + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + // Missing file = empty unit; materialization defers to the first write. + } + const state: UnitState = + text === undefined + ? { + version: descriptor.version, + global: null, + tables: new Map(descriptor.tables.map(table => [table, new Map<string, unknown>()])), + } + : parse(text, descriptor) + return new JsonKvUnit(descriptor, path, state, onClose) +} + +class JsonKvUnit implements KvUnit { + private closed = false + /** In-flight publishes; close() drains them before releasing the unit. */ + private readonly inFlight = new Set<Promise<void>>() + + constructor( + private readonly descriptor: KvUnitDescriptor, + private readonly path: string, + private readonly state: UnitState, + private readonly onClose: () => void, + ) {} + + // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the closed guard a rejection, not a synchronous throw + async loadAll(): Promise<{ tables: Record<string, Record<string, unknown>>; global: unknown }> { + this.assertOpen() + const tables: Record<string, Record<string, unknown>> = {} + for (const [table, records] of this.state.tables) { + tables[table] = Object.fromEntries(records) + } + return { tables, global: this.state.global } + } + + async putRecord(table: string, key: string, value: unknown): Promise<void> { + this.assertOpen() + const records = this.records(table) + const hadKey = records.has(key) + const previous = records.get(key) + records.set(key, value) + // Roll back on a failed publish: memory is authoritative, so a rejected + // write must not survive in memory (or ride along with the next publish). + await this.publish().catch((error: unknown) => { + if (hadKey) records.set(key, previous) + else records.delete(key) + throw error + }) + } + + async deleteRecord(table: string, key: string): Promise<void> { + this.assertOpen() + const records = this.records(table) + if (!records.has(key)) return + const previous = records.get(key) + records.delete(key) + await this.publish().catch((error: unknown) => { + records.set(key, previous) + throw error + }) + } + + async setGlobal(value: unknown): Promise<void> { + this.assertOpen() + if (!this.descriptor.hasGlobal) { + throw new Error(`unit '${this.descriptor.name}' does not declare a global slot`) + } + const previous = this.state.global + this.state.global = value + await this.publish().catch((error: unknown) => { + this.state.global = previous + throw error + }) + } + + async close(): Promise<void> { + if (this.closed) { + await Promise.allSettled(this.inFlight) + return + } + this.closed = true + await Promise.allSettled(this.inFlight) + this.onClose() + } + + private assertOpen(): void { + if (this.closed) { + throw new StorageError('closed', `unit '${this.descriptor.name}' is closed`) + } + } + + private records(table: string): Map<string, unknown> { + const records = this.state.tables.get(table) + if (!records) { + throw new Error(`unit '${this.descriptor.name}' does not declare table '${table}'`) + } + return records + } + + private publish(): Promise<void> { + const write = writeAtomic(this.path, serialize(this.descriptor.name, this.state)) + this.inFlight.add(write) + // Swallow only on the tracking branch: the caller still awaits `write` + // itself, so rejections stay observed exactly once. + write.catch(() => {}).finally(() => this.inFlight.delete(write)) + return write + } +} diff --git a/packages/storage/storage-json/tests/json-backend.spec.ts b/packages/storage/storage-json/tests/json-backend.spec.ts new file mode 100644 index 0000000000..870498f0ea --- /dev/null +++ b/packages/storage/storage-json/tests/json-backend.spec.ts @@ -0,0 +1,222 @@ +import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import Storage from '@deepseek-ai/dsh-storage' +import InvariantService from '@deepseek-ai/dsh-invariants' +import { runKvBackendContract } from '../../storage/tests/contract.ts' +import { Config, JsonStorageBackend, apply } from '../src/index.ts' +import * as InvariantCompanion from '../src/invariant.ts' + +const roots: string[] = [] + +async function freshRoot(): Promise<string> { + const root = await mkdtemp(join(tmpdir(), 'dsh-storage-json-')) + roots.push(root) + return root +} + +afterAll(async () => { + for (const root of roots) await rm(root, { recursive: true, force: true }) +}) + +runKvBackendContract('json', async () => { + const root = await freshRoot() + return { + backend: new JsonStorageBackend(root), + reopen: async () => new JsonStorageBackend(root), + } +}) + +describe('json backend specifics', () => { + const descriptor = { name: 'shape', version: 1, tables: ['t'], hasGlobal: true } + + it('publishes a human-readable pretty-printed file', async () => { + const root = await freshRoot() + const backend = new JsonStorageBackend(root) + const unit = await backend.kv.open(descriptor) + await unit.putRecord('t', 'k', { hello: 'world' }) + const text = await readFile(join(root, 'shape.json'), 'utf8') + expect(text).toBe(`${JSON.stringify( + { unit: { name: 'shape', version: 1 }, global: null, tables: { t: { k: { hello: 'world' } } } }, + null, + 2, + )}\n`) + await backend.close() + }) + + it('defers materialization until the first write', async () => { + const root = await freshRoot() + const backend = new JsonStorageBackend(root) + await backend.kv.open(descriptor) + await expect(readFile(join(root, 'shape.json'), 'utf8')).rejects.toMatchObject({ code: 'ENOENT' }) + await backend.close() + }) + + it('rejects a malformed medium', async () => { + const root = await freshRoot() + await writeFile(join(root, 'shape.json'), 'not json at all', 'utf8') + const backend = new JsonStorageBackend(root) + await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' }) + await backend.close() + }) + + it('rejects a foreign unit header', async () => { + const root = await freshRoot() + await writeFile( + join(root, 'shape.json'), + JSON.stringify({ unit: { name: 'other', version: 1 }, global: null, tables: {} }), + 'utf8', + ) + const backend = new JsonStorageBackend(root) + await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' }) + await backend.close() + }) + + it('rejects double-open of one unit as a plain caller error', async () => { + const root = await freshRoot() + const backend = new JsonStorageBackend(root) + await backend.kv.open(descriptor) + await expect(backend.kv.open(descriptor)).rejects.toThrow(/already open/) + await backend.close() + }) + + it('rolls back memory when a publish fails', async () => { + const root = await freshRoot() + const backend = new JsonStorageBackend(root) + const unit = await backend.kv.open(descriptor) + await unit.putRecord('t', 'k', { v: 'committed' }) + await unit.setGlobal({ g: 'committed' }) + // Make every publish fail: revoke write permission on the root. + await chmod(root, 0o500) + await expect(unit.putRecord('t', 'k', { v: 'rejected' })).rejects.toThrow() + await expect(unit.putRecord('t', 'k2', { v: 'also rejected' })).rejects.toThrow() + await expect(unit.deleteRecord('t', 'k')).rejects.toThrow() + await expect(unit.setGlobal({ g: 'rejected' })).rejects.toThrow() + await chmod(root, 0o700) + const snapshot = await unit.loadAll() + expect(snapshot.tables['t']).toEqual({ k: { v: 'committed' } }) + expect(snapshot.global).toEqual({ g: 'committed' }) + // The next successful publish must not carry rejected writes to disk. + await unit.putRecord('t', 'k3', { v: 'later' }) + const text = await readFile(join(root, 'shape.json'), 'utf8') + expect(text).not.toContain('rejected') + await backend.close() + }) + + it('rejects undeclared table and global access as caller errors', async () => { + const root = await freshRoot() + const backend = new JsonStorageBackend(root) + const unit = await backend.kv.open({ name: 'shape', version: 1, tables: ['t'], hasGlobal: false }) + await expect(unit.putRecord('undeclared', 'k', {})).rejects.toThrow(/does not declare table/) + await expect(unit.setGlobal({})).rejects.toThrow(/does not declare a global slot/) + await backend.close() + }) + + it('rejects invalid unit and table names', async () => { + const root = await freshRoot() + const backend = new JsonStorageBackend(root) + await expect(backend.kv.open({ ...descriptor, name: 'Bad-Name' })).rejects.toMatchObject({ + name: 'StorageError', + code: 'malformed-medium', + }) + await expect(backend.kv.open({ ...descriptor, tables: ['ok', 'not ok'] })).rejects.toMatchObject({ + name: 'StorageError', + code: 'malformed-medium', + }) + await backend.close() + await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'closed' }) + }) + + it('opens a file missing a declared table as that table empty', async () => { + const root = await freshRoot() + await writeFile( + join(root, 'contract_unit.json'), + JSON.stringify({ unit: { name: 'contract_unit', version: 3 }, global: null, tables: { alpha: { k: 1 } } }), + 'utf8', + ) + const backend = new JsonStorageBackend(root) + const unit = await backend.kv.open({ name: 'contract_unit', version: 3, tables: ['alpha', 'beta'], hasGlobal: true }) + const snapshot = await unit.loadAll() + expect(snapshot.tables['alpha']).toEqual({ k: 1 }) + expect(snapshot.tables['beta']).toEqual({}) + await backend.close() + }) + + it('propagates non-ENOENT read failures', async () => { + const root = await freshRoot() + const { mkdir } = await import('node:fs/promises') + // A directory where the unit file should be: readFile fails with EISDIR. + await mkdir(join(root, 'shape.json')) + const backend = new JsonStorageBackend(root) + await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'EISDIR' }) + await backend.close() + }) + + it('rejects malformed table shapes and foreign versions distinctly', async () => { + const root = await freshRoot() + await writeFile( + join(root, 'shape.json'), + JSON.stringify({ unit: { name: 'shape', version: 1 }, global: null, tables: { t: ['not', 'an', 'object'] } }), + 'utf8', + ) + const backend = new JsonStorageBackend(root) + await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' }) + + await writeFile( + join(root, 'shape.json'), + JSON.stringify({ unit: { name: 'shape', version: 9 }, global: null, tables: {} }), + 'utf8', + ) + await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'version-mismatch' }) + + await writeFile(join(root, 'shape.json'), JSON.stringify({ unit: { name: 'shape', version: 1 }, global: null }), 'utf8') + await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' }) + + await writeFile(join(root, 'shape.json'), JSON.stringify('just a string'), 'utf8') + await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' }) + await backend.close() + }) + + it('registers on the hub via apply and closes on dispose', async () => { + const root = await freshRoot() + const ctx = new Context() + await ctx.plugin(Storage) + const fiber = await ctx.plugin({ apply, Config, inject: ['storage'] }, { root }) + const backend = ctx.storage.backend.get('json') + const unit = await backend.kv!.open(descriptor) + await unit.putRecord('t', 'k', { v: 1 }) + await fiber.dispose() + expect(() => ctx.storage.backend.get('json')).toThrow() + await expect(unit.putRecord('t', 'x', {})).rejects.toMatchObject({ code: 'closed' }) + }) + + it('registers the invariant companion and disposes cleanly', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService) + const fiber = await ctx.plugin(InvariantCompanion) + // Disposal releases the reservation: a fresh mount succeeds. + await fiber.dispose() + await ctx.plugin(InvariantCompanion) + }) + + it('close drains in-flight writes and blocks in-flight opens', async () => { + const root = await freshRoot() + const backend = new JsonStorageBackend(root) + const unit = await backend.kv.open(descriptor) + const bigWrite = unit.putRecord('t', 'big', { blob: 'x'.repeat(4 * 1024 * 1024) }) + await unit.close() + await expect(bigWrite).resolves.toBeUndefined() + const onDisk = JSON.parse(await readFile(join(root, 'shape.json'), 'utf8')) as { + tables: Record<string, Record<string, unknown>> + } + expect(onDisk.tables['t']?.['big']).toBeDefined() + + const backend2 = new JsonStorageBackend(root) + const opening = backend2.kv.open(descriptor) + const closing = backend2.close() + await expect(opening.then(u => u.putRecord('t', 'x', {}))).rejects.toMatchObject({ code: 'closed' }) + await closing + }) +}) diff --git a/packages/storage/storage-json/tsconfig.json b/packages/storage/storage-json/tsconfig.json new file mode 100644 index 0000000000..5a13b64de8 --- /dev/null +++ b/packages/storage/storage-json/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../storage" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/storage/storage-sqlite/README.md b/packages/storage/storage-sqlite/README.md new file mode 100644 index 0000000000..272b27f979 --- /dev/null +++ b/packages/storage/storage-sqlite/README.md @@ -0,0 +1,41 @@ +# @deepseek-ai/dsh-storage-sqlite + +SQLite backend for the [storage hub](../storage/README.md): registers as backend `sqlite`, serving the `kv` facet over one `node:sqlite` database file (or `:memory:`). Design and trade-offs: [domain KV storage Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md). + +## Storage model + +Document-per-row: each unit table becomes a physical `"u_<unit>_<table>" (key TEXT PRIMARY KEY, value TEXT)` STRICT table whose `value` is the record's JSON text, so one key updates one row (the reason to route a high-churn domain here instead of the JSON backend). Unit identity lives in two metadata tables — `units` stamps each unit's format version at first open and rejects a differing descriptor with `version-mismatch`; `unit_globals` holds each unit's global singleton row. The physical layout version lives in `PRAGMA user_version`; any other stamped value rejects (unreleased format, no migrations). Unit and table names are validated against the hub's `UNIT_NAME_RE` before they reach DDL, so no external input is ever interpolated into SQL identifiers. + +Every write primitive is a single prepared statement — SQLite's per-statement atomicity satisfies the KV contract without explicit transactions, and write ordering stays the caller's responsibility (the domain layer's write chain). Missing directories and database files are created owner-only (`0o700`/`0o600`), matching the session-persistence SQLite backend, whose open sequence this package copies verbatim until the planned media-layer extraction. + +## Configuration (schemastery) + +```ts +interface Config { + path: string // SQLite database file path, or ':memory:' for an in-process DB + journalMode?: 'wal' | 'delete' | 'truncate' | 'persist' // journal_mode pragma; default 'wal' +} +``` + +## Model Experience + +### Stored domain records + +#### What the model sees + +Nothing. This backend contributes no prompt, tool, or schema; it persists non-session domain data (workspace records, future session sidecar metadata) behind `ctx.storage` for host-side consumers only. + +#### Token effect + +Zero live-request tokens. + +#### KV Cache effect + +None — the backend never touches live request prefixes. + +## Known Limitations and Deferred Work + +- **`DatabaseSync` is synchronous** — each write blocks the event loop for its (single-statement) duration; acceptable at domain-data scale. +- **No busy-wait or retry policy** — another connection holding a write transaction rejects the operation immediately; multi-process write protection is on the design's future-work list. +- **Only the current `STORAGE_SQLITE_SCHEMA_VERSION` opens** — any other stamped version is rejected rather than migrated (pre-release stance). +- **`openDatabase` duplicates the session-persistence SQLite open sequence** — extraction into a shared media layer is deferred to the planned session-backend migration (see the Agent Note's reuse audit). diff --git a/packages/storage/storage-sqlite/package.json b/packages/storage/storage-sqlite/package.json new file mode 100644 index 0000000000..dc792fe350 --- /dev/null +++ b/packages/storage/storage-sqlite/package.json @@ -0,0 +1,42 @@ +{ + "name": "@deepseek-ai/dsh-storage-sqlite", + "description": "SQLite storage backend (kv facet) for the DeepSeek Harness storage hub", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-storage": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "dependencies": { + "schemastery": "^3.18.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-storage": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/storage/storage-sqlite/src/index.ts b/packages/storage/storage-sqlite/src/index.ts new file mode 100644 index 0000000000..72fff382bc --- /dev/null +++ b/packages/storage/storage-sqlite/src/index.ts @@ -0,0 +1,167 @@ +/** + * SQLite storage backend for the storage hub: one database file hosts every + * routed unit, document-per-row (`key TEXT` / `value TEXT` JSON). Registers + * as backend `sqlite`; the disposer unregisters first, then closes the medium. + * @module @deepseek-ai/dsh-storage-sqlite + */ + +import type { Context } from 'cordis' +import z from 'schemastery' +import type { DatabaseSync } from 'node:sqlite' +import { StorageError, UNIT_NAME_RE } from '@deepseek-ai/dsh-storage' +import type { KvFacet, KvUnit, KvUnitDescriptor, StorageBackend } from '@deepseek-ai/dsh-storage' +import { openDatabase, recordTableName, type JournalMode } from './schema.ts' +import { SqliteKvUnit } from './unit.ts' + +export { STORAGE_SQLITE_SCHEMA_VERSION, type JournalMode } from './schema.ts' + +/** Cordis plugin name. */ +export const name = 'storage-sqlite' +/** The backend registers on the storage hub. */ +export const inject = ['storage'] + +/** Plugin configuration. */ +export interface Config { + /** + * Filesystem path to the SQLite database file. The special value `:memory:` + * opens an in-process database (tests). On filesystems with POSIX modes, + * missing directories and databases are created owner-only; existing path + * modes are preserved. Filesystem setup errors other than an existing + * database fail the open. The backend does not protect confidentiality or + * integrity when another principal can replace the database entry in its + * parent directory. + */ + path: string + /** + * SQLite `journal_mode` pragma. `wal` (the default) suits local disks; pick + * a rollback-journal mode (`delete`/`truncate`/`persist`) on filesystems + * where WAL's shared-memory files do not work (network mounts). See + * {@link JournalMode}. + */ + journalMode?: JournalMode +} + +/** Schemastery validator for {@link Config}. */ +export const Config: z<Config> = z.object({ + path: z.string().required(), + journalMode: z.union(['wal', 'delete', 'truncate', 'persist'] as const).default('wal'), +}) + +/** + * The SQLite {@link StorageBackend}. Owns one `DatabaseSync` connection and + * the open-unit table; `kv.open` validates names, enforces the per-unit + * version stamp in `units`, and ensures the unit's record tables. + */ +export class SqliteStorageBackend implements StorageBackend { + /** The key-value facet; the only shape this backend serves. */ + readonly kv: KvFacet = { open: descriptor => this.openUnit(descriptor) } + + private readonly ready: Promise<DatabaseSync> + /** Open (or still-opening) units by name; presence is the double-open guard. */ + private readonly units = new Map<string, Promise<SqliteKvUnit>>() + private closing: Promise<void> | undefined + + /** + * @param config - Validated plugin configuration. + */ + constructor(config: Config) { + this.ready = openDatabase(config.path, (config as Required<Config>).journalMode) + // Mark the rejection handled: every primitive re-awaits `ready`, so an + // open failure still surfaces to each caller; this guard only prevents an + // unhandled-rejection crash when the failure precedes the first use. + this.ready.catch(() => {}) + } + + private openUnit(descriptor: KvUnitDescriptor): Promise<KvUnit> { + if (this.closing !== undefined) { + return Promise.reject(new StorageError('closed', 'sqlite storage backend is closed')) + } + if (!UNIT_NAME_RE.test(descriptor.name)) { + return Promise.reject(new Error(`kv unit name '${descriptor.name}' violates ${UNIT_NAME_RE}`)) + } + for (const table of descriptor.tables) { + if (!UNIT_NAME_RE.test(table)) { + return Promise.reject(new Error(`kv table name '${table}' in unit '${descriptor.name}' violates ${UNIT_NAME_RE}`)) + } + } + if (this.units.has(descriptor.name)) { + return Promise.reject(new Error(`kv unit '${descriptor.name}' is already open (double-open is a caller bug)`)) + } + // Reserve the name synchronously so a concurrent second open of the same + // name rejects instead of racing past the guard during the awaits below. + const pending = this.materializeUnit(descriptor) + this.units.set(descriptor.name, pending) + pending.catch(() => this.units.delete(descriptor.name)) + return pending + } + + private async materializeUnit(descriptor: KvUnitDescriptor): Promise<SqliteKvUnit> { + const db = await this.ready + const row = db.prepare('SELECT version FROM units WHERE name = ?').get(descriptor.name) as + | { version: number } + | undefined + if (row === undefined) { + db.prepare('INSERT INTO units (name, version) VALUES (?, ?)').run(descriptor.name, descriptor.version) + } else if (row.version !== descriptor.version) { + throw new StorageError( + 'version-mismatch', + `kv unit '${descriptor.name}' is stamped version ${row.version} on the medium, incompatible with descriptor version ${descriptor.version}`, + ) + } + for (const table of descriptor.tables) { + // Both segments passed UNIT_NAME_RE, so the identifier is safe in DDL. + db.exec(` + CREATE TABLE IF NOT EXISTS "${recordTableName(descriptor.name, table)}" ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ) STRICT + `) + } + return new SqliteKvUnit(db, descriptor, () => { + this.units.delete(descriptor.name) + }) + } + + /** + * Close every open unit and release the database. Idempotent; concurrent + * and repeated calls resolve once teardown finishes. + * @returns resolution after the medium is released. + */ + close(): Promise<void> { + this.closing ??= this.doClose() + return this.closing + } + + private async doClose(): Promise<void> { + let db: DatabaseSync + try { + db = await this.ready + } catch { + // The medium never opened; that failure already rejected the opener and + // every unit call, so there is nothing left to release here. + return + } + for (const pending of [...this.units.values()]) { + const unit = await pending.catch(() => undefined) + await unit?.close() + } + db.close() + } +} + +/** + * Register the SQLite backend as `sqlite` on the storage hub. The disposer + * unregisters the name first, then closes the backend. + * @param ctx - Plugin context (must inject `storage`). + * @param config - Validated plugin configuration. + */ +export function apply(ctx: Context, config: Config) { + const backend = new SqliteStorageBackend(config) + ctx.effect(() => { + const dispose = ctx.storage.backend.register('sqlite', backend) + return async () => { + dispose() + await backend.close() + } + }, 'storage-sqlite.registerBackend') +} diff --git a/packages/storage/storage-sqlite/src/invariant.ts b/packages/storage/storage-sqlite/src/invariant.ts new file mode 100644 index 0000000000..cbfadc8442 --- /dev/null +++ b/packages/storage/storage-sqlite/src/invariant.ts @@ -0,0 +1,32 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-storage-sqlite`. + * @module @deepseek-ai/dsh-storage-sqlite/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-storage-sqlite' + +/** Cordis companion plugin name. */ +export const name = 'storage-sqlite-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: schema-version and unit-version consistency are + * open-time checks that reject before a unit exists, and durability needs the + * backend round-trip tests in the shared KV conformance suite; this package + * exposes no continuously observable in-process relation. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/storage/storage-sqlite/src/schema.ts b/packages/storage/storage-sqlite/src/schema.ts new file mode 100644 index 0000000000..c9ac817415 --- /dev/null +++ b/packages/storage/storage-sqlite/src/schema.ts @@ -0,0 +1,120 @@ +/** + * Schema + open-time helpers for the SQLite storage backend: the physical + * layout version, the database open/configure sequence (permissions, pragmas, + * version stamp/reject), and the unit metadata tables. Unit record tables are + * created per descriptor in `unit.ts`. + * @module @deepseek-ai/dsh-storage-sqlite/schema + */ + +import { DatabaseSync } from 'node:sqlite' +import { mkdir, open } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { StorageError } from '@deepseek-ai/dsh-storage' + +/** + * The on-disk physical layout version, stored in `PRAGMA user_version`. + * Orthogonal to each unit's own `version` (stamped per unit in the `units` + * row). Bumped only on a breaking change to the table layout; any other + * stamped version rejects — this unreleased format has no migrations. + */ +export const STORAGE_SQLITE_SCHEMA_VERSION = 1 + +/** + * Journal modes the backend will run under. `wal` is the default; the + * rollback-journal modes (`delete`/`truncate`/`persist`) exist for + * filesystems where WAL's shared-memory files do not work (network mounts). + * `memory`/`off` are excluded: dropping journal durability silently + * contradicts the durability clause of the KV backend contract. + */ +export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' + +/* jscpd:ignore-start -- deliberately mirrors the session-persistence-sqlite / + session-query-sqlite open sequence; this group is the third user, and the + shared medium helper is deferred to the log-facet migration so the session + packages stay untouched this phase (see the domain KV storage Agent Note's + reuse audit). */ +/** + * Exclusively create a missing database file with owner-only permissions. + * Existing files retain their modes, and errors other than `EEXIST` propagate. + * `DatabaseSync` reopens by path, so this does not protect confidentiality or + * integrity when another principal can replace the database entry in its + * parent directory. + */ +async function createDatabaseFile(path: string): Promise<void> { + try { + const handle = await open(path, 'wx', 0o600) + await handle.close() + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error + } +} + +/** + * Open the database and apply its schema and pragmas. Missing directories and + * database files are created owner-only (`:memory:` skips filesystem setup). + * A zero `user_version` is stamped with {@link STORAGE_SQLITE_SCHEMA_VERSION}; + * every other non-current version rejects rather than being migrated in place. + * @param path - the SQLite database file to open, or `:memory:`. + * @param journalMode - validated journal pragma. + * @returns the open handle with pragmas applied and the unit metadata tables ensured. + */ +export async function openDatabase(path: string, journalMode: JournalMode): Promise<DatabaseSync> { + const actual = path === ':memory:' ? path : resolve(path) + if (actual !== ':memory:') { + await mkdir(dirname(actual), { recursive: true, mode: 0o700 }) + await createDatabaseFile(actual) + } + const db = new DatabaseSync(actual) + try { + configureDatabase(db, actual, journalMode) + return db + } catch (error: unknown) { + db.close() + throw error + } +} + +function configureDatabase(db: DatabaseSync, path: string, journalMode: JournalMode): void { + db.exec('PRAGMA foreign_keys = ON') + // The validated union is safe to interpolate into a non-bindable PRAGMA. + db.exec(`PRAGMA journal_mode = ${journalMode.toUpperCase()}`) + // `PRAGMA user_version` always returns exactly one row { user_version }. + const { user_version: onDisk } = db.prepare('PRAGMA user_version').get() as { user_version: number } + if (onDisk !== 0 && onDisk !== STORAGE_SQLITE_SCHEMA_VERSION) { + throw new StorageError( + 'version-mismatch', + `storage database at "${path}" has schema version ${onDisk}, incompatible with this build (${STORAGE_SQLITE_SCHEMA_VERSION})`, + ) + } + /* jscpd:ignore-end */ + db.exec(` + CREATE TABLE IF NOT EXISTS units ( + name TEXT PRIMARY KEY, + version INTEGER NOT NULL + ) STRICT + `) + db.exec(` + CREATE TABLE IF NOT EXISTS unit_globals ( + unit TEXT PRIMARY KEY REFERENCES units(name), + value TEXT NOT NULL + ) STRICT + `) + if (onDisk === 0) { + // Stamp fresh databases LAST: the stamp asserts the layout is complete, + // so a failure above must leave the medium unstamped (a re-open after + // the obstruction is cleared retries materialization from scratch). + db.exec(`PRAGMA user_version = ${STORAGE_SQLITE_SCHEMA_VERSION}`) + } +} + +/** + * Physical table name for one unit table. Both segments are validated against + * `UNIT_NAME_RE` before reaching this, so the result is safe to interpolate + * into DDL and prepared-statement text. + * @param unit - Validated unit name. + * @param table - Validated table name. + * @returns the `u_<unit>_<table>` identifier. + */ +export function recordTableName(unit: string, table: string): string { + return `u_${unit}_${table}` +} diff --git a/packages/storage/storage-sqlite/src/unit.ts b/packages/storage/storage-sqlite/src/unit.ts new file mode 100644 index 0000000000..d8260b3108 --- /dev/null +++ b/packages/storage/storage-sqlite/src/unit.ts @@ -0,0 +1,156 @@ +/** + * One opened SQLite KV unit: prepared per-table statements over the + * `u_<unit>_<table>` record tables plus this unit's row in the shared + * `unit_globals` table. Each primitive is a single statement, so atomicity + * comes from SQLite itself — no explicit transactions, and no write queue + * (write ordering is the caller's responsibility per the KV contract). + * @module @deepseek-ai/dsh-storage-sqlite/unit + */ + +import type { DatabaseSync, StatementSync } from 'node:sqlite' +import { StorageError } from '@deepseek-ai/dsh-storage' +import type { KvUnit, KvUnitDescriptor } from '@deepseek-ai/dsh-storage' +import { recordTableName } from './schema.ts' + +/** Prepared statements for one declared table. */ +interface TableStatements { + upsert: StatementSync + remove: StatementSync + selectAll: StatementSync +} + +/** + * The SQLite {@link KvUnit}. Constructed by the backend AFTER the unit's + * record tables exist; statements are prepared once here and reused for every + * primitive. Values are stored as JSON text in the `value` column. + */ +export class SqliteKvUnit implements KvUnit { + private readonly tables = new Map<string, TableStatements>() + private readonly globalUpsert: StatementSync | undefined + private readonly globalSelect: StatementSync | undefined + private closed = false + + /** + * @param db - Open database handle owned by the backend (never closed here). + * @param descriptor - Validated descriptor whose record tables already exist. + * @param onClose - Backend callback releasing this unit's open-name slot. + */ + constructor( + db: DatabaseSync, + private readonly descriptor: KvUnitDescriptor, + private readonly onClose: () => void, + ) { + for (const table of descriptor.tables) { + // Both name segments are validated against UNIT_NAME_RE by the backend, + // so the physical identifier is safe to interpolate into statement text. + const physical = recordTableName(descriptor.name, table) + this.tables.set(table, { + upsert: db.prepare( + `INSERT INTO "${physical}" (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`, + ), + remove: db.prepare(`DELETE FROM "${physical}" WHERE key = ?`), + selectAll: db.prepare(`SELECT key, value FROM "${physical}"`), + }) + } + this.globalUpsert = descriptor.hasGlobal + ? db.prepare( + 'INSERT INTO unit_globals (unit, value) VALUES (?, ?) ON CONFLICT(unit) DO UPDATE SET value = excluded.value', + ) + : undefined + this.globalSelect = descriptor.hasGlobal + ? db.prepare('SELECT value FROM unit_globals WHERE unit = ?') + : undefined + } + + loadAll(): Promise<{ tables: Record<string, Record<string, unknown>>; global: unknown }> { + return this.settle(() => { + const tables: Record<string, Record<string, unknown>> = {} + for (const [name, statements] of this.tables) { + // Null prototype: record keys are arbitrary strings, so '__proto__' + // must land as an own property instead of mutating the prototype. + const records: Record<string, unknown> = Object.create(null) as Record<string, unknown> + for (const row of statements.selectAll.all() as unknown as Array<{ key: string; value: string }>) { + records[row.key] = this.parseValue(row.value, `table '${name}' key '${row.key}'`) + } + tables[name] = records + } + let global: unknown = null + if (this.globalSelect !== undefined) { + const row = this.globalSelect.get(this.descriptor.name) as { value: string } | undefined + if (row !== undefined) global = this.parseValue(row.value, 'global slot') + } + return { tables, global } + }) + } + + /** Parse one stored value column, mapping bad JSON to `malformed-medium`. */ + private parseValue(text: string, slot: string): unknown { + try { + return JSON.parse(text) + } catch (error) { + throw new StorageError( + 'malformed-medium', + `kv unit '${this.descriptor.name}' holds unparsable JSON at ${slot}`, + { cause: error }, + ) + } + } + + putRecord(table: string, key: string, value: unknown): Promise<void> { + return this.settle(() => { + this.statementsFor(table).upsert.run(key, JSON.stringify(value)) + }) + } + + deleteRecord(table: string, key: string): Promise<void> { + return this.settle(() => { + this.statementsFor(table).remove.run(key) + }) + } + + setGlobal(value: unknown): Promise<void> { + return this.settle(() => { + if (this.globalUpsert === undefined) { + throw new Error(`kv unit '${this.descriptor.name}' declared no global slot`) + } + this.globalUpsert.run(this.descriptor.name, JSON.stringify(value)) + }) + } + + close(): Promise<void> { + if (!this.closed) { + this.closed = true + this.onClose() + } + return Promise.resolve() + } + + /** + * Run one synchronous primitive behind the closed guard, mapping a throw to + * a rejection so the Promise-returning contract never throws synchronously. + */ + private settle<T>(operation: () => T): Promise<T> { + try { + this.ensureOpen() + return Promise.resolve(operation()) + } catch (error) { + // Non-Error throws can only enter through JSON.stringify propagating a + // value's own toJSON throw; wrap those, preserve every real Error. + return Promise.reject(error instanceof Error ? error : new Error(String(error))) + } + } + + private ensureOpen(): void { + if (this.closed) { + throw new StorageError('closed', `kv unit '${this.descriptor.name}' is closed`) + } + } + + private statementsFor(table: string): TableStatements { + const statements = this.tables.get(table) + if (statements === undefined) { + throw new Error(`kv unit '${this.descriptor.name}' declared no table '${table}'`) + } + return statements + } +} diff --git a/packages/storage/storage-sqlite/tests/invariant.spec.ts b/packages/storage/storage-sqlite/tests/invariant.spec.ts new file mode 100644 index 0000000000..0c23906ca4 --- /dev/null +++ b/packages/storage/storage-sqlite/tests/invariant.spec.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import InvariantService from '@deepseek-ai/dsh-invariants' +import * as StorageSqliteInvariant from '../src/invariant.ts' + +describe('invariant companion', () => { + it('registers under the package name with an explained-empty installer', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService, { enabled: true }) + await expect(ctx.plugin(StorageSqliteInvariant).await()).resolves.toBeDefined() + }) +}) diff --git a/packages/storage/storage-sqlite/tests/sqlite-backend.spec.ts b/packages/storage/storage-sqlite/tests/sqlite-backend.spec.ts new file mode 100644 index 0000000000..b5ddd46fb1 --- /dev/null +++ b/packages/storage/storage-sqlite/tests/sqlite-backend.spec.ts @@ -0,0 +1,263 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { DatabaseSync } from 'node:sqlite' +import Storage from '@deepseek-ai/dsh-storage' +import type { KvUnitDescriptor } from '@deepseek-ai/dsh-storage' +import { runKvBackendContract } from '../../storage/tests/contract.ts' +import * as StorageSqlite from '../src/index.ts' +import { Config, SqliteStorageBackend, STORAGE_SQLITE_SCHEMA_VERSION } from '../src/index.ts' + +/** Mirror the loader: resolve schemastery defaults before construction. */ +function backendAt(path: string): SqliteStorageBackend { + return new SqliteStorageBackend(new Config({ path })) +} + +const dirs: string[] = [] +afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) }) + +async function freshDbPath(): Promise<string> { + const dir = await mkdtemp(join(tmpdir(), 'dsh-storage-sqlite-')) + dirs.push(dir) + return join(dir, 'storage.db') +} + +// The contract suite's reopen() needs a surviving medium, so the harness binds +// a real file; :memory: gets its own cases below. +runKvBackendContract('sqlite', async () => { + const path = await freshDbPath() + return { + backend: backendAt(path), + reopen: async () => backendAt(path), + } +}) + +const DESCRIPTOR: KvUnitDescriptor = { + name: 'specimen', + version: 1, + tables: ['records'], + hasGlobal: true, +} + +describe('sqlite backend specifics', () => { + it('opens an in-memory database', async () => { + const backend = backendAt(':memory:') + const unit = await backend.kv.open(DESCRIPTOR) + await unit.putRecord('records', 'k', { n: 1 }) + expect((await unit.loadAll()).tables['records']).toEqual({ k: { n: 1 } }) + await backend.close() + }) + + it('materializes STRICT record tables and stamps the schema version', async () => { + const path = await freshDbPath() + const backend = backendAt(path) + const unit = await backend.kv.open(DESCRIPTOR) + await unit.putRecord('records', 'k', { n: 1 }) + await backend.close() + + const db = new DatabaseSync(path) + try { + const { user_version: version } = db.prepare('PRAGMA user_version').get() as { user_version: number } + expect(version).toBe(STORAGE_SQLITE_SCHEMA_VERSION) + const table = db.prepare( + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'u_specimen_records'", + ).get() as { sql: string } | undefined + expect(table?.sql).toContain('STRICT') + const unitRow = db.prepare('SELECT version FROM units WHERE name = ?').get('specimen') as { version: number } + expect(unitRow.version).toBe(DESCRIPTOR.version) + } finally { + db.close() + } + }) + + it('rejects a mismatched database schema version', async () => { + const path = await freshDbPath() + const db = new DatabaseSync(path) + db.exec('PRAGMA user_version = 999') + db.close() + + const backend = backendAt(path) + await expect(backend.kv.open(DESCRIPTOR)).rejects.toMatchObject({ + name: 'StorageError', + code: 'version-mismatch', + }) + await backend.close() + }) + + it('rejects invalid unit and table names before touching the medium', async () => { + const backend = backendAt(':memory:') + await expect(backend.kv.open({ ...DESCRIPTOR, name: 'Bad-Name' })).rejects.toThrow(/violates/) + await expect(backend.kv.open({ ...DESCRIPTOR, tables: ['ok', '1bad'] })).rejects.toThrow(/violates/) + await backend.close() + }) + + it('rejects a second open of the same unit name', async () => { + const backend = backendAt(':memory:') + await backend.kv.open(DESCRIPTOR) + await expect(backend.kv.open(DESCRIPTOR)).rejects.toThrow(/already open/) + await backend.close() + }) + + it('allows re-open after unit close, and rejects open on a closed backend', async () => { + const backend = backendAt(':memory:') + const unit = await backend.kv.open(DESCRIPTOR) + await unit.close() + const again = await backend.kv.open(DESCRIPTOR) + await again.putRecord('records', 'k', 1) + await backend.close() + await expect(backend.kv.open(DESCRIPTOR)).rejects.toMatchObject({ code: 'closed' }) + }) + + it('round-trips prototype-polluting keys as own properties', async () => { + const backend = backendAt(':memory:') + const unit = await backend.kv.open(DESCRIPTOR) + await unit.putRecord('records', '__proto__', { evil: true }) + await unit.putRecord('records', 'constructor', { n: 1 }) + const { tables } = await unit.loadAll() + const records = tables['records']! + expect(Object.hasOwn(records, '__proto__')).toBe(true) + expect(records['__proto__']).toEqual({ evil: true }) + expect(records['constructor']).toEqual({ n: 1 }) + expect(Object.getPrototypeOf({})).not.toHaveProperty('evil') + await backend.close() + }) + + it('leaves a failed materialization unstamped so a repaired medium reopens', async () => { + const path = await freshDbPath() + // Obstruct table creation: an index squatting on the unit_globals name + // makes CREATE TABLE IF NOT EXISTS throw AFTER the units table exists. + const setup = new DatabaseSync(path) + setup.exec('CREATE TABLE squatter (x TEXT)') + setup.exec('CREATE INDEX unit_globals ON squatter(x)') + setup.close() + + const broken = backendAt(path) + await expect(broken.kv.open(DESCRIPTOR)).rejects.toThrow(/already an index/) + await broken.close() + + // Clear the obstruction; the medium must still be version 0, not a + // half-materialized database stamped as current. + const repair = new DatabaseSync(path) + expect((repair.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(0) + repair.exec('DROP INDEX unit_globals') + repair.close() + + const backend = backendAt(path) + const unit = await backend.kv.open(DESCRIPTOR) + await unit.putRecord('records', 'k', { n: 1 }) + await backend.close() + }) + + it('rejects unparsable stored JSON with malformed-medium', async () => { + const path = await freshDbPath() + const backend = backendAt(path) + const unit = await backend.kv.open(DESCRIPTOR) + await unit.putRecord('records', 'good', { n: 1 }) + await unit.setGlobal({ g: 1 }) + await backend.close() + + const db = new DatabaseSync(path) + db.prepare('UPDATE u_specimen_records SET value = ? WHERE key = ?').run('{not json', 'good') + db.close() + + const reopened = backendAt(path) + const damaged = await reopened.kv.open(DESCRIPTOR) + await expect(damaged.loadAll()).rejects.toMatchObject({ + name: 'StorageError', + code: 'malformed-medium', + }) + await reopened.close() + }) + + it('wraps a non-Error toJSON throw into an Error rejection', async () => { + const backend = backendAt(':memory:') + const unit = await backend.kv.open(DESCRIPTOR) + // JSON.stringify propagates a value's own toJSON throw verbatim; the unit + // must still reject with an Error instance. + const hostile = { toJSON: () => { throw 'not an error' } } + await expect(unit.putRecord('records', 'k', hostile)).rejects.toThrow('not an error') + await expect(unit.putRecord('records', 'k', hostile)).rejects.toBeInstanceOf(Error) + await backend.close() + }) + + it('rejects setGlobal on a unit without a global slot and writes to undeclared tables', async () => { + const backend = backendAt(':memory:') + const unit = await backend.kv.open({ ...DESCRIPTOR, hasGlobal: false }) + await expect(unit.setGlobal({ g: 1 })).rejects.toThrow(/declared no global slot/) + await expect(unit.putRecord('undeclared', 'k', 1)).rejects.toThrow(/declared no table/) + expect((await unit.loadAll()).global).toBeNull() + await backend.close() + }) + + it('drains a still-pending failed open during close', async () => { + const path = await freshDbPath() + const first = backendAt(path) + await (await first.kv.open(DESCRIPTOR)).close() + await first.close() + + const backend = backendAt(path) + // Do not await: close() must tolerate an in-flight open that will reject + // (version mismatch) while its name is still reserved in the unit table. + const pending = backend.kv.open({ ...DESCRIPTOR, version: 99 }) + const closed = backend.close() + await expect(pending).rejects.toMatchObject({ code: 'version-mismatch' }) + await closed + }) + + it('propagates filesystem errors other than an existing database file', async () => { + if (process.platform === 'win32') return + const dir = await mkdtemp(join(tmpdir(), 'dsh-storage-sqlite-')) + dirs.push(dir) + await chmod(dir, 0o500) + const backend = backendAt(join(dir, 'storage.db')) + await expect(backend.kv.open(DESCRIPTOR)).rejects.toMatchObject({ code: 'EACCES' }) + await backend.close() + await chmod(dir, 0o700) + }) + + it('preserves the mode of an existing database file', async () => { + if (process.platform === 'win32') return + const path = await freshDbPath() + await writeFile(path, '', { mode: 0o644 }) + await chmod(path, 0o644) + const backend = backendAt(path) + const unit = await backend.kv.open(DESCRIPTOR) + await unit.putRecord('records', 'k', 1) + await backend.close() + }) + + it('registers on the storage hub as backend sqlite and closes on dispose', async () => { + const ctx = new Context() + await ctx.plugin(Storage) + const fiber = await ctx.plugin(StorageSqlite, { path: ':memory:' }) + const backend = ctx.storage.backend.get('sqlite') + const unit = await backend.kv!.open(DESCRIPTOR) + await unit.putRecord('records', 'k', { n: 1 }) + + await fiber.dispose() + expect(ctx.storage.backend.names()).toEqual([]) + await expect(backend.kv!.open(DESCRIPTOR)).rejects.toMatchObject({ code: 'closed' }) + }) + + it('rejects an unparsable global slot with malformed-medium', async () => { + const path = await freshDbPath() + const backend = backendAt(path) + const unit = await backend.kv.open(DESCRIPTOR) + await unit.setGlobal({ g: 1 }) + await backend.close() + + const db = new DatabaseSync(path) + db.prepare('UPDATE unit_globals SET value = ? WHERE unit = ?').run('][', 'specimen') + db.close() + + const reopened = backendAt(path) + const damaged = await reopened.kv.open(DESCRIPTOR) + await expect(damaged.loadAll()).rejects.toMatchObject({ + name: 'StorageError', + code: 'malformed-medium', + }) + await reopened.close() + }) +}) diff --git a/packages/storage/storage-sqlite/tsconfig.json b/packages/storage/storage-sqlite/tsconfig.json new file mode 100644 index 0000000000..5a13b64de8 --- /dev/null +++ b/packages/storage/storage-sqlite/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../storage" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/storage/storage/README.md b/packages/storage/storage/README.md new file mode 100644 index 0000000000..c2f7da9fd1 --- /dev/null +++ b/packages/storage/storage/README.md @@ -0,0 +1,39 @@ +# @deepseek-ai/dsh-storage + +Storage hub (`ctx.storage`) for non-session data: a named backend registry plus mounted data-form facilities. The hub performs no IO itself — backends own media, data forms own semantics. Design and trade-offs: [domain KV storage Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md). + +## Shape + +- `ctx.storage.backend` — name → backend table. Multiple backends stay mounted side by side (`json`, `sqlite`); which backend serves a consumer is that consumer's configuration (the domain layer's route table), never a hub-global choice. `register()` returns the disposer; duplicate names and unknown lookups fail loud. +- `ctx.storage.mount(form, facility)` / `ctx.storage.form(form)` — data-form mounting. `StorageForms` is merge-extensible; the domain layer merges `domain` and is reached as `ctx.storage.domain`. +- A backend owns one medium (file-tree root, database file) and exposes optional data-shape **facets** — `kv` today; an append-log facet is reserved for the future session-backend migration. `src/backend.ts` is the normative contract text; `tests/contract.ts` exports the shared conformance suite every backend runs. + +## Packages in this group + +| Package | Role | +| --- | --- | +| `dsh-storage` | The hub service + backend vocabulary + shared conformance suite | +| `dsh-storage-json` | JSON backend: one unit per human-readable file, atomic whole-file rewrite | +| `dsh-storage-sqlite` | SQLite backend: one database hosting all routed units, document-per-row | +| `dsh-storage-domain` | Domain data form (`ctx.storage.domain`): typed schemas, write chain, change events | + +## Model Experience + +### Backend and form registrations + +#### What the model sees + +Nothing. `ctx.storage` is a host-side registration table; the hub registers no tools, injects no prompts, and writes no session events. + +#### Token effect + +Zero direct tokens on every request. + +#### KV Cache effect + +Independent of live requests: the hub never touches a request prefix, so it cannot invalidate provider cache reuse. + +## Known Limitations and Deferred Work + +- **`kv` is the only data shape** — the append-log facet the future session-backend migration needs is reserved in the design note but not yet defined; backends currently have exactly one facet to implement. +- **Forms resolve lazily** — reading `ctx.storage.domain` before the domain plugin mounts throws `form-not-mounted`; assemblies order plugins accordingly (misconfiguration fails loud rather than silently deferring). diff --git a/packages/storage/storage/package.json b/packages/storage/storage/package.json new file mode 100644 index 0000000000..600eb997ee --- /dev/null +++ b/packages/storage/storage/package.json @@ -0,0 +1,37 @@ +{ + "name": "@deepseek-ai/dsh-storage", + "description": "Storage hub (ctx.storage): named backend registry plus mounted data-form facilities for the DeepSeek Harness", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-invariants": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "devDependencies": { + "@deepseek-ai/dsh-invariants": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/storage/storage/src/backend.ts b/packages/storage/storage/src/backend.ts new file mode 100644 index 0000000000..d9070874ca --- /dev/null +++ b/packages/storage/storage/src/backend.ts @@ -0,0 +1,104 @@ +/** + * Backend-facing vocabulary of the storage hub: a backend owns one medium + * (a file-tree root, a database file) and exposes data-shape facets over it. + * This module is the normative contract text for backend implementers; the + * shared conformance suite in `tests/contract.ts` asserts every clause. + * @module @deepseek-ai/dsh-storage/src/backend + */ + +/** Allowed shape for unit and table names: safe as a file name and as a SQL identifier segment without escaping. */ +export const UNIT_NAME_RE = /^[a-z][a-z0-9_]*$/ + +/** + * One registered backend. A backend owns exactly one medium and shares its + * lifecycle across all facets; facets are optional members — a backend that + * cannot serve a shape simply omits it, and resolution fails loud instead. + */ +export interface StorageBackend { + /** Key-value data shape; absent when this backend cannot serve it. */ + readonly kv?: KvFacet + + /** + * Drain in-flight writes across all open units and release the medium. + * Idempotent; concurrent and repeated calls resolve once teardown finishes. + * @returns resolution after the medium is released. + */ + close(): Promise<void> +} + +/** The key-value data shape: whole-unit snapshots plus per-record durable writes. */ +export interface KvFacet { + /** + * Open one unit, creating it when the medium holds no trace of it yet + * (materialization may defer to the first write, but {@link KvUnit.loadAll} + * must immediately serve the empty shape). A version already stamped on the + * medium that differs from `descriptor.version` rejects with + * `version-mismatch`; a medium that cannot be parsed as this unit rejects + * with `malformed-medium`. Opening the same unit name twice without closing + * is a caller bug and rejects. + * @param descriptor - Static identity and shape of the unit to open. + * @returns the opened unit. + */ + open(descriptor: KvUnitDescriptor): Promise<KvUnit> +} + +/** Static identity and shape of one KV unit, projected from its owner's spec. */ +export interface KvUnitDescriptor { + /** Unit name; must match {@link UNIT_NAME_RE}. Also the file-name / SQL-identifier segment. */ + readonly name: string + /** Unit format version; a non-negative integer stamped on the medium at first materialization. */ + readonly version: number + /** Table names; each must match {@link UNIT_NAME_RE}. */ + readonly tables: readonly string[] + /** Whether this unit carries the global singleton slot. */ + readonly hasGlobal: boolean +} + +/** + * One opened unit. Values are opaque JSON to this layer: no schema, no + * events, no domain meaning. The unit does NOT serialize concurrent writes — + * write ordering is the caller's responsibility (the domain layer runs one + * write chain per unit); the unit only guarantees that each single call is + * atomic on the medium and durable once resolved (a crash after resolution + * followed by a re-open observes the write). Any call after {@link close} + * rejects with `closed`. + */ +export interface KvUnit { + /** + * Read the full current snapshot. + * @returns every table's records keyed by table name, plus the global + * singleton (`null` when never written or not declared). + */ + loadAll(): Promise<{ tables: Record<string, Record<string, unknown>>; global: unknown }> + + /** + * Upsert one record durably. Overwrite semantics: an existing key is replaced. + * @param table - Declared table name. + * @param key - Record key; any string is safe (keys never reach file paths). + * @param value - Opaque JSON-serializable record. + * @returns resolution after durability. + */ + putRecord(table: string, key: string, value: unknown): Promise<void> + + /** + * Delete one record durably. Idempotent: a missing key is a no-op. + * @param table - Declared table name. + * @param key - Record key. + * @returns resolution after durability. + */ + deleteRecord(table: string, key: string): Promise<void> + + /** + * Write the global singleton durably. Only valid when the descriptor + * declared `hasGlobal`. + * @param value - Opaque JSON-serializable value. + * @returns resolution after durability. + */ + setGlobal(value: unknown): Promise<void> + + /** + * Drain this unit's in-flight writes and release it. Idempotent. + * @returns resolution after the unit is released. + */ + close(): Promise<void> +} diff --git a/packages/storage/storage/src/error.ts b/packages/storage/storage/src/error.ts new file mode 100644 index 0000000000..9e3424db55 --- /dev/null +++ b/packages/storage/storage/src/error.ts @@ -0,0 +1,35 @@ +/** + * Error vocabulary for the storage hub and its backends. + * @module @deepseek-ai/dsh-storage/src/error + */ + +/** Discriminant codes carried by every {@link StorageError}. */ +export type StorageErrorCode = + | 'backend-not-found' + | 'form-not-mounted' + | 'duplicate-backend' + | 'duplicate-mount' + | 'version-mismatch' + | 'malformed-medium' + | 'closed' + +/** + * Error thrown by the hub and by backend implementations. The `code` is the + * stable contract consumers may switch on; `message` is diagnostic prose. + */ +export class StorageError extends Error { + override readonly name = 'StorageError' + + /** + * @param code - Stable discriminant for the failure class. + * @param message - Human-readable diagnostic detail. + * @param options - Standard error options (`cause`). + */ + constructor( + readonly code: StorageErrorCode, + message: string, + options?: ErrorOptions, + ) { + super(message, options) + } +} diff --git a/packages/storage/storage/src/index.ts b/packages/storage/storage/src/index.ts new file mode 100644 index 0000000000..15fb70d778 --- /dev/null +++ b/packages/storage/storage/src/index.ts @@ -0,0 +1,86 @@ +/** + * Storage hub (`ctx.storage`): a named backend registry plus mounted + * data-form facilities. The hub itself performs no IO — backends own media, + * data forms (the domain layer first) own semantics. + * @module @deepseek-ai/dsh-storage + */ + +import { Context, Service } from 'cordis' +import { StorageError } from './error.ts' +import { BackendRegistry } from './registry.ts' + +export { BackendRegistry } from './registry.ts' +export { StorageError } from './error.ts' +export type { StorageErrorCode } from './error.ts' +export { UNIT_NAME_RE } from './backend.ts' +export type { StorageBackend, KvFacet, KvUnit, KvUnitDescriptor } from './backend.ts' + +declare module 'cordis' { + interface Context { + storage: Storage + } +} + +/** + * Data forms mountable on the hub, keyed by form name. Form owners extend + * this map via declaration merging (the domain layer merges + * `domain: DomainFacility`) and mount the facility in their `apply`. + */ +export interface StorageForms {} + +/** + * The storage hub service. Backends register under `backend`; data forms + * mount under their `StorageForms` key and are reached as `ctx.storage.<form>`. + */ +export class Storage extends Service { + /** Named backend table; multiple backends stay mounted side by side. */ + readonly backend = new BackendRegistry() + + private readonly forms = new Map<keyof StorageForms, unknown>() + + constructor(ctx: Context) { + super(ctx, 'storage') + } + + /** + * Mount a data-form facility on the hub. Mounting is an effect: the + * returned disposer unmounts the form. + * @param form - Form key declared in {@link StorageForms}. + * @param facility - The facility instance to expose. + * @returns the disposer that unmounts the form. + */ + mount<K extends keyof StorageForms>(form: K, facility: StorageForms[K]): () => void { + if (this.forms.has(form)) { + throw new StorageError('duplicate-mount', `storage form '${String(form)}' is already mounted`) + } + this.forms.set(form, facility) + return () => { + // Same stale-disposer guard as BackendRegistry.register. + if (this.forms.get(form) === facility) { + this.forms.delete(form) + } + } + } + + /** + * Resolve a mounted data form. + * @param form - Form key declared in {@link StorageForms}. + * @returns the mounted facility. + */ + form<K extends keyof StorageForms>(form: K): StorageForms[K] { + if (!this.forms.has(form)) { + throw new StorageError('form-not-mounted', `storage form '${String(form)}' is not mounted`) + } + return this.forms.get(form) as StorageForms[K] + } + + /** Domain data form; present once the domain layer plugin is loaded. */ + get domain(): StorageForms extends { domain: infer D } ? D : never { + return this.form('domain' as keyof StorageForms) + } +} + +// Service packages default-export their service class and nothing else +// plugin-shaped (packages/AGENTS.md): mixing a default export with a +// function-plugin `apply` makes the Loader drop the plugin namespace. +export default Storage diff --git a/packages/storage/storage/src/invariant.ts b/packages/storage/storage/src/invariant.ts new file mode 100644 index 0000000000..cac811a39a --- /dev/null +++ b/packages/storage/storage/src/invariant.ts @@ -0,0 +1,32 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-storage`. + * @module @deepseek-ai/dsh-storage/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-storage' + +/** Cordis companion plugin name. */ +export const name = 'storage-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: the hub is a pure registration table (names → + * backends, forms → facilities) whose consistency is fully enforced at the + * call sites (duplicate/missing entries fail loud synchronously); it owns no + * event stream or mutable medium to cross-check. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/storage/storage/src/registry.ts b/packages/storage/storage/src/registry.ts new file mode 100644 index 0000000000..136cecc227 --- /dev/null +++ b/packages/storage/storage/src/registry.ts @@ -0,0 +1,62 @@ +/** + * Named backend registry of the storage hub. + * @module @deepseek-ai/dsh-storage/src/registry + */ + +import type { StorageBackend } from './backend.ts' +import { StorageError } from './error.ts' + +/** + * Mutable name → backend table. Multiple backends stay mounted side by side; + * which backend serves which consumer is the consumer's configuration + * (e.g. the domain layer's route table), never a hub-global choice. + */ +export class BackendRegistry { + private readonly backends = new Map<string, StorageBackend>() + + /** + * Register a named backend. Registration is an effect: the returned + * disposer removes the name. Disposal does NOT close the backend — the + * owning plugin closes it after unregistering. + * @param name - Backend name, e.g. `json` or `sqlite`. + * @param backend - The backend instance. + * @returns the disposer that unregisters the name. + */ + register(name: string, backend: StorageBackend): () => void { + if (this.backends.has(name)) { + throw new StorageError('duplicate-backend', `storage backend '${name}' is already registered`) + } + this.backends.set(name, backend) + return () => { + // Remove only this registration's contribution: after dispose + re-register, + // a stale disposer firing again must not remove the successor. + if (this.backends.get(name) === backend) { + this.backends.delete(name) + } + } + } + + /** + * Resolve a backend by name. + * @param name - Registered backend name. + * @returns the backend. + */ + get(name: string): StorageBackend { + const backend = this.backends.get(name) + if (!backend) { + throw new StorageError( + 'backend-not-found', + `storage backend '${name}' is not registered (registered: ${[...this.backends.keys()].join(', ') || 'none'})`, + ) + } + return backend + } + + /** + * Registered backend names, for diagnostics. + * @returns a snapshot array of names. + */ + names(): string[] { + return [...this.backends.keys()] + } +} diff --git a/packages/storage/storage/tests/contract.ts b/packages/storage/storage/tests/contract.ts new file mode 100644 index 0000000000..d173918dce --- /dev/null +++ b/packages/storage/storage/tests/contract.ts @@ -0,0 +1,102 @@ +/** + * Shared KV-backend conformance suite. Each backend's spec file calls + * {@link runKvBackendContract} with a factory bound to its own medium; the + * suite asserts every clause of the `src/backend.ts` contract so both + * backends are held to identical semantics. + * @module + */ + +import { describe, expect, it } from 'vitest' +import type { KvUnitDescriptor, StorageBackend } from '../src/backend.ts' + +/** One conformance run: a fresh backend plus a way to reopen the same medium (crash simulation). */ +export interface KvBackendContractHarness { + /** The backend under test, freshly created over an empty medium. */ + backend: StorageBackend + /** Open a NEW backend instance over the SAME medium, as after a process restart. */ + reopen(): Promise<StorageBackend> +} + +const DESCRIPTOR: KvUnitDescriptor = { + name: 'contract_unit', + version: 3, + tables: ['alpha', 'beta'], + hasGlobal: true, +} + +/** + * Run the shared conformance suite against one backend implementation. + * @param label - Suite label, e.g. `json` / `sqlite`. + * @param create - Factory producing a fresh harness per test. + */ +export function runKvBackendContract(label: string, create: () => Promise<KvBackendContractHarness>) { + describe(`kv backend contract: ${label}`, () => { + it('opens a missing unit as empty and serves loadAll immediately', async () => { + const { backend } = await create() + const unit = await backend.kv!.open(DESCRIPTOR) + const snapshot = await unit.loadAll() + expect(snapshot.tables).toEqual({ alpha: {}, beta: {} }) + expect(snapshot.global).toBeNull() + await backend.close() + }) + + it('round-trips records and global durably across reopen', async () => { + const harness = await create() + const unit = await harness.backend.kv!.open(DESCRIPTOR) + await unit.putRecord('alpha', 'k1', { n: 1 }) + await unit.putRecord('alpha', 'k2', { n: 2 }) + await unit.putRecord('beta', 'weird key / with:stuff', { ok: true }) + await unit.setGlobal({ counter: 7 }) + await harness.backend.close() + + const reopened = await harness.reopen() + const unit2 = await reopened.kv!.open(DESCRIPTOR) + const snapshot = await unit2.loadAll() + expect(snapshot.tables['alpha']).toEqual({ k1: { n: 1 }, k2: { n: 2 } }) + expect(snapshot.tables['beta']).toEqual({ 'weird key / with:stuff': { ok: true } }) + expect(snapshot.global).toEqual({ counter: 7 }) + await reopened.close() + }) + + it('putRecord overwrites and deleteRecord is idempotent', async () => { + const { backend } = await create() + const unit = await backend.kv!.open(DESCRIPTOR) + await unit.putRecord('alpha', 'k', { v: 'old' }) + await unit.putRecord('alpha', 'k', { v: 'new' }) + await unit.deleteRecord('alpha', 'k') + await unit.deleteRecord('alpha', 'k') + await unit.deleteRecord('alpha', 'never-existed') + const snapshot = await unit.loadAll() + expect(snapshot.tables['alpha']).toEqual({}) + await backend.close() + }) + + it('rejects a version mismatch on reopen without touching the data', async () => { + const harness = await create() + const unit = await harness.backend.kv!.open(DESCRIPTOR) + await unit.putRecord('alpha', 'k', { v: 1 }) + await harness.backend.close() + + const reopened = await harness.reopen() + await expect(reopened.kv!.open({ ...DESCRIPTOR, version: 4 })).rejects.toMatchObject({ + name: 'StorageError', + code: 'version-mismatch', + }) + // Original version still opens and still holds the data. + const unit2 = await reopened.kv!.open(DESCRIPTOR) + expect((await unit2.loadAll()).tables['alpha']).toEqual({ k: { v: 1 } }) + await reopened.close() + }) + + it('rejects operations after unit close, and close is idempotent', async () => { + const { backend } = await create() + const unit = await backend.kv!.open(DESCRIPTOR) + await unit.close() + await unit.close() + await expect(unit.putRecord('alpha', 'k', {})).rejects.toMatchObject({ code: 'closed' }) + await expect(unit.loadAll()).rejects.toMatchObject({ code: 'closed' }) + await backend.close() + await backend.close() + }) + }) +} diff --git a/packages/storage/storage/tests/registry.spec.ts b/packages/storage/storage/tests/registry.spec.ts new file mode 100644 index 0000000000..413bbe914c --- /dev/null +++ b/packages/storage/storage/tests/registry.spec.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import Storage, { BackendRegistry } from '../src/index.ts' +import type { StorageBackend } from '../src/index.ts' + +const fakeBackend = (): StorageBackend => ({ close: async () => {} }) + +describe('BackendRegistry', () => { + it('registers, resolves, and disposes names', () => { + const registry = new BackendRegistry() + const backend = fakeBackend() + const dispose = registry.register('json', backend) + expect(registry.get('json')).toBe(backend) + expect(registry.names()).toEqual(['json']) + dispose() + expect(registry.names()).toEqual([]) + expect(() => registry.get('json')).toThrowMatchingObject({ code: 'backend-not-found' }) + }) + + it('rejects duplicate names', () => { + const registry = new BackendRegistry() + registry.register('json', fakeBackend()) + expect(() => registry.register('json', fakeBackend())).toThrowMatchingObject({ code: 'duplicate-backend' }) + }) +}) + +describe('Storage service', () => { + it('mounts on the context and exposes registry plus form mounting', async () => { + const ctx = new Context() + await ctx.plugin(Storage) + expect(ctx.storage).toBeInstanceOf(Storage) + + const facility = { marker: true } + const dispose = ctx.storage.mount('domain' as never, facility as never) + expect(ctx.storage.form('domain' as never)).toBe(facility) + expect(ctx.storage.domain).toBe(facility) + expect(() => ctx.storage.mount('domain' as never, facility as never)).toThrowMatchingObject({ + code: 'duplicate-mount', + }) + dispose() + expect(() => ctx.storage.form('domain' as never)).toThrowMatchingObject({ code: 'form-not-mounted' }) + expect(() => ctx.storage.domain).toThrowMatchingObject({ code: 'form-not-mounted' }) + }) + + it('ignores a stale disposer after dispose and re-mount / re-register', async () => { + const ctx = new Context() + await ctx.plugin(Storage) + const first = { first: true } + const second = { second: true } + const staleMount = ctx.storage.mount('domain' as never, first as never) + staleMount() + ctx.storage.mount('domain' as never, second as never) + staleMount() + expect(ctx.storage.form('domain' as never)).toBe(second) + + const backendA = fakeBackend() + const backendB = fakeBackend() + const staleRegister = ctx.storage.backend.register('json', backendA) + staleRegister() + ctx.storage.backend.register('json', backendB) + staleRegister() + expect(ctx.storage.backend.get('json')).toBe(backendB) + }) +}) + +expect.extend({ + toThrowMatchingObject(received: () => unknown, expected: object) { + try { + received() + } catch (error) { + const pass = Object.entries(expected).every( + entry => (error as Record<string, unknown>)[entry[0]] === entry[1], + ) + return { pass, message: () => `expected thrown error to match ${JSON.stringify(expected)}, got ${String(error)}` } + } + return { pass: false, message: () => 'expected function to throw' } + }, +}) + +declare module 'vitest' { + interface Assertion<T> { + toThrowMatchingObject(expected: object): T + } +} diff --git a/packages/storage/storage/tsconfig.json b/packages/storage/storage/tsconfig.json new file mode 100644 index 0000000000..9966c8ca8a --- /dev/null +++ b/packages/storage/storage/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/subagent/subagent-acp/README.md b/packages/subagent/subagent-acp/README.md index 59f4c4787b..45d9abe2b8 100644 --- a/packages/subagent/subagent-acp/README.md +++ b/packages/subagent/subagent-acp/README.md @@ -96,6 +96,6 @@ Append-only; newly visible content follows the reusable request prefix and does - **A fresh process per run** — persistent-process pooling is a future optimization ([the seam Agent Note](../../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md)). - **Local workspaces only** — the resolved cwd is a local path handed to a child on the same machine; workspace mapping for a remote ACP agent would need its own backend capability and is not designed here. - **No optional start-time capabilities** — this provider cannot apply the local harness's `outputSchema`, depth cap, tool filter, or persona inside the remote process, so it advertises none and the service rejects requests that require them. -- **Only `agent_message_chunk` text is collected** — the child's tool-call activity, thought chunks, and plan updates are not surfaced to the parent. +- **Only committed `agent_message_chunk` text is collected** — the automation server keeps reasoning, tool activity, plans, and other trace data in the child session log rather than emitting them on ACP. - **Permission prompts are auto-answered** (`permission: allow | reject`) — no human is surfaced a child's `session/request_permission` in this cut. - **No snapshot-tier replay coverage** (`TODO(acp-subagent-replay)`) — an ACP child is its own process with its own replay shape, deferred. diff --git a/packages/support/acp-snapshot/README.md b/packages/support/acp-snapshot/README.md index 05a4974c19..9732513dc3 100644 --- a/packages/support/acp-snapshot/README.md +++ b/packages/support/acp-snapshot/README.md @@ -6,7 +6,7 @@ Four layers, importable separately: - **`launchAcpTestAgent` (launcher)** — boots a source agent under tsx or a built `lib` agent under plain Node from a supplied cwd, connects the SDK client over a raw-byte stdout tee, collects session updates and stderr, surfaces asynchronous spawn failures through startup, fails closed on unhandled permission requests, and owns graceful or signalled shutdown. Shutdown waits for process exit, inherited stdio closure, and ACP parser exhaustion before resolving or propagating a child error, so captures are complete and callers can remove owned paths after either outcome. When Windows accepts forced termination but publishes its exit marker asynchronously, shutdown gives that marker a bounded grace before treating fallback refusal as a second failure. Snapshot and ordinary e2e suites share this process boundary; a test supplies only agent paths, cwd, environment overrides, and any permission policy. - **`runScenario` (harness)** — drives ACP JSON-RPC stdio from a deterministic `input.json` script through the launcher, tees raw stdout for the expected-output and purity checks, and harvests every persisted raw JSONL session log (parent and subagent children, primary-first) after graceful stdin EOF. `AgentUnderTest` supplies absolute `binScript`, optional `libBinScript`, `configPath`, and `tsconfigPath` paths because the subprocess cwd is outside the repo; `workspaceParent` may move the generated child cwd from the platform temp directory when that grant is itself under test. Startup failures preserve captured agent stderr in the rejected diagnostic. -- **Normalizers** — pure functions turning the two captured surfaces into stable text: `normalizeStdout` (JSON-RPC ids → first-seen sequence; UUIDs/cwd → tokens; cwd-rooted separators selected as canonical `/` or host-native; `session_info_update.updatedAt` → `{{updatedAt}}`; doubles as the stdout-purity check), `normalizeSessionLog` (times zeroed, `seq` kept, the same cwd-path policy), `scrubSystemPrompts` (prompt text → `{{system}}`), `scrubToolSchemas` (schema bulk → `{{tools}}`), and `scrubRequestHeaders` (all header bulk → `{{system}}`/`{{tools}}`/`{{messagePrefix}}` outside each pin, structure kept — [pinned-header Agent Note](../../../.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)). +- **Normalizers** — pure functions turning the two captured surfaces into stable text: `normalizeStdout` (JSON-RPC ids → first-seen sequence; UUIDs and every native/JavaScript filesystem spelling of the generated cwd → tokens, longest-first; cwd-rooted separators selected as canonical `/` or host-native; doubles as the stdout-purity check), `normalizeSessionLog` (times zeroed, `seq` kept, the same cwd-path policy), `scrubSystemPrompts` (prompt text → `{{system}}`), `scrubToolSchemas` (schema bulk → `{{tools}}`), and `scrubRequestHeaders` (all header bulk → `{{system}}`/`{{tools}}`/`{{messagePrefix}}` outside each pin, structure kept — [pinned-header Agent Note](../../../.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)). - **`defineAcpSnapshotSuite` (factory)** — registers the whole describe/it tree for a scenario table: per-scenario expected-output and re-persisted-log comparisons, record/refresh fixture write-back, rejection of structured `UNKNOWN_TOOL` results, the per-header-class pin (`system-prompt.expected.md` plus `tool-schemas.expected.json`) with its live uniformity guard, and the fixture guard block (no orphan scenario dirs, required files present, exactly one pin per class, every JSONL prompt/schema-scrubbed, non-pinning fixtures fully header-scrubbed). Refresh expands packed timing envelopes before aligning existing volatile event times, so switching between packed and unpacked layouts cannot shift later records; fresh chunk-fragment arrays remain authoritative. A newly inserted `session/title` receives its preceding event's time so feature-driven insertions do not churn the remainder of a fixture. Each scenario directory's `session.jsonl` plus contiguous `session.<n>.jsonl` siblings are the ordered primary/child inventory; the scenario table does not duplicate their count. Must be called at vitest collection time. A consuming `*.snapshot.ts` is the scenario table plus one factory call: @@ -14,7 +14,22 @@ A consuming `*.snapshot.ts` is the scenario table plus one factory call: ```ts import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { defineAcpSnapshotSuite, type Scenario } from '@deepseek-ai/dsh-acp-snapshot' +import { + defineAcpSnapshotSuite, + type Scenario, + type SnapshotSuiteOptions, +} from '@deepseek-ai/dsh-acp-snapshot' + +function snapshotMode(value: string | undefined): SnapshotSuiteOptions['mode'] { + switch (value) { + case undefined: + case '': + case 'replay': return 'replay' + case 'record': return 'record' + case 'refresh': return 'refresh' + default: throw new Error(`unknown DSH_SNAPSHOT mode: ${value}`) + } +} const SCENARIOS: Scenario[] = [ { name: 'text-turn', hasModelTurn: true, recorded: true, pinsHeader: true }, @@ -28,11 +43,7 @@ defineAcpSnapshotSuite({ }, snapshotsDir: join(dirname(fileURLToPath(import.meta.url)), 'snapshots'), scenarios: SCENARIOS, // exactly one entry per header class sets pinsHeader - mode: process.env.DSH_SNAPSHOT === 'record' - ? 'record' - : process.env.DSH_SNAPSHOT === 'refresh' - ? 'refresh' - : 'replay', + mode: snapshotMode(process.env.DSH_SNAPSHOT), }) ``` @@ -42,7 +53,7 @@ Every scenario compares `stdout.expected.jsonl` with cwd-rooted separators canon The example also ships a `cordis.snapshot.yml` replay overlay next to its `cordis.yml` (the bin swaps them under `DSH_SNAPSHOT=replay` — [single-source replay config Agent Note](../../../.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.md)); replay fixtures are served by [`dsh-llm-replay`](../llm-replay/README.md), which this package points at via the `DSH_SNAPSHOT_*` env vars it sets on the child. `pnpm run test:snapshot:record` calls the live LLM and rewrites the recorded scenarios' model fixtures; `pnpm run test:snapshot:refresh` stays keyless, runs the replay overlay, and rewrites stdout, comparable session-log expected outputs, and each pin's prompt and tool-schema sidecars from the committed model scripts. Fixture roles, record/replay/refresh semantics, and scenario-table fields are documented on `Scenario` and in the [snapshot Agent Note](../../../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md). -Constraints: `suite.ts` imports vitest, so the package entry is importable only inside a vitest run (the launcher, harness, and normalizers have no such dependency but ship from the same entry). ACP-specific by design — the launcher speaks the SDK's `ClientSideConnection`. Permission round-trips are scriptable: `InputScript.permissionAnswers` is a FIFO queue of option-kind selections (`allow_once`, `reject_once`, …) the client maps to the agent-issued `optionId` at answer time; an absent or exhausted queue answers `cancelled`, and a kind the request never offered rejects the run (the agent is answered `cancelled`, so a tolerant agent cannot absorb the scenario bug). Session config options are scriptable too: the `setConfigOption` step switches a knob over `session/set_config_option`, and `setConfigOptionExpectError` asserts the bridge rejects an unknown id or out-of-vocabulary value (the error frame stays in the transcript). +Constraints: `suite.ts` imports vitest, so the package entry is importable only inside a vitest run (the launcher, harness, and normalizers have no such dependency but ship from the same entry). ACP-specific by design — the launcher speaks the SDK's `ClientSideConnection`. Input scripts cover initialization, fresh-session creation, text prompting, cancellation, expected RPC failures, and durable turn-boundary waits. Permission round-trips are a FIFO queue of option-kind selections (`allow_once`, `reject_once`, …) mapped to the agent-issued `optionId`; an absent or exhausted queue answers `cancelled`, and an unoffered kind rejects the run. ## Model Experience @@ -56,3 +67,4 @@ None; this package neither assembles nor sends a provider request. - **Session harvest requires raw JSONL mode** — `runScenario` collects persisted `.jsonl` logs, so snapshot configs set `persistenceCompression: 'none'`; compressed JSONL and SQLite compositions have no snapshot-harvest path. - **Built mode requires current artifacts** — run `pnpm run build` before selecting `DSH_EXAMPLE_MODE=lib`; source mode remains the zero-build path. +- **Backend coverage still rides an ACP driver** — see the [automation-only ACP decision](../../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md#snapshot-boundary) for why retained scenarios use this transport. diff --git a/packages/support/acp-snapshot/src/harness.ts b/packages/support/acp-snapshot/src/harness.ts index 2821969457..b2f229c875 100644 --- a/packages/support/acp-snapshot/src/harness.ts +++ b/packages/support/acp-snapshot/src/harness.ts @@ -17,7 +17,7 @@ */ import { cp, mkdtemp, readFile, readdir, rm } from 'node:fs/promises' -import { existsSync } from 'node:fs' +import { existsSync, realpathSync } from 'node:fs' import { createHash } from 'node:crypto' import { tmpdir } from 'node:os' import { basename, dirname, join, delimiter } from 'node:path' @@ -25,8 +25,6 @@ import { setTimeout as delay } from 'node:timers/promises' import { ClientSideConnection, PROTOCOL_VERSION, - type CreateElicitationRequest, - type CreateElicitationResponse, type RequestPermissionRequest, type RequestPermissionResponse, type SessionNotification, @@ -44,18 +42,19 @@ const WAIT_POLL_INTERVAL_MS = 10 * (random) session id into a `{{sessionId}}` variable that later steps * reference, since a committed file cannot know the id in advance. * - * `promptAndCancel` starts a prompt without awaiting completion, waits until - * the client observes the selected update (`agent_message_chunk` by default), - * then cancels and awaits completion. An optional `waitForFile` first observes - * a cwd-relative readiness marker, and a named `waitForToolCallUpdate` keeps - * the step open for a terminal tool update that may follow the prompt response. + * `promptAndCancel` starts a prompt without awaiting completion, waits for a + * readiness condition, then cancels and awaits completion. `waitForFile` + * observes a cwd-relative marker; the default observes the durable turn start. * `promptAndWaitForAgentMessage` arms an exact text-chunk waiter before sending * the prompt, then keeps the application live until that later update arrives. - * `waitForTurnEnd` holds the subprocess open until the selected session's latest - * complete raw-JSONL turn boundary is `turn/end`; its timeout defaults to 10s. + * `waitForTurnStart` waits for an open durable turn, optionally at or beyond a + * specified turn number. `waitForTurnEnd` holds the subprocess open until the + * selected session's latest complete raw-JSONL turn boundary is `turn/end`. + * A standalone `cancel` may also wait for a cwd-relative readiness marker. + * All wait timeouts default to 10s. */ export type InputStep = - | { op: 'initialize'; terminalOutput?: boolean } + | { op: 'initialize' } | { op: 'newSession' } | { op: 'newSessionExpectError'; additionalDirectories?: string[] } | { op: 'prompt'; text: string } @@ -64,16 +63,11 @@ export type InputStep = | { op: 'promptAndCancel' text: string - afterUpdate?: 'agent_message_chunk' | 'tool_call' waitForFile?: { path: string; timeoutMs?: number } - waitForToolCallUpdate?: string } + | { op: 'waitForTurnStart'; minimumTurn?: number; timeoutMs?: number } | { op: 'waitForTurnEnd'; timeoutMs?: number } - | { op: 'cancel' } - | { op: 'setMode'; modeId: string } - | { op: 'setModeExpectError'; modeId: string } - | { op: 'setConfigOption'; configId: string; value: string } - | { op: 'setConfigOptionExpectError'; configId: string; value: string } + | { op: 'cancel'; waitForFile?: { path: string; timeoutMs?: number } } /** A scenario's `input.json`: an ordered list of input steps. */ export interface InputScript { @@ -86,21 +80,11 @@ export interface InputScript { * kind → the offered `optionId` at answer time. A request beyond the queue * (or with no queue at all) is answered `cancelled` — the stub behavior a * scenario without approvals relies on. A scripted kind the request does - * not offer REJECTS the run: the scenario scripted an impossible click, + * not offer REJECTS the run: the scenario scripted an impossible selection, * and {@link runScenario} throws once the in-flight step settles (the * agent itself just sees `cancelled`, so it cannot absorb the bug). */ permissionAnswers?: PermissionAnswer[] - /** - * Ordered answers for the agent's `elicitation/create` round-trips (the - * ask_user_question / plan-review forms), consumed FIFO — the Nth request - * gets the Nth answer. Exhaustion (or no queue) answers `cancel`, the same - * fail-closed stub an elicitation-free scenario relies on. Unlike permission - * kinds, the scripted strings are not validated against the offered form — - * a stray `choice` reaches the agent verbatim, which reads it as a custom - * (non-consenting) answer, so a scenario bug fails safe in the transcript. - */ - elicitationAnswers?: ElicitationAnswer[] } /** One scripted answer to a permission request: which offered option kind to select. */ @@ -109,16 +93,6 @@ export interface PermissionAnswer { kind: 'allow_once' | 'allow_always' | 'reject_once' | 'reject_always' } -/** One scripted answer to an elicitation form (accept with choice/custom content, or cancel). */ -export interface ElicitationAnswer { - /** Accept the form with the content below, or cancel it. */ - action: 'accept' | 'cancel' - /** The selected option label (the form's `choice` field). */ - choice?: string - /** Free-form text (the form's `custom` field). */ - custom?: string -} - /** One harvested session log plus the identifying facts off its header line. */ export interface HarvestedLog { /** The recorded session id (header `id`). */ @@ -141,6 +115,8 @@ export interface RunResult { sessionId?: string /** The generated cwd the session ran in (the bash workspace). */ cwd: string + /** Filesystem-resolved spellings of {@link cwd} that child processes may report. */ + cwdAliases: string[] /** * Every persisted session log harvested after the run, ordered primary-first: * the top-level (parent) session — the one with no `parentSession` — then each @@ -156,6 +132,8 @@ export interface RunOptions { agent: AgentUnderTest /** `replay` (default, keyless) or `record` (real API, harvests the log). */ mode: 'replay' | 'record' + /** Scenario-specific deployment environment layered into the subprocess. */ + env?: NodeJS.ProcessEnv /** The recorded session JSONL fixture path (replay reads it; record writes near it). */ fixtureFile: string /** Optional sidecar override path (replay). */ @@ -222,6 +200,7 @@ export function snapshotSpillRoot( */ export async function runScenario(input: InputScript, opts: RunOptions): Promise<RunResult> { const cwd = await mkdtemp(join(opts.workspaceParent ?? tmpdir(), 'acp-snap-cwd-')) + const cwdAliases = [...new Set([realpathSync(cwd), realpathSync.native(cwd)])] const sessionsRoot = await mkdtemp(join(tmpdir(), 'acp-snap-sessions-')) // Fixed path length: spill-policy budgets the preview against the REAL path // before stdout normalization, so tmpdir() length differences churn expected outputs. @@ -241,6 +220,7 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise await cp(opts.workspaceDir, cwd, { recursive: true }) } const env: NodeJS.ProcessEnv = { + ...opts.env, DSH_SNAPSHOT: opts.mode, DSH_SNAPSHOT_FILE: opts.fixtureFile, DSH_SNAPSHOT_SESSIONS_ROOT: sessionsRoot, @@ -256,13 +236,11 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise // Permission answers are consumed FIFO across the whole run; exhaustion // falls back to `cancelled` so approval-free scenarios keep the plain stub. const permissionQueue = [...input.permissionAnswers ?? []] - // Elicitation answers mirror the permission queue: FIFO, cancel on exhaustion. - const elicitationQueue = [...input.elicitationAnswers ?? []] // A scenario bug detected inside a client callback (a scripted permission // kind the agent never offered). It cannot fail the run from in there: a // callback throw only becomes a JSON-RPC error RESPONSE to the agent, and // a tolerant agent treats that as a denial and carries on — the run (or - // worse, a record) would absorb the impossible click silently. So the + // worse, a record) would absorb the impossible selection silently. So the // callback answers `cancelled` (a well-defined path for the agent), // captures the error here, and the step loop fails the run on it. let scriptError: Error | undefined @@ -276,7 +254,7 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise if (answer === undefined) return Promise.resolve({ outcome: { outcome: 'cancelled' } }) const option = params.options.find(o => o.kind === answer.kind) if (option === undefined) { - // The scenario scripted a click the agent never offered — a scenario + // The scenario scripted a selection the agent never offered — a scenario // bug. Captured (last one wins; same bug class either way) and // answered `cancelled`; the step loop rejects the run on it. scriptError = new Error( @@ -287,17 +265,6 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise } return Promise.resolve({ outcome: { outcome: 'selected', optionId: option.optionId } }) }, - createElicitation(_params: CreateElicitationRequest): Promise<CreateElicitationResponse> { - const answer = elicitationQueue.shift() - if (answer === undefined || answer.action !== 'accept') return Promise.resolve({ action: 'cancel' }) - return Promise.resolve({ - action: 'accept', - content: { - ...answer.choice !== undefined ? { choice: answer.choice } : {}, - ...answer.custom !== undefined ? { custom: answer.custom } : {}, - }, - }) - }, }) const active = launched await active.spawned @@ -311,6 +278,7 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise match => active.waitForUpdate(match), () => sessionId, (id) => { sessionId = id }, + (id, timeoutMs, minimumTurn) => waitForPersistedTurnStart(sessionsRoot, id, timeoutMs, minimumTurn), (id, timeoutMs) => waitForPersistedTurnEnd(sessionsRoot, id, timeoutMs), ) // A permission exchange happens while a step's request is in flight, so @@ -329,6 +297,7 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise rawStdout: launched.rawStdout(), stderr: launched.stderr(), cwd, + cwdAliases, ...sessionId !== undefined ? { sessionId } : {}, sessionLogs, } @@ -382,13 +351,14 @@ async function runStep( waitForUpdate: (match: (u: SessionNotification['update']) => boolean) => Promise<SessionNotification['update']>, getSessionId: () => string | undefined, setSessionId: (id: string) => void, + waitForTurnStart: (sessionId: string, timeoutMs?: number, minimumTurn?: number) => Promise<void>, waitForTurnEnd: (sessionId: string, timeoutMs?: number) => Promise<void>, ): Promise<void> { switch (step.op) { case 'initialize': await client.initialize({ protocolVersion: PROTOCOL_VERSION, - clientCapabilities: step.terminalOutput === true ? { _meta: { terminal_output: true } } : {}, + clientCapabilities: {}, }) return case 'newSession': { @@ -431,7 +401,7 @@ async function runStep( if (sessionId === undefined) throw new Error('snapshot-harness: promptExpectError before newSession') // The model fails this turn (a recorded provider error), so the bridge // answers the prompt with a JSON-RPC error and the SDK rejects. That - // rejection IS the expected editor experience — swallow it so the run + // rejection IS the expected protocol result — swallow it so the run // completes and the stdout transcript (the error frame) is captured. await client.prompt({ sessionId, prompt: [{ type: 'text', text: step.text }] }) .then(() => { throw new Error('snapshot-harness: expected the prompt to fail but it succeeded') }, @@ -442,21 +412,16 @@ async function runStep( const sessionId = getSessionId() if (sessionId === undefined) throw new Error('snapshot-harness: promptAndCancel before newSession') // Dispatch without awaiting because the fixture does not settle on its - // own. Waiting for the selected update pins it before cancellation and - // the cancelled prompt response in the transcript. + // own. Wait for an external readiness marker or the durable turn start + // before sending cancellation. const promptDone = client.prompt({ sessionId, prompt: [{ type: 'text', text: step.text }] }) - const afterUpdate = step.afterUpdate ?? 'agent_message_chunk' - await waitForUpdate(u => u.sessionUpdate === afterUpdate) if (step.waitForFile !== undefined) { await waitForWorkspaceFile(cwd, step.waitForFile.path, step.waitForFile.timeoutMs) + } else { + await waitForTurnStart(sessionId) } - // Arm this before cancellation so a fast tool drain cannot outrun the waiter. - const toolCallUpdateDone = step.waitForToolCallUpdate === undefined - ? undefined - : waitForUpdate(u => u.sessionUpdate === 'tool_call_update' && u.toolCallId === step.waitForToolCallUpdate) await client.cancel({ sessionId }) await promptDone - if (toolCallUpdateDone !== undefined) await toolCallUpdateDone return } case 'waitForTurnEnd': { @@ -465,53 +430,46 @@ async function runStep( await waitForTurnEnd(sessionId, step.timeoutMs) return } + case 'waitForTurnStart': { + const sessionId = getSessionId() + if (sessionId === undefined) throw new Error('snapshot-harness: waitForTurnStart before newSession') + await waitForTurnStart(sessionId, step.timeoutMs, step.minimumTurn) + return + } case 'cancel': { const sessionId = getSessionId() if (sessionId === undefined) throw new Error('snapshot-harness: cancel before newSession') + if (step.waitForFile !== undefined) { + await waitForWorkspaceFile(cwd, step.waitForFile.path, step.waitForFile.timeoutMs) + } await client.cancel({ sessionId }) return } - case 'setMode': { - const sessionId = getSessionId() - if (sessionId === undefined) throw new Error('snapshot-harness: setMode before newSession') - await client.setSessionMode({ sessionId, modeId: step.modeId }) - return - } - case 'setModeExpectError': { - const sessionId = getSessionId() - if (sessionId === undefined) throw new Error('snapshot-harness: setModeExpectError before newSession') - // The bridge rejects an unknown/uncomposed mode id with invalidParams; - // that rejection IS the expected wire behavior — swallow it so the run - // completes and the error frame is captured in the transcript. - await client.setSessionMode({ sessionId, modeId: step.modeId }).then( - () => { throw new Error('snapshot-harness: expected session/set_mode to be rejected but it succeeded') }, - () => { /* expected: the bridge rejected the mode id */ }, - ) - return - } - case 'setConfigOption': { - const sessionId = getSessionId() - if (sessionId === undefined) throw new Error('snapshot-harness: setConfigOption before newSession') - await client.setSessionConfigOption({ sessionId, configId: step.configId, value: step.value }) - return - } - case 'setConfigOptionExpectError': { - const sessionId = getSessionId() - if (sessionId === undefined) throw new Error('snapshot-harness: setConfigOptionExpectError before newSession') - // The bridge rejects an unknown id / out-of-vocabulary value; the SDK - // surfaces that as a rejected RPC — swallow it so the run completes and - // the error frame is captured in the transcript. - await client.setSessionConfigOption({ sessionId, configId: step.configId, value: step.value }).then( - () => { throw new Error('snapshot-harness: expected set_config_option to be rejected but it succeeded') }, - () => { /* expected: the bridge rejected the id or value */ }, - ) - return - } default: throw new Error(`snapshot-harness: unknown input op ${JSON.stringify(step)}`) } } +/** Wait until persistence exposes an open turn for the selected session. */ +async function waitForPersistedTurnStart( + root: string, + sessionId: string, + timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, + minimumTurn?: number, +): Promise<void> { + const deadline = Date.now() + timeoutMs + while (true) { + const log = (await harvestSessionLogs(root)).find(candidate => candidate.id === sessionId) + const openTurn = log === undefined ? undefined : latestOpenTurn(log.content) + if (openTurn !== undefined && (minimumTurn === undefined || openTurn >= minimumTurn)) return + if (Date.now() >= deadline) { + const detail = minimumTurn === undefined ? 'turn/start' : `turn/start at or beyond turn ${minimumTurn}` + throw new Error(`snapshot-harness: session "${sessionId}" did not persist ${detail} within ${timeoutMs}ms`) + } + await delay(WAIT_POLL_INTERVAL_MS) + } +} + /** * Wait until the raw JSONL backend exposes one complete closing turn boundary. * The ACP cancel notification settles its prompt before the agent necessarily @@ -557,6 +515,20 @@ function latestTurnIsClosed(content: string): boolean { > complete.lastIndexOf('\n{"type":"turn/start",') } +/** Return the latest open turn number, validating the persisted boundary record. */ +function latestOpenTurn(content: string): number | undefined { + const complete = content.slice(0, content.lastIndexOf('\n') + 1) + const start = complete.lastIndexOf('\n{"type":"turn/start",') + if (start <= complete.lastIndexOf('\n{"type":"turn/end",')) return undefined + const end = complete.indexOf('\n', start + 1) + const record = JSON.parse(complete.slice(start + 1, end)) as { data?: { turn?: unknown } | null } + const turn = record.data?.turn + if (!Number.isSafeInteger(turn) || (turn as number) < 1) { + throw new Error('snapshot-harness: invalid persisted turn/start record') + } + return turn as number +} + /** * Harvest EVERY persisted `.jsonl` session log under a sessions root, parse each * header line, and return them ordered primary-first: the top-level session (no diff --git a/packages/support/acp-snapshot/src/index.ts b/packages/support/acp-snapshot/src/index.ts index 53e7b0d5f9..2a03947fef 100644 --- a/packages/support/acp-snapshot/src/index.ts +++ b/packages/support/acp-snapshot/src/index.ts @@ -18,7 +18,6 @@ export { runScenario, - type ElicitationAnswer, type HarvestedLog, type InputScript, type InputStep, diff --git a/packages/support/acp-snapshot/src/launcher.ts b/packages/support/acp-snapshot/src/launcher.ts index d10d05c15b..441ab463d7 100644 --- a/packages/support/acp-snapshot/src/launcher.ts +++ b/packages/support/acp-snapshot/src/launcher.ts @@ -15,8 +15,6 @@ import { ndJsonStream, type Agent as AcpAgent, type Client, - type CreateElicitationRequest, - type CreateElicitationResponse, type RequestPermissionRequest, type RequestPermissionResponse, type SessionNotification, @@ -49,8 +47,6 @@ export interface AcpTestLaunchOptions { env?: NodeJS.ProcessEnv /** Permission handler; omitted requests fail closed as `cancelled`. */ requestPermission?: (params: RequestPermissionRequest) => Promise<RequestPermissionResponse> - /** Elicitation handler; omitted requests fail closed as `cancel`. */ - createElicitation?: (params: CreateElicitationRequest) => Promise<CreateElicitationResponse> } /** A running ACP test process and its captured client-side surfaces. */ @@ -156,8 +152,6 @@ export function launchAcpTestAgent(options: AcpTestLaunchOptions): LaunchedAcpTe } const requestPermission = options.requestPermission ?? (() => Promise.resolve({ outcome: { outcome: 'cancelled' as const } })) - const createElicitation = options.createElicitation - ?? (() => Promise.resolve({ action: 'cancel' as const })) const makeClient = (_agent: AcpAgent): Client => ({ sessionUpdate(params: SessionNotification): Promise<void> { return trackClientCallback(() => { @@ -181,7 +175,6 @@ export function launchAcpTestAgent(options: AcpTestLaunchOptions): LaunchedAcpTe }) }, requestPermission: params => trackClientCallback(() => requestPermission(params)), - unstable_createElicitation: params => trackClientCallback(() => createElicitation(params)), }) const client = new ClientSideConnection(makeClient, stream) // `exit` only reports the parent process's status. Descendants may retain diff --git a/packages/support/acp-snapshot/src/normalize.ts b/packages/support/acp-snapshot/src/normalize.ts index f21340bc59..0dabbfdff2 100644 --- a/packages/support/acp-snapshot/src/normalize.ts +++ b/packages/support/acp-snapshot/src/normalize.ts @@ -11,7 +11,6 @@ const CWD = '{{cwd}}' const SYSTEM = '{{system}}' const TOOLS = '{{tools}}' const MESSAGE_PREFIX = '{{messagePrefix}}' -const UPDATED_AT = '{{updatedAt}}' const EVENT_TIME = '{{eventTime}}' const EVENT_OMITTED_BYTES = '{{eventOmittedBytes}}' @@ -52,6 +51,8 @@ export interface NormalizeContext { sessionIds: string[] /** The generated cwd the run used — replaced with `{{cwd}}`. */ cwd: string + /** Other filesystem spellings of the same cwd (for example Windows short and long paths). */ + cwdAliases?: readonly string[] } /** How cwd-rooted path separators are represented after the cwd is tokenized. */ @@ -66,9 +67,13 @@ export interface NormalizeOptions { /** Replace cwd, session ids, and any stray UUID with stable tokens in a string. */ function scrubString(value: string, ctx: NormalizeContext, cwdPathMode: CwdPathMode): string { let out = value - // cwd first (longest, most specific), then explicit session ids, then any - // residual UUID (covers ids that appear in places we didn't enumerate). - out = out.split(ctx.cwd).join(CWD) + // Filesystem APIs can report one directory with several spellings. Replace + // every known spelling longest-first so a shorter alias cannot corrupt a + // longer one before it is tokenized. + const cwdSpellings = [...new Set([ctx.cwd, ...ctx.cwdAliases ?? []])] + .filter(spelling => spelling.length > 0) + .sort((left, right) => right.length - left.length) + for (const spelling of cwdSpellings) out = out.split(spelling).join(CWD) out = out.split(`/private${CWD}`).join(CWD) if (cwdPathMode === 'canonical') { // Restrict separator conversion to paths rooted at the cwd token. A global @@ -140,8 +145,6 @@ export function normalizeStdout( if ('id' in frame && frame.id !== undefined && frame.id !== null) { frame.id = stableId(frame.id) } - const update = (frame.params as { update?: Record<string, unknown> } | undefined)?.update - if (update?.sessionUpdate === 'session_info_update') update.updatedAt = UPDATED_AT return scrubValue(frame, ctx, cwdPathMode) as Record<string, unknown> }) return frames.map(f => JSON.stringify(f)).join('\n') + '\n' diff --git a/packages/support/acp-snapshot/src/suite.ts b/packages/support/acp-snapshot/src/suite.ts index 51e958a106..f75e17d36a 100644 --- a/packages/support/acp-snapshot/src/suite.ts +++ b/packages/support/acp-snapshot/src/suite.ts @@ -47,6 +47,8 @@ const PACKED_CHUNK_ROW_TYPES = new Set(['text-chunks', 'reasoning-chunks', 'tool /** A snapshot scenario and how its fixtures are produced. */ export interface Scenario { name: string + /** Deployment environment for this scenario's subprocess. */ + env?: NodeJS.ProcessEnv /** Whether the scenario drives at least one model turn (so a JSONL expected output applies). */ hasModelTurn: boolean /** @@ -604,6 +606,7 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { agent, mode: childMode, fixtureFile: join(dir, 'session.jsonl'), + ...scenario.env !== undefined ? { env: scenario.env } : {}, ...existsSync(overrideFile) ? { overrideFile } : {}, // In REPLAY, forward the recorded child fixtures so each subagent session // replays from its own script. In RECORD they are harvested, not read. @@ -629,6 +632,7 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { ...result.sessionLogs.map(l => l.id), ], cwd: result.cwd, + cwdAliases: result.cwdAliases, } // Record writes live model fixtures; keyless refresh writes every comparable replayed diff --git a/packages/support/acp-snapshot/tests/fixtures/fake-acp-agent.ts b/packages/support/acp-snapshot/tests/fixtures/fake-acp-agent.ts index df3bb0b970..9be693e7ad 100644 --- a/packages/support/acp-snapshot/tests/fixtures/fake-acp-agent.ts +++ b/packages/support/acp-snapshot/tests/fixtures/fake-acp-agent.ts @@ -45,18 +45,10 @@ interface Behavior { rejectExtraDirs?: boolean /** How `session/prompt` settles: a clean response, a JSON-RPC error, or a hang until `session/cancel`. */ prompt?: 'respond' | 'error' | 'hang-until-cancel' - /** Emit a tool call instead of a message chunk before parking a cancellable prompt. */ - cancelAtToolCall?: boolean - /** Emit the parked tool call's terminal update after answering cancellation. */ - cancelToolCallUpdate?: boolean /** Persist the scripted logs while handling cancellation, before stdin EOF. */ persistLogsOnCancel?: boolean /** Before responding to a prompt, send a `session/request_permission` request and echo its outcome as a chunk. */ permissionProbe?: boolean - /** Before responding to a prompt, send an `elicitation/create` request and echo its response as a chunk. */ - elicitationProbe?: boolean - /** How `session/set_mode` settles: an empty response (echoing the modeId as a chunk) or a JSON-RPC error. */ - setMode?: 'respond' | 'error' /** Echo the `DSH_SNAPSHOT_*` env the harness set as a chunk (spec-side env-plumbing assertions). */ echoEnv?: boolean /** Echo the sorted cwd listing as a chunk (spec-side workspace-seeding assertions). */ @@ -73,13 +65,6 @@ interface Behavior { strayBucketFile?: boolean /** Delete the sessions root entirely (harvest must yield no logs). */ deleteSessionsRoot?: boolean - /** - * Vocabulary for `session/set_config_option`: allowed values per config id. - * A set naming an unknown id or an out-of-vocabulary value rejects (the - * real bridge's rule); a valid set answers with the complete refreshed - * option state, `currentValue` updated. Absent: every set rejects. - */ - configOptions?: Record<string, string[]> } const sessionsRoot = process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? '' @@ -102,10 +87,10 @@ let sessionId = '' let sessionCwd = '' /** The parked prompt request id while `hang-until-cancel` waits for the cancel notification. */ let parkedPromptId: number | string | null = null -/** Resolvers for outbound probe responses (permission/elicitation), keyed by request id. */ +/** The transient raw JSONL log that proves the parked turn started durably. */ +let parkedTurnLog: string | undefined +/** Resolvers for outbound permission responses, keyed by request id. */ const pendingOutbound = new Map<number, (result: unknown) => void>() -/** Per-run `session/set_config_option` state: config id → current value (first vocabulary entry until set). */ -const currentConfig: Record<string, string> = {} function send(frame: Record<string, unknown>): void { process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...frame })}\n`) @@ -138,39 +123,34 @@ function instantiate(value: unknown): unknown { return value } +/** Persist an open turn so cancellation tests wait on agent state, not presentation output. */ +function persistParkedTurnStart(): void { + parkedTurnLog = join(sessionsRoot, 'ready', 'open.jsonl') + mkdirSync(dirname(parkedTurnLog), { recursive: true }) + writeFileSync(parkedTurnLog, [ + JSON.stringify({ type: 'session', version: 0, id: sessionId, createdAt: 1, cwd: sessionCwd, delegationDepth: 0 }), + JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }), + '', + ].join('\n')) +} + +/** Remove the transient open-turn log before publishing any scripted final logs. */ +function clearParkedTurnStart(): void { + if (parkedTurnLog === undefined) return + rmSync(parkedTurnLog, { force: true }) + parkedTurnLog = undefined +} + async function handlePrompt(id: number | string): Promise<void> { - if ((behavior.prompt ?? 'respond') === 'hang-until-cancel') { - // A thought chunk BEFORE any message chunk: a promptAndCancel waiter - // watches for agent_message_chunk, so this exercises its non-matching - // update path while the waiter is armed. - send({ - method: 'session/update', - params: { sessionId, update: { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: 'mulling' } } }, - }) - } - if (behavior.cancelAtToolCall === true) { - send({ - method: 'session/update', - params: { - sessionId, - update: { - sessionUpdate: 'tool_call', - toolCallId: 'call_fake_1', - title: 'fake tool', - kind: 'execute', - status: 'in_progress', - }, - }, - }) - } else { - chunk('thinking about it') - } + chunk('thinking about it') if (behavior.echoEnv === true) { chunk(`env:${JSON.stringify({ mode: process.env.DSH_SNAPSHOT, override: process.env.DSH_SNAPSHOT_OVERRIDE ?? null, childFiles: process.env.DSH_SNAPSHOT_CHILD_FILES ?? null, spillRoot: process.env.DSH_SNAPSHOT_SPILL_ROOT ?? null, + // Scenario-supplied deployment env (the `Scenario.env` layering seam). + permissionMode: process.env.DSH_PERMISSION_MODE ?? null, })}`) } if (behavior.echoWorkspace === true) { @@ -185,7 +165,7 @@ async function handlePrompt(id: number | string): Promise<void> { method: 'session/request_permission', params: { sessionId, - toolCall: { toolCallId: 'call_fake_1', title: 'fake tool', kind: 'execute', status: 'pending' }, + toolCall: { toolCallId: 'call_fake_1' }, options: [ { optionId: 'opt-allow', name: 'Allow once', kind: 'allow_once' }, { optionId: 'opt-reject', name: 'Reject once', kind: 'reject_once' }, @@ -195,23 +175,6 @@ async function handlePrompt(id: number | string): Promise<void> { }) chunk(`permission:${JSON.stringify((result as { outcome?: unknown } | undefined)?.outcome ?? null)}`) } - if (behavior.elicitationProbe === true) { - const requestId = nextOutboundId++ - const result = await new Promise<unknown>((resolve) => { - pendingOutbound.set(requestId, resolve) - send({ - id: requestId, - method: 'elicitation/create', - params: { - sessionId, - mode: 'form', - message: 'Approve this plan and leave plan mode?', - requestedSchema: { type: 'object', title: 'Plan review', properties: { choice: { type: 'string' }, custom: { type: 'string' } }, required: [] }, - }, - }) - }) - chunk(`elicitation:${JSON.stringify(result ?? null)}`) - } switch (behavior.prompt ?? 'respond') { case 'respond': respond(id, { stopReason: 'end_turn' }) @@ -220,6 +183,7 @@ async function handlePrompt(id: number | string): Promise<void> { respondError(id, 'model exploded') return case 'hang-until-cancel': + persistParkedTurnStart() parkedPromptId = id return } @@ -254,59 +218,13 @@ function handleFrame(frame: Record<string, unknown>): void { case 'session/prompt': void handlePrompt(id as number | string) return - case 'session/set_mode': - if ((behavior.setMode ?? 'respond') === 'error') { - respondError(id as number | string, 'unknown mode') - return - } - chunk(`setMode:${String(params.modeId)}`) - respond(id as number | string, {}) - return - case 'session/set_config_option': { - const vocabulary = behavior.configOptions - const configId = params.configId as string - const value = params.value as string - const values = vocabulary?.[configId] - if (values === undefined) { - respondError(id as number | string, `unknown config option ${configId}`) - return - } - if (!values.includes(value)) { - respondError(id as number | string, `unknown ${configId} value ${value}`) - return - } - currentConfig[configId] = value - // The real bridge's contract: every set answers with the COMPLETE - // refreshed option state, not just the changed entry. - respond(id as number | string, { - configOptions: Object.entries(vocabulary as Record<string, string[]>).map(([cid, vs]) => ({ - id: cid, - type: 'select', - currentValue: currentConfig[cid] ?? vs[0], - options: vs.map(v => ({ value: v, name: v })), - })), - }) - return - } case 'session/cancel': if (parkedPromptId !== null) { const parked = parkedPromptId parkedPromptId = null - respond(parked, { stopReason: 'cancelled' }) - if (behavior.cancelToolCallUpdate === true) { - send({ - method: 'session/update', - params: { - sessionId, - update: { - sessionUpdate: 'tool_call_update', - toolCallId: 'call_fake_1', - status: 'failed', - }, - }, - }) - } + clearParkedTurnStart() if (behavior.persistLogsOnCancel === true) writeLogs() + respond(parked, { stopReason: 'cancelled' }) } return default: @@ -325,6 +243,7 @@ function writeLogs(): void { } function flushLogsAndExit(): void { + clearParkedTurnStart() writeLogs() if (behavior.strayRootFile === true) writeFileSync(join(sessionsRoot, 'stray.txt'), 'not a bucket\n') if (behavior.strayBucketFile === true) { diff --git a/packages/support/acp-snapshot/tests/harness.spec.ts b/packages/support/acp-snapshot/tests/harness.spec.ts index a87e72d3d4..7c8de992f4 100644 --- a/packages/support/acp-snapshot/tests/harness.spec.ts +++ b/packages/support/acp-snapshot/tests/harness.spec.ts @@ -95,8 +95,8 @@ describe('runScenario', () => { expect(clientClosed).toBe(true) }) - it('centralizes ACP boot, captures, updates, fail-closed interactions, and shutdown', { timeout: 20_000 }, async () => { - const { dir, fixtureFile } = await scenario({ permissionProbe: true, elicitationProbe: true, echoEnv: true, stderrNote: 'launcher stderr' }) + it('centralizes ACP boot, captures, updates, fail-closed permissions, and shutdown', { timeout: 20_000 }, async () => { + const { dir, fixtureFile } = await scenario({ permissionProbe: true, echoEnv: true, stderrNote: 'launcher stderr' }) const sessionsRoot = await mkdtemp(join(tmpdir(), 'acp-launcher-sessions-')) tempDirs.push(sessionsRoot) const launched = launchAcpTestAgent({ @@ -112,6 +112,8 @@ describe('runScenario', () => { await launched.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) const { sessionId } = await launched.client.newSession({ cwd: dir, mcpServers: [] }) const nextChunk = launched.waitForUpdate(update => update.sessionUpdate === 'agent_message_chunk') + const laterChunk = launched.waitForUpdate(update => update.sessionUpdate === 'agent_message_chunk' + && update.content.type === 'text' && update.content.text === 'never this one') const predicateFailure = new Error('predicate failed') const failedPredicate = launched.waitForUpdate(() => { throw predicateFailure }) .catch((error: unknown): unknown => error) @@ -120,8 +122,8 @@ describe('runScenario', () => { expect((await nextChunk).sessionUpdate).toBe('agent_message_chunk') expect(launched.updates.some(update => update.sessionUpdate === 'agent_message_chunk')).toBe(true) expect(launched.rawStdout()).toContain('permission:{\\"outcome\\":\\"cancelled\\"}') - expect(launched.rawStdout()).toContain('elicitation:{\\"action\\":\\"cancel\\"}') expect(launched.stderr()).toContain('launcher stderr') + void laterChunk.catch(() => undefined) const unmatched = expect(launched.waitForUpdate(() => false)).rejects.toThrow(/update stream closed/) await launched.close() await unmatched @@ -374,7 +376,7 @@ describe('runScenario', () => { } }) - it('drives a full turn: initialize (terminal caps), session, prompt, permission stub, harvest', { timeout: 20_000 }, async () => { + it('drives a full turn: initialize, session, prompt, permission stub, harvest', { timeout: 20_000 }, async () => { const { fixtureFile } = await scenario({ permissionProbe: true, logs: [{ @@ -386,7 +388,7 @@ describe('runScenario', () => { }], }) const result = await runScenario( - { steps: [{ op: 'initialize', terminalOutput: true }, { op: 'newSession' }, { op: 'prompt', text: 'go' }] }, + { steps: [{ op: 'initialize' }, { op: 'newSession' }, { op: 'prompt', text: 'go' }] }, { agent: AGENT, mode: 'replay', fixtureFile }, ) expect(result.sessionId).toBeDefined() @@ -482,7 +484,7 @@ describe('runScenario', () => { expect(child.startsWith(`..${sep}`)).toBe(false) }) - it('promptAndCancel waits for the streamed chunk, cancels, and settles the prompt', { timeout: 20_000 }, async () => { + it('promptAndCancel waits for the durable turn start, cancels, and settles the prompt', { timeout: 20_000 }, async () => { const { fixtureFile } = await scenario({ prompt: 'hang-until-cancel' }) const result = await runScenario( { steps: [...boot, { op: 'promptAndCancel', text: 'hang' }] }, @@ -539,28 +541,6 @@ describe('runScenario', () => { expect(result.rawStdout).toContain('thinking about it') }) - it('promptAndCancel can bracket cancellation with tool-call updates', { timeout: 20_000 }, async () => { - const { fixtureFile } = await scenario({ - prompt: 'hang-until-cancel', - cancelAtToolCall: true, - cancelToolCallUpdate: true, - }) - const result = await runScenario( - { - steps: [...boot, { - op: 'promptAndCancel', - text: 'hang', - afterUpdate: 'tool_call', - waitForToolCallUpdate: 'call_fake_1', - }], - }, - { agent: AGENT, mode: 'replay', fixtureFile }, - ) - expect(result.rawStdout).toContain('"sessionUpdate":"tool_call"') - expect(result.rawStdout.indexOf('"sessionUpdate":"tool_call"')).toBeLessThan(result.rawStdout.indexOf('cancelled')) - expect(result.rawStdout.indexOf('cancelled')).toBeLessThan(result.rawStdout.indexOf('"sessionUpdate":"tool_call_update"')) - }) - it('waitForTurnEnd holds cancellation open through the persisted closing boundary', { timeout: 20_000 }, async () => { const { fixtureFile } = await scenario({ prompt: 'hang-until-cancel', @@ -580,6 +560,108 @@ describe('runScenario', () => { expect(result.sessionLogs[0]?.content).toContain('"type":"turn/end"') }) + it('waitForTurnStart can require a later durable turn before continuing', { timeout: 20_000 }, async () => { + const { fixtureFile } = await scenario({ + prompt: 'hang-until-cancel', + persistLogsOnCancel: true, + logs: [{ + file: 'bucket/session.jsonl', + lines: [ + { type: 'session', version: 0, id: '{{SID}}', createdAt: 1, delegationDepth: 0 }, + { type: 'turn/start', seq: 0, time: 1, data: { turn: 3 } }, + ], + }], + }) + const result = await runScenario( + { + steps: [ + ...boot, + { op: 'promptAndCancel', text: 'hang' }, + { op: 'waitForTurnStart', minimumTurn: 3 }, + ], + }, + { agent: AGENT, mode: 'replay', fixtureFile }, + ) + expect(result.sessionLogs[0]?.content).toContain('"turn":3') + }) + + it('waitForTurnStart rejects missing, earlier, and malformed durable turns', { timeout: 20_000 }, async () => { + const missing = await scenario({}) + await expect(runScenario( + { steps: [...boot, { op: 'waitForTurnStart', timeoutMs: 20 }] }, + { agent: AGENT, mode: 'replay', fixtureFile: missing.fixtureFile }, + )).rejects.toThrow(/did not persist turn\/start within 20ms/) + + const earlier = await scenario({ + prompt: 'hang-until-cancel', + persistLogsOnCancel: true, + logs: [{ + file: 'bucket/session.jsonl', + lines: [ + { type: 'session', version: 0, id: '{{SID}}', createdAt: 1, delegationDepth: 0 }, + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + ], + }], + }) + await expect(runScenario( + { + steps: [ + ...boot, + { op: 'promptAndCancel', text: 'hang' }, + { op: 'waitForTurnStart', minimumTurn: 3, timeoutMs: 20 }, + ], + }, + { agent: AGENT, mode: 'replay', fixtureFile: earlier.fixtureFile }, + )).rejects.toThrow(/turn\/start at or beyond turn 3 within 20ms/) + + const closed = await scenario({ + prompt: 'hang-until-cancel', + persistLogsOnCancel: true, + logs: [{ + file: 'bucket/session.jsonl', + lines: [ + { type: 'session', version: 0, id: '{{SID}}', createdAt: 1, delegationDepth: 0 }, + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'stop' } } }, + ], + }], + }) + await expect(runScenario( + { + steps: [ + ...boot, + { op: 'promptAndCancel', text: 'hang' }, + { op: 'waitForTurnStart', timeoutMs: 20 }, + ], + }, + { agent: AGENT, mode: 'replay', fixtureFile: closed.fixtureFile }, + )).rejects.toThrow(/did not persist turn\/start within 20ms/) + + for (const turn of [undefined, 0]) { + const malformed = await scenario({ + prompt: 'hang-until-cancel', + persistLogsOnCancel: true, + logs: [{ + file: 'bucket/session.jsonl', + lines: [ + { type: 'session', version: 0, id: '{{SID}}', createdAt: 1, delegationDepth: 0 }, + { type: 'turn/start', seq: 0, time: 1, data: turn === undefined ? {} : { turn } }, + ], + }], + }) + await expect(runScenario( + { + steps: [ + ...boot, + { op: 'promptAndCancel', text: 'hang' }, + { op: 'waitForTurnStart' }, + ], + }, + { agent: AGENT, mode: 'replay', fixtureFile: malformed.fixtureFile }, + )).rejects.toThrow('invalid persisted turn/start record') + } + }) + it('waitForTurnEnd times out for a missing log and an open logged turn', { timeout: 20_000 }, async () => { const missing = await scenario({}) await expect(runScenario( @@ -695,15 +777,27 @@ describe('runScenario', () => { expect(result.sessionId).toBeDefined() }) + it('a standalone cancel can wait for cwd-relative readiness', { timeout: 20_000 }, async () => { + const { dir, fixtureFile } = await scenario({}) + const workspaceDir = join(dir, 'workspace') + const { mkdir } = await import('node:fs/promises') + await mkdir(workspaceDir, { recursive: true }) + await writeFile(join(workspaceDir, 'ready'), '') + const result = await runScenario( + { steps: [...boot, { op: 'cancel', waitForFile: { path: 'ready' } }] }, + { agent: AGENT, mode: 'replay', fixtureFile, workspaceDir }, + ) + expect(result.sessionId).toBeDefined() + }) + it.each([ [{ op: 'prompt', text: 'x' }, /prompt before newSession/], [{ op: 'promptAndWaitForAgentMessage', text: 'x', waitForText: 'later' }, /promptAndWaitForAgentMessage before newSession/], [{ op: 'promptExpectError', text: 'x' }, /promptExpectError before newSession/], [{ op: 'promptAndCancel', text: 'x' }, /promptAndCancel before newSession/], + [{ op: 'waitForTurnStart' }, /waitForTurnStart before newSession/], [{ op: 'waitForTurnEnd' }, /waitForTurnEnd before newSession/], [{ op: 'cancel' }, /cancel before newSession/], - [{ op: 'setConfigOption', configId: 'sandbox-mode', value: 'read-only' }, /setConfigOption before newSession/], - [{ op: 'setConfigOptionExpectError', configId: 'sandbox-mode', value: 'yolo' }, /setConfigOptionExpectError before newSession/], ] as [InputStep, RegExp][])('rejects %j before newSession', { timeout: 20_000 }, async (step, message) => { const { fixtureFile } = await scenario({}) await expect(runScenario( @@ -712,53 +806,6 @@ describe('runScenario', () => { )).rejects.toThrow(message) }) - it('setConfigOption switches a value and receives the complete refreshed option state', { timeout: 20_000 }, async () => { - const { fixtureFile } = await scenario({ - configOptions: { 'sandbox-mode': ['read-only', 'workspace-write'], 'approval-policy': ['ask', 'never'] }, - }) - const result = await runScenario( - { - steps: [...boot, - { op: 'setConfigOption', configId: 'sandbox-mode', value: 'workspace-write' }, - { op: 'setConfigOption', configId: 'approval-policy', value: 'never' }], - }, - { agent: AGENT, mode: 'replay', fixtureFile }, - ) - // Every set answers with the FULL state: the second response carries the - // first switch's value too — the complete-refreshed-state contract. - const frames = result.rawStdout.trim().split('\n').map(line => JSON.parse(line) as { result?: { configOptions?: { id: string; currentValue: string }[] } }) - const states = frames - .map(f => f.result?.configOptions) - .filter(options => options !== undefined) - .map(options => Object.fromEntries((options as { id: string; currentValue: string }[]).map(o => [o.id, o.currentValue]))) - expect(states).toEqual([ - { 'sandbox-mode': 'workspace-write', 'approval-policy': 'ask' }, - { 'sandbox-mode': 'workspace-write', 'approval-policy': 'never' }, - ]) - }) - - it('setConfigOptionExpectError swallows the rejection for unknown ids and out-of-vocabulary values', { timeout: 20_000 }, async () => { - const { fixtureFile } = await scenario({ configOptions: { 'sandbox-mode': ['read-only'] } }) - const result = await runScenario( - { - steps: [...boot, - { op: 'setConfigOptionExpectError', configId: 'sandbox-mode', value: 'yolo' }, - { op: 'setConfigOptionExpectError', configId: 'reasoning-effort', value: 'max' }], - }, - { agent: AGENT, mode: 'replay', fixtureFile }, - ) - expect(result.rawStdout).toContain('unknown sandbox-mode value yolo') - expect(result.rawStdout).toContain('unknown config option reasoning-effort') - }) - - it('setConfigOptionExpectError throws when the set unexpectedly succeeds', { timeout: 20_000 }, async () => { - const { fixtureFile } = await scenario({ configOptions: { 'sandbox-mode': ['read-only'] } }) - await expect(runScenario( - { steps: [...boot, { op: 'setConfigOptionExpectError', configId: 'sandbox-mode', value: 'read-only' }] }, - { agent: AGENT, mode: 'replay', fixtureFile }, - )).rejects.toThrow(/expected set_config_option to be rejected/) - }) - it('rejects an unknown input op', { timeout: 20_000 }, async () => { const { fixtureFile } = await scenario({}) const bogus = { op: 'reticulate' } as unknown as InputStep @@ -814,69 +861,6 @@ describe('runScenario', () => { expect(result.sessionLogs).toHaveLength(0) }) - it('drives session/set_mode and swallows the expected rejection of setModeExpectError', { timeout: 20_000 }, async () => { - const { fixtureFile } = await scenario({}) - const result = await runScenario( - { steps: [...boot, { op: 'setMode', modeId: 'plan' }] }, - { agent: AGENT, mode: 'replay', fixtureFile }, - ) - expect(result.rawStdout).toContain('setMode:plan') - - const rejecting = await scenario({ setMode: 'error' }) - const rejected = await runScenario( - { steps: [...boot, { op: 'setModeExpectError', modeId: 'yolo' }] }, - { agent: AGENT, mode: 'replay', fixtureFile: rejecting.fixtureFile }, - ) - expect(rejected.rawStdout).toContain('unknown mode') - }) - - it('fails the run when setModeExpectError unexpectedly succeeds, and both mode ops require a session', { timeout: 20_000 }, async () => { - const { fixtureFile } = await scenario({}) - await expect(runScenario( - { steps: [...boot, { op: 'setModeExpectError', modeId: 'plan' }] }, - { agent: AGENT, mode: 'replay', fixtureFile }, - )).rejects.toThrow(/expected session\/set_mode to be rejected/) - await expect(runScenario( - { steps: [{ op: 'initialize' }, { op: 'setMode', modeId: 'plan' }] }, - { agent: AGENT, mode: 'replay', fixtureFile }, - )).rejects.toThrow(/setMode before newSession/) - await expect(runScenario( - { steps: [{ op: 'initialize' }, { op: 'setModeExpectError', modeId: 'plan' }] }, - { agent: AGENT, mode: 'replay', fixtureFile }, - )).rejects.toThrow(/setModeExpectError before newSession/) - }) - - it('answers elicitations from the scripted queue, falling back to cancel on exhaustion', { timeout: 20_000 }, async () => { - const { fixtureFile } = await scenario({ elicitationProbe: true }) - // Three prompts → three elicitations: an accept-with-choice, an - // accept-with-custom (feedback), then the exhausted-queue cancel. - const result = await runScenario( - { - steps: [...boot, { op: 'prompt', text: 'one' }, { op: 'prompt', text: 'two' }, { op: 'prompt', text: 'three' }], - elicitationAnswers: [ - { action: 'accept', choice: 'Approve' }, - { action: 'accept', custom: 'add tests first' }, - ], - }, - { agent: AGENT, mode: 'replay', fixtureFile }, - ) - const first = result.rawStdout.indexOf('elicitation:{\\"action\\":\\"accept\\",\\"content\\":{\\"choice\\":\\"Approve\\"}}') - const second = result.rawStdout.indexOf('elicitation:{\\"action\\":\\"accept\\",\\"content\\":{\\"custom\\":\\"add tests first\\"}}') - const third = result.rawStdout.indexOf('elicitation:{\\"action\\":\\"cancel\\"}') - expect(first).toBeGreaterThanOrEqual(0) - expect(second).toBeGreaterThan(first) - expect(third).toBeGreaterThan(second) - }) - - it('a scripted elicitation cancel answers cancel', { timeout: 20_000 }, async () => { - const { fixtureFile } = await scenario({ elicitationProbe: true }) - const result = await runScenario( - { steps: [...boot, { op: 'prompt', text: 'one' }], elicitationAnswers: [{ action: 'cancel' }] }, - { agent: AGENT, mode: 'replay', fixtureFile }, - ) - expect(result.rawStdout).toContain('elicitation:{\\"action\\":\\"cancel\\"}') - }) - it('answers permission requests from the scripted queue by option kind, falling back to cancelled', { timeout: 20_000 }, async () => { const { fixtureFile } = await scenario({ permissionProbe: true }) // Two prompts → two permission round-trips; one scripted answer, so the diff --git a/packages/support/acp-snapshot/tests/normalize.spec.ts b/packages/support/acp-snapshot/tests/normalize.spec.ts index f2e4b74da7..103dba0336 100644 --- a/packages/support/acp-snapshot/tests/normalize.spec.ts +++ b/packages/support/acp-snapshot/tests/normalize.spec.ts @@ -44,6 +44,24 @@ describe('normalizeStdout', () => { expect(out).not.toContain(ctx.sessionIds[0] as string) }) + it('scrubs every filesystem spelling of the cwd longest-first', () => { + const longCwd = String.raw`C:\Users\runneradmin\AppData\Local\Temp\acp-snapshot` + const aliasedCtx: NormalizeContext = { + sessionIds: [], + cwd: String.raw`C:\Users\RUNNER~1\AppData\Local\Temp\acp-snapshot`, + cwdAliases: [ + longCwd, + String.raw`C:\Users\runneradmin\AppData\Local\Temp\acp`, + ], + } + const raw = JSON.stringify({ + cwd: longCwd, + path: `${longCwd}\\nested\\proof.txt`, + }) + const frame = JSON.parse(normalizeStdout(raw, aliasedCtx)) as { cwd: string; path: string } + expect(frame).toEqual({ cwd: '{{cwd}}', path: '{{cwd}}/nested/proof.txt' }) + }) + it('canonicalizes only cwd-rooted path separators', () => { const windowsCtx: NormalizeContext = { sessionIds: [], @@ -105,24 +123,6 @@ Additional instructions from: nested\AGENTS.md`, expect(out).not.toContain('"id"') }) - it('stabilizes the timestamp carried by session title updates', () => { - const raw = JSON.stringify({ - jsonrpc: '2.0', - method: 'session/update', - params: { - sessionId: ctx.sessionIds[0], - update: { - sessionUpdate: 'session_info_update', - title: 'Stable title', - updatedAt: '2026-07-20T17:03:13.689Z', - }, - }, - }) - const out = normalizeStdout(raw, ctx) - expect(out).toContain('"updatedAt":"{{updatedAt}}"') - expect(out).not.toContain('2026-07-20T17:03:13.689Z') - }) - it('stabilizes only the top-level event timestamp and spill byte count in event-read text', () => { const raw = JSON.stringify({ jsonrpc: '2.0', diff --git a/packages/support/acp-snapshot/tests/suite.spec.ts b/packages/support/acp-snapshot/tests/suite.spec.ts index 14bcb8178c..e021bc31d9 100644 --- a/packages/support/acp-snapshot/tests/suite.spec.ts +++ b/packages/support/acp-snapshot/tests/suite.spec.ts @@ -53,6 +53,7 @@ const REPLAY_SCENARIOS: Scenario[] = [ hasModelTurn: true, recorded: true, headerClass: 'main', + env: { DSH_PERMISSION_MODE: 'never' }, configPath: AGENT.configPath, workspaceParent: tmpdir(), }, @@ -130,6 +131,8 @@ describe('defineAcpSnapshotSuite: refresh write-back', () => { expect(stdout).not.toContain('stale stdout') expect(stdout).toContain('env:{\\"mode\\":\\"replay\\"') expect(stdout).not.toContain('\\"mode\\":\\"refresh\\"') + // The scenario's own env layer reached the subprocess. + expect(stdout).toContain('\\"permissionMode\\":\\"never\\"') const blocked = readFileSync(join(refreshDir, 'blocked-log', 'session.jsonl'), 'utf8') expect(blocked).toContain('"decision":"block"') diff --git a/packages/support/llm-replay/README.md b/packages/support/llm-replay/README.md index 0d89d4337d..40227393d3 100644 --- a/packages/support/llm-replay/README.md +++ b/packages/support/llm-replay/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-llm-replay -A replay LLM plugin for keyless snapshot tests. It yields model streams reconstructed from a recorded **session JSONL** fixture, so a test can boot the real agent against a fixed model transcript with no API key. With `providers` configured it registers a replay-only adapter whose catalog is visible to clients such as ACP editors; without `providers` it installs the catch-all `llm/stream` waterfall used by tests that do not need discovery. +A replay LLM plugin for keyless snapshot tests. It yields model streams reconstructed from a recorded **session JSONL** fixture, so a test can boot the real agent against a fixed model transcript with no API key. With `providers` configured it registers a replay-only adapter whose catalog is available to scenarios that exercise model discovery; without `providers` it installs the catch-all `llm/stream` waterfall used by tests that do not need discovery. Its consumers are the ACP snapshot harness in `examples/acp-agent` and the `stream-json` snapshot in `examples/headless-agent`; each loads this plugin in place of a real LLM adapter. Keeping derivation and replay here places that logic under the per-file 100% coverage gate on `packages/*/src`. @@ -8,7 +8,7 @@ Its consumers are the ACP snapshot harness in `examples/acp-agent` and the `stre The fixture IS the persisted session log (`<scenario>/session.jsonl`). Its `assistant/chunk` events carry every `StreamChunk`, so grouping them by `(turn, step)` reconstructs each `stream()` call's chunk sequence (one model call per loop step). Recording is therefore "run the real agent once and harvest the `.jsonl`", done by the snapshot harness — this plugin does not record. A fixture may carry its `request/header` content tokenized to `{{system}}`/`{{tools}}` (the harness pins that content in one scenario and scrubs the rest); replay is indifferent — derivation reads only `assistant/chunk` events and the line-0 session header. -Two failure modes are not reconstructable from `assistant/chunk` alone — a pure throw before any chunk (e.g. an HTTP 401, where the log holds only a `turn/end {error}` and no chunks) and a cancel/hang (timing, not chunk content). A scenario that needs those supplies an optional sidecar (`<scenario>/replay.override.json`: a `ReplayEntry[]`) that REPLACES the derived script. +Two failure modes are not reconstructable from `assistant/chunk` alone — a pure throw before any chunk (e.g. an HTTP 401, where the log holds only a `turn/end {error}` and no chunks) and a cancel/hang (timing, not chunk content). A scenario that needs those supplies an optional sidecar (`<scenario>/replay.override.json`: a `ReplayEntry[]`) that REPLACES the derived script. A `hang` entry may name `readyFile`; replay writes that empty marker after its prefix chunks reach the loop and before it waits for cancellation, so an external driver can cancel deterministically without observing a presentation update. ## Nested agents: per-session keying diff --git a/packages/support/llm-replay/src/index.ts b/packages/support/llm-replay/src/index.ts index ca4511db8a..cd1993b1e2 100644 --- a/packages/support/llm-replay/src/index.ts +++ b/packages/support/llm-replay/src/index.ts @@ -6,7 +6,7 @@ * @module @deepseek-ai/dsh-llm-replay */ -import { existsSync, readFileSync } from 'node:fs' +import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { delimiter as pathDelimiter } from 'node:path' import type { Context } from 'cordis' import { decodeStorageRecord } from '@deepseek-ai/dsh-session' @@ -22,7 +22,11 @@ import { LlmAdapter, LlmError, assertNever } from '@deepseek-ai/dsh-llm' export type ReplayEntry = | { kind: 'chunks'; chunks: StreamChunk[] } | { kind: 'throw'; chunks: StreamChunk[]; message: string; code: string } - | { kind: 'hang' } + | { + kind: 'hang' + /** Optional marker written after the prefix chunks are consumed and before the stream waits for cancellation. */ + readyFile?: string + } /** One model exposed by a replay-only provider catalog. */ export interface ReplayModelConfig { @@ -42,7 +46,7 @@ export interface ReplayProviderConfig { id: string /** Selector label; defaults to {@link id}. */ name?: string - /** Advisory models exposed to clients such as ACP editors. */ + /** Advisory models exposed to replay scenarios that exercise discovery. */ models?: ReplayModelConfig[] } @@ -301,6 +305,7 @@ async function* replayEntry(entry: ReplayEntry, signal: AbortSignal | undefined) // chunk, then wait for abort and surface it as the consumer expects. yield { type: 'block-start', index: 0, blockType: 'text' } yield { type: 'text-delta', index: 0, text: 'partial' } + if (entry.readyFile !== undefined) writeFileSync(entry.readyFile, '') await new Promise<void>((_resolve, reject) => { if (signal?.aborted) { reject(new Error('aborted')); return } signal?.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true }) diff --git a/packages/support/llm-replay/tests/llm-replay.spec.ts b/packages/support/llm-replay/tests/llm-replay.spec.ts index 14086db27f..645b655445 100644 --- a/packages/support/llm-replay/tests/llm-replay.spec.ts +++ b/packages/support/llm-replay/tests/llm-replay.spec.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' @@ -379,7 +379,8 @@ describe('installLlmReplay (through the real LlmService)', () => { it('rejects a hang entry when the signal fires DURING the wait (abort listener path)', async () => { writeFileSync(file, sessionJsonl([]), 'utf8') const overrideFile = join(dir, 'replay.override.json') - writeFileSync(overrideFile, JSON.stringify([{ kind: 'hang' }]), 'utf8') + const readyFile = join(dir, 'stream-ready') + writeFileSync(overrideFile, JSON.stringify([{ kind: 'hang', readyFile }]), 'utf8') const ctx = new Context() await ctx.plugin(LlmService) installLlmReplay(ctx, { file, overrideFile }) @@ -392,6 +393,7 @@ describe('installLlmReplay (through the real LlmService)', () => { expect((await iterator.next()).value).toMatchObject({ type: 'text-delta' }) const pending = iterator.next() await new Promise(r => setImmediate(r)) + expect(existsSync(readyFile)).toBe(true) controller.abort() await expect(pending).rejects.toThrow('aborted') }) diff --git a/packages/tasks/tool-tasks/README.md b/packages/tasks/tool-tasks/README.md index a103640cd5..d471e709bc 100644 --- a/packages/tasks/tool-tasks/README.md +++ b/packages/tasks/tool-tasks/README.md @@ -8,7 +8,7 @@ The model-facing control surface for `ctx.tasks`: three kind-independent tools, - `task_list()` returns caller-visible tasks as `<id> [<kind>] <status> — <label>`. - `task_kill(task_id, reason?)` requests cancellation immediately and forwards the logged reason. Terminal tasks return a non-consuming snapshot. -All three use generic ACP cards: `read` for output and list, `execute` for kill. +All three use generic UI cards: `read` for output and list, `execute` for kill. Their canonical values are `{ text, task }`, `PublicTaskSnapshot[]`, and `{ outcome: 'cancellation-requested' | 'already-finished', task }`. A public snapshot carries id, kind, label, status/detail, and start/finish times; it deliberately omits `ownerSession` and the internal `reported` notice bit. Native renderers preserve the status and acknowledgement text above. diff --git a/packages/todo/README.md b/packages/todo/README.md index c19fab82d3..a2dfa2549d 100644 --- a/packages/todo/README.md +++ b/packages/todo/README.md @@ -6,4 +6,4 @@ The model-facing todo tool. A single **product** package — there is no interfa |---|---|---| | `tool-todo/` | Model-facing `todo_write` tool; writes the whole list to the session log (`todo/write`) | (registers on `ctx.tools`) | -The list lives on the event-sourced session log (`SessionEventMap['todo/write']`, owned by [`dsh-session`](../core/session)); this package is the thin consumer that appends the snapshot. UIs render off `session/event`: the [TUI app](../examples/tui-demo) shows a persistent plan, while the [ACP bridge](../ui/acp) maps it to a `plan` sessionUpdate. +The list lives on the event-sourced session log (`SessionEventMap['todo/write']`, owned by [`dsh-session`](../core/session)); this package is the thin consumer that appends the snapshot. UIs such as the [TUI app](../examples/tui-demo) and the host/client runtime render the durable list from session events. diff --git a/packages/todo/tool-todo/README.md b/packages/todo/tool-todo/README.md index febb2c9ce0..330f816027 100644 --- a/packages/todo/tool-todo/README.md +++ b/packages/todo/tool-todo/README.md @@ -6,7 +6,7 @@ The model-facing `todo_write` tool: the agent's whole task list, replaced wholes Registers one tool, `todo_write(todos: [{ content, status }])`, on `ctx.tools`. The model sends the ENTIRE list every call — there are no partial updates or per-item edits. Each call appends a `todo/write` event (the full list snapshot) to the calling agent's session log via `agent.session.append('todo/write', { todos })`; the current list is the most recent such event (last-write-wins on replay). -`status` is one of `pending`, `in_progress`, `completed` — exactly the ACP `PlanEntryStatus` triple. +`status` is one of `pending`, `in_progress`, or `completed`. ## Single owner @@ -18,7 +18,7 @@ Beyond the schema's type/required/enum checks, `execute` rejects an empty or dup ## Rendering -The canonical result is `{ todos, counts: { pending, inProgress, completed } }`; its Native renderer returns the compact update acknowledgement. The tool also writes the full `todo/write` session event. UIs subscribe to `session/event` and render that durable list themselves: the [TUI app](../../examples/tui-demo) shows a persistent plan, and the [ACP bridge](../../ui/acp) maps the list to a `plan` sessionUpdate (synthesizing the `priority` ACP requires). +The canonical result is `{ todos, counts: { pending, inProgress, completed } }`; its Native renderer returns the compact update acknowledgement. The tool also writes the full `todo/write` session event. UIs subscribe to the event stream and render that durable list themselves; the [TUI app](../../examples/tui-demo) shows it as a persistent plan. ## Export shape @@ -57,5 +57,5 @@ Append-only; newly visible content follows the reusable request prefix and does ## Known Limitations and Deferred Work - **Single-owner scope only** — the list belongs to the one calling agent session; subagent/shared/swarm scopes are a deliberate cut (see § Single owner), and a non-agent caller is rejected. -- **The item shape is deliberately minimal** — `content` plus three-state `status`; no id, priority, or active-form fields, and the ACP bridge synthesizes the `priority` ACP requires. +- **The item shape is deliberately minimal** — `content` plus three-state `status`; whole-list replacement needs no stable id, priority, or active-form fields. - **Whole-list replacement is the only operation** — no partial updates, no read-back tool; the model must resend the entire list each call. diff --git a/packages/ui/README.md b/packages/ui/README.md index f8e4704f20..0367223a24 100644 --- a/packages/ui/README.md +++ b/packages/ui/README.md @@ -1,10 +1,9 @@ -# ui/ — editor/client integration surfaces +# ui/ — human and SDK-client integration surfaces -Integrations that expose the agent to an external editor or client. These are **product** packages: a real surface a user drives the harness through. +Human-facing channels and the out-of-process SDK server. These are **product** packages: real interfaces that a person or SDK client drives. | Package | Role | ctx key | |---|---|---| -| `acp/` | Agent Client Protocol bridge: serves agents, commands, and live/replayed title updates to an ACP editor over JSON-RPC stdio | (drives `ctx.agents`/`ctx.sessions`) | | `commands/` | Human-command registry: shared discovery metadata, scoped shadowing, cancellation, and direct UI dispatch | `ctx.commands` | | `user-approval/` | One-shot user-approval mechanism, closed outcome vocabulary, audit events, and per-session approval policy | `ctx.approval` | | `permission/` | User-facing permission presets (`workspace-write`/`danger-full-access`): one product-level select bundling the sandbox-mode and approval-policy knobs, written through to their session events | `ctx.permission` | @@ -14,8 +13,8 @@ Integrations that expose the agent to an external editor or client. These are ** | `jsonrpc/` | Stdio JSON-RPC server for out-of-process SDK clients | (drives `ctx.agents`) | | `app-boot/` | Shared boot glue for the app bins: `.env` loading, fail-loud Loader guards, snapshot-aware config resolution, the settle-the-tree boot sequence | (library for the bins) | -A UI integration is a client-driver plugin, not a loop change: it consumes the existing `agent/*` event taxonomy and the `dsh-agent` factory. The `jsonrpc` plugin is the SDK-client sibling of the `acp` bridge (a JSON-RPC server over `ctx.agents` for out-of-process SDK clients rather than editors). [`tui`](tui/README.md) is the interactive terminal front door and supplies the terminal-local `ctx.tui` extension service; non-interactive tasks use the headless `cli-demo` app instead of a UI channel. [`commands`](commands/README.md) is the human-only discovery and dispatch plane shared by TUI and ACP; command input and output do not become model messages. +A UI integration is a client-driver plugin, not a loop change: it consumes the existing `agent/*` event taxonomy and the `dsh-agent` factory. [`tui`](tui/README.md) is the interactive terminal front door and supplies the terminal-local `ctx.tui` extension service; [`jsonrpc`](jsonrpc/README.md) serves out-of-process SDK clients, while non-interactive one-shot tasks use `cli-demo`. [`commands`](commands/README.md) is the human-only discovery and dispatch plane consumed by TUI; command input and output do not become model messages. -`user-approval`, `user-interaction`, and `tool-ask-user` live here because asking a human is a UI-backed product affordance, not part of the providerless core spine. `user-approval` owns the one-shot `ctx.approval` decision mechanism and its policy tier; answerers remain with their UI channel owners. `user-interaction` remains provider-neutral (`ctx.userInteraction`), while `tool-ask-user` is its model-facing consumer and the app/bridge packages provide concrete providers. +`user-approval`, `user-interaction`, and `tool-ask-user` live here because asking a human is a UI-backed product affordance, not part of the providerless core spine. `user-approval` owns the one-shot `ctx.approval` decision mechanism and its policy tier; answerers remain with the channel or automation transport that owns the agent. `user-interaction` remains provider-neutral (`ctx.userInteraction`), while `tool-ask-user` is its model-facing consumer and interactive app packages provide concrete providers. -The runnable app bundles that bake these bridges into boot bins — the TUI app, ACP server app, and JSON-RPC SDK-runtime bin — live in [`examples/`](../examples/README.md) (`tui-demo`, `acp-demo`, `jsonrpc-demo`), each composed over the [`agent-spine-demo`](../examples/agent-spine-demo/README.md) bundle. `ui/` keeps the reusable bridge/channel plugins and the `app-boot` glue; each front door owns its stdout policy, and a leaf `cordis.yml` supplies backends and optional tools. +The runnable app bundles that bake these interfaces into boot bins live in [`examples/`](../examples/README.md), composed over [`agent-spine-demo`](../examples/agent-spine-demo/README.md). `ui/` keeps the reusable human/SDK channel plugins and shared `app-boot` glue; the automation-only ACP transport lives in [`acp/`](../acp/README.md). Each front door owns its stdout policy, and a leaf `cordis.yml` supplies backends and optional tools. diff --git a/packages/ui/acp/README.md b/packages/ui/acp/README.md deleted file mode 100644 index f135e42553..0000000000 --- a/packages/ui/acp/README.md +++ /dev/null @@ -1,199 +0,0 @@ -# @deepseek-ai/dsh-acp - -Agent Client Protocol bridge over JSON-RPC stdio. Editors can create or resume agents, stream their events, answer questions and approvals, and render tool calls. One connection supports multiple isolated sessions; Zed is the primary compatibility target. - -It is a **client-driver / UI plugin**, the structured analogue of the terminal `dsh-tui` channel — NOT a loop change and NOT a [capability seam](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md). It consumes the existing `agent/*` event taxonomy, the `dsh-agent` create/resume factory, and `dsh-session-persistence`. - -## Service / plugin - -`apply(ctx, config)` — wires an `AgentSideConnection` (from `@agentclientprotocol/sdk`) to `process.stdin`/`process.stdout` and implements the ACP `Agent` method surface. - -The plugin injects `agents`, [`commands`](../commands/README.md), `sessionPersistence`, `sessionQuery`, `tools`, `userInteraction`, `llm`, and `systemPrompt`, never the concrete loop. Persistence backs `session/load`; live-preferred session queries back `session/list`; the command registry backs slash discovery and direct dispatch; the LLM catalog backs model selection; prompt assembly keeps model variables aligned with routing; tool definitions own presentation; user interaction maps agent questions to ACP forms. - -### Config - -| Key | Default | Meaning | -|---|---|---| -| `provider` | — | Initial provider route for created agents (must have a registered adapter). | -| `model` | — | Initial model id for created agents. | - -(No persona key: `dsh-system-prompt`'s own `persona` config supplies the global default section, so ACP-created agents render it without the bridge carrying prompt text. An agent-scoped same-name section may still shadow that default.) - -The `initialize` handshake reports a fixed server identity (`agentInfo: { name: 'deepseek-harness-acp', version: '0.0.1' }`) — branding is a literal at the `initialize` site, not config. - -## ACP method mapping - -| ACP method | Harness seam | Notes | -|---|---|---| -| `initialize` | static | negotiate `protocolVersion`; advertise baseline prompt capabilities (`text`, plus `resource_link` rendered as text), `loadSession: true`, and `sessionCapabilities.list` | -| `session/new` | `ctx.agents.create({ sessionId, meta:{cwd} })` | creates a new session/agent; N concurrent sessions are allowed, keyed by id; advertises the effective command snapshot; `cwd` must be absolute (it becomes the session's workspace — see Per-session cwd); non-empty `additionalDirectories` and `mcpServers` rejected | -| `session/load` | `ctx.agents.resume(...)` | reserves the id, verifies the persisted cwd, resumes, replays user, assistant, tool, and title events, and re-advertises commands | -| `session/list` | `ctx.sessionQuery` | returns live-preferred newest-first sessions with absolute cwd and optional folded title; supports exact normalized cwd filtering, returns no cursor, and rejects supplied cursors | -| `session/prompt` | `ctx.commands.execute()` or `agent.followup()` | a flattened prompt beginning with `/` stays in the direct command plane; ordinary prompts support ACP `text` and `resource_link`; `dsh-session:` links and inline mentions are snapshotted through optional `ctx.sessionReferences` before enqueue; unsupported content, unavailable reference capability, failed snapshots, and empty prompts are rejected; one request is in flight per session and settles on the owning turn's end, with an error turn rejecting the RPC | -| `session/cancel` | command `AbortSignal` or `agent.cancel()` | aborts the exact direct command, or applies the queue-aware agent cancel and settles its prompt `cancelled`; one session never cancels another | -| `session/update` | `session/event` | streams user replay, assistant text/reasoning, retry/failure attempt markers, tool render intents, and `session_info_update` title revisions | -| `elicitation/create` | `ctx.userInteraction.ask()` | maps `ask_user_question` questions to ACP form elicitations; option descriptions are shown in enum titles, `multi_select` uses ACP array enums, optionless requests use a required `custom` field, and a non-empty custom answer overrides any selected choice | -| `session/request_permission` | `approval/request` listener | answers one-shot allow/reject requests for bridge-owned calls; foreign or call-less requests delegate and fail closed if unanswered — see "Permission prompts" | -| `session/set_config_option` | agent-scoped request target / `ctx.permission.set()` | per-session provider+model and permission-preset switching over [session config options](https://agentclientprotocol.com/protocol/session-config-options) — see "Session config options" | - -## Multi-session - -One id-keyed record map plus exact agent-object checks route every event, prompt, cancel, and approval to one session. Each session permits one in-flight prompt or reference-preparation operation; `session/cancel` aborts preparation before it can enqueue. Teardown drains all sessions in parallel. See the [multi-session Agent Note](../../../.agents/notes/implemented/feature/2026-06-14-acp-multi-session.md). - -## Human commands - -After `session/new` and `session/load`, the bridge emits ACP's full `available_commands_update` snapshot for that exact agent. A new session's server-generated id is introduced by the RPC response before its snapshot enters the connection write queue. A global or scoped registry change refreshes every live session from its independently resolved view, so clients replace rather than merge cached catalogs. Names omit the slash; descriptions and optional unstructured-input hints map directly to ACP `AvailableCommand`. - -ACP v1 permits a command prompt to carry additional content blocks. The bridge applies its ordinary lossless flattening for supported `text` and `resource_link` blocks, then dispatches when the result begins with `/`. Known commands execute without a model request. Unknown or malformed slash input returns a direct error instead of falling back to the model; prefix whitespace when literal slash-leading text must reach the model. Expected handler errors, thrown failures, and successful text stream as UI-only `agent_message_chunk` output and end the request; cancellation returns `cancelled`. See the [command Agent Note](../../../.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md) and the [ACP v1 slash-command contract](https://agentclientprotocol.com/protocol/v1/slash-commands). - -## Session config options - -The bridge advertises a `model`-category select in `session/new` and `session/load` when the session has a complete target whose provider is registered. Values encode the complete provider/model pair, are grouped by provider when more than one group is available, and come from `ctx.llm.listProviders()` / `listModels()`. The configured or last-requested model is added when absent because catalogs are advisory and private adapters may accept unlisted ids. A selection changes only that ACP session. Agent-scoped prompt assembly snapshots the selected pair for one step, supplies matching `{{provider}}` / `{{model}}` variables, and the `agent/request` waterfall applies the same pair; a concurrent selection therefore takes effect on the next step instead of splitting prompt text from routing. The resulting request header is the durable record restored by `session/load`; a selection never used by a request remains in-memory only. - -When `ctx.permission` is composed, the bridge also advertises a `permission` select. Options come from the deployment's preset table; the current value comes from the session fold, with switch-away-only `custom` for unmatched knobs. `session/set_config_option` accepts advertised presets and writes both sandbox-mode and approval-policy events through `PermissionService.set()`. Open-turn switches append immediately; idle switches overlay responses and anchor at the next `agent/prompt-submit`, before request assembly. A crash before anchoring restores the durable fold. See the [model-catalog Agent Note](../../../.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md), [sandbox Agent Note](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md), [`dsh-permission`](../permission/README.md), and [protocol matrix](acp-feature-support.md#6-session-modes--config-options--models). - -The shared [`ctx.tasks` runtime](../../tasks/tasks/) fences access to predictable task ids by the owning session; ACP sessions therefore cannot read or stop one another's background work. - -ACP updates are append-only, so `llm/retry` emits a visible separator that marks preceding partial model output discarded before the next attempt streams. A terminal model-request failure emits the same discarded-output warning; replay derives both markers from the durable events. - -A log-only `session/title` event maps to ACP `session_info_update` with `title` and the event timestamp as `updatedAt`. The same mapping runs for live events and `session/load` replay, so an asynchronously generated late title and a restored persisted title have one wire representation without entering model history. - -`session/list` returns the same latest folded title in standard `SessionInfo.title`. When `ctx.sessionReferences` is mounted, each listed item also carries `_meta["deepseek-harness/sessionReference"].uri`; a title-aware client can render `title ?? sessionId` in its `@` picker and submit that URI as a `resource_link` with the same display name. Sessions without cwd are omitted because ACP requires an absolute `SessionInfo.cwd` and the bridge cannot load them. - -## Per-session cwd - -`session/new` records the request's absolute cwd in the session header. Before constructing an agent, `session/load` uses persisted metadata to require an absolute request cwd that matches the stored one. Bash defaults to that workspace; an explicit relative workdir resolves against it, and multiple sessions may use different workspaces. `additionalDirectories` remains unsupported. - -## Tool-call presentation - -Tools return provider-neutral `generic`, `terminal`, or `diff` render intents from `presentCall()` and `presentResult()`. The bridge maps the discriminator to ACP without special-casing tool names and falls back to a generic card. Per-session call-id state supplies result events with their omitted name and arguments during live streaming and replay. File-card titles are relative to the session cwd and use the host separator, while location and diff paths remain raw so the editor opens the real file. See [`dsh-tools`](../../core/tools/README.md#tool-owned-ui-presentation). - -## Terminal card (capability-gated) - -When the client advertises `_meta.terminal_output`, terminal intents map to Zed's terminal info, output, and exit metadata. The bridge resolves relative cwd against the session and preserves the host filesystem separator, places the description before the terminal block, and omits result content because ACP updates replace call content. Other clients receive a generic card and bridge-derived fenced console fallback. Session creation snapshots the capability so call and result agree. The command still executes through the harness, not ACP terminal creation. See the [terminal-rendering Agent Note](../../../.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md) and [render-intent Agent Note](../../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md). - -## Settle-exactly-once - -A prompt captures its owning turn and settles exactly once from the matching durable `turn/end`, even if presentation failed. Turn correlation excludes stale endings. Error turns reject with an ACP internal error; empty prompts reject before enqueue. - -## Permission prompts - -For a bridge-owned call, the [approval seam](../user-approval/README.md) maps `ask` to an editor prompt with one-shot allow/reject options. Foreign or call-less requests delegate; unknown choices never grant, cancellation stays cancellation, and transport failure becomes fail-closed unavailability. Whether a tool asks remains policy outside the bridge. - -## Disposal & disconnect - -Disposal and client disconnect share one memoized teardown. It cancels pending prompts and disposes all owned agent handles in parallel, waiting for loop exit and final flush before registry removal. Mid-turn teardown records `disposed`; `session/cancel` records `aborted`. - -## stdout is the protocol - -The JSON-RPC frames go on stdout, so this plugin MUST run in an example that loads **no stdout logger** (the console logger writes to stdout and would corrupt the frames). The guarantee is config-only — see `examples/acp-agent` (no console logger) and [ACP support risks](../../../.agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.md#risks). A stderr exporter is fine for logging. - -## Running - -`pnpm --dir /path/to/deepseek-harness run demo:acp` boots `examples/acp-agent` (needs `DEEPSEEK_API_KEY`). Point an ACP client at it; for Zed, add to `agent_servers`: - -```json -{ - "agent_servers": { - "DeepSeek Harness": { - "command": "pnpm", - "args": ["--dir", "/path/to/deepseek-harness", "run", "demo:acp"] - } - } -} -``` - -## Model Experience - -### User messages - -#### What the model sees - -Each ACP `session/prompt` becomes an agent user message: text passes through verbatim and each ordinary `resource_link` becomes exactly a leading newline, `[resource_link name=<JSON-string> uri=<JSON-string>]`, and a trailing newline. When `ctx.sessionReferences` is mounted, a `resource_link` whose URI uses `dsh-session:` or an inline canonical mention becomes readable `@label` text plus one durable untrusted snapshot context; without the capability it is rejected. Unsupported image, audio, and embedded-resource blocks are rejected rather than silently omitted. - -#### Token effect - -Prompt tokens are data-dependent and remain in that session's history until compaction. Concurrent ACP sessions keep separate contexts. - -#### KV Cache effect - -Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries. - -### Human commands - -#### What the model sees - -Nothing from command discovery, slash input, or command output. A command handler may separately mutate a durable domain whose later state affects model requests. - -#### Token effect - -Direct dispatch adds no model tokens and no session message. The mutated domain owns any later prompt or history cost. - -#### KV Cache effect - -Command discovery, dispatch, and direct output never enter a model request and do not affect its cache. A mutated domain owns any later cache effect. - -### Human answers and permission decisions - -#### What the model sees - -When optional consumers are loaded, ACP form answers become the exact JSON shape documented by `dsh-tool-ask-user`. Failures become `Error: ACP user questions must come from an agent-owned request`, `Error: ACP user question has no matching session`, `Error: ACP elicitation request failed`, `Error: ask_user_question was cancelled by the user`, `Error: ask_user_question returned no answer`, or `Error: ask_user_question was aborted before the user answered`. Permission decisions control whether another tool yields success or denial. ACP tool cards, terminal output, diffs, title updates, and other streamed session updates are UI-only. - -#### Token effect - -Answer, error, and denial text enters context only through the owning tool result; presentation metadata adds zero model tokens. A replacement `tool/result` still changes the model-facing session surface, but live and replayed ACP feeds ignore it as an execution update so the original terminal or diff completion is not overwritten. - -#### KV Cache effect - -Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries. - -### Permission preset switches - -#### What the model sees - -`session/set_config_option` emits no model message itself. When `dsh-permission` is composed, the bridge writes the selected preset through that service; the resulting model-visible policy prompt and change notice belong to [`dsh-user-approval`](../user-approval/README.md), while sandbox-mode effects belong to [`dsh-tool-bash`](../../bash/tool-bash/README.md). The ACP `Permissions` select, its option descriptions, pending idle value, and refreshed config response remain client-only. - -#### Token effect - -Zero direct tokens from the ACP option or the log-only `permission/preset` event. Downstream cost is limited to the owning plugins' policy prompt, conditional retained change notice, and any changed tool outcome. - -#### KV Cache effect - -The ACP option and log event cause no direct invalidation. The downstream policy-prompt change may invalidate reuse from that system section, while its change notice appends to history. - -### Model switches - -#### What the model sees - -The ACP selector itself emits no message. The selected provider/model pair supplies the next step's `{{provider}}` / `{{model}}` prompt variables and request routing together; all other call-config fields continue through the `agent/request` waterfall unchanged. - -#### Token effect - -The selector adds no direct tokens. A changed model may tokenize the same retained prompt/history differently, and any persona text that interpolates provider or model changes accordingly. - -#### KV Cache effect - -Switching provider or model selects a different cache domain. If the persona interpolates either value, the rendered system prompt also changes and prevents reuse from its first changed token. - -### Loaded sessions - -#### What the model sees - -`session/load` resumes the persisted log, after which the loop sends its reconstructed history and request header. Replaying that log to the editor is not an extra model message. - -#### Token effect - -Restored context has the persistence and session packages' normal retained cost; ACP replay to the client adds none. - -#### KV Cache effect - -Loading does not rewrite the stored log, but the next request is reconstructed under the current envelope and route. Reuse requires that reconstruction to match; ACP replay to the client has no cache effect. - -## Known Limitations and Deferred Work - -- **`additionalDirectories`** — rejected. A session operates in its single `cwd` (see Per-session cwd); widening the tool/filesystem scope to extra roots is a separate sandbox concern, not yet implemented. -- **Prompt content is `text` + `resource_link` only** — image, audio, and embedded-resource blocks are rejected, as is a non-empty `mcpServers` list at `session/new`. -- **Session picker UI is client-owned** — `session/list` supplies standard title metadata and, when references are available, a canonical URI extension; an ACP client must consume those fields to add an `@` picker. Title/body search remains future metadata or FTS work. -- **Terminal cards render completed output** — live incremental streaming and command classification are named follow-ups of [the terminal-rendering Agent Note](../../../.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md). -- **Permission answers are one-shot only** — the bridge offers `allow_once` / `reject_once`; durable `allow_always` grants and their storage/revocation policy remain deferred to the approval seam. -- **Command output is live-only** — discovery is refreshed after load, but direct command results are not persisted or replayed into a reconnected editor. diff --git a/packages/ui/acp/acp-feature-support.md b/packages/ui/acp/acp-feature-support.md deleted file mode 100644 index 3292ee17c4..0000000000 --- a/packages/ui/acp/acp-feature-support.md +++ /dev/null @@ -1,158 +0,0 @@ -# ACP feature support checklist - -A structured inventory of [Agent Client Protocol](https://agentclientprotocol.com) (ACP) features and where the harness's ACP bridge ([`@deepseek-ai/dsh-acp`](README.md)) stands on each. The bridge exposes the harness agent as an ACP **server** (the agent side of an editor↔agent connection), so "supported" below means *the bridge implements the agent's half* — answering an agent method, advertising a capability, or calling a client method. - -## Scope - -This tracks the **stable** ACP v1 surface (schema `1.14.0`, `schema/v1/schema.json`) PLUS the **unstable/draft** features that the two reference adapters — [`claude-agent-acp`](https://github.com/zed-industries/claude-code-acp) (Claude Code) and [`codex-acp`](https://github.com/zed-industries/codex-acp) (OpenAI Codex) — actually ship. A purely-unstable feature that neither reference adapter uses is omitted (see [Out of scope](#out-of-scope)). - -Legend: ✅ supported · ⚠️ partial / fallback · ❌ not yet · — n/a. The **Stable** column marks whether the feature is in the released v1 schema (S) or only the unstable schema (U). The **Claude** / **Codex** columns record whether each reference adapter ships it, as a maturity signal. - -## At a glance - -The bridge implements the **core prompt-turn loop** for N concurrent sessions: initialize, session new/load/list, prompt, cancel, streamed assistant/thought chunks, tool-call rendering (including Zed terminal cards), resumable session replay, slash commands, one-shot permission prompts, per-session model selection and permission presets, and **session modes** (the picker, via `@deepseek-ai/dsh-plan-mode`). The largest **unbuilt** areas are **MCP passthrough** and **agent plans**, plus the client **filesystem** and **terminal** method families (which the adapters mostly do NOT drive either — see rows 43-49). See [Gap summary](#gap-summary). - -## 1. Agent methods (client → agent) - -| Method | Stable | Bridge | Claude | Codex | Notes | -|---|---|---|---|---|---| -| `initialize` | S | ✅ | ✅ | ✅ | Negotiates `PROTOCOL_VERSION`; advertises `loadSession`, `sessionCapabilities.list`, and baseline prompt caps. Snapshots the Zed `_meta.terminal_output` client cap. | -| `authenticate` | S | ⚠️ | ✅ | ✅ | No-op stub; the bridge advertises no `authMethods`, so there is nothing to authenticate. | -| `logout` | S | ❌ | ✅ | ✅ | Gated by `agentCapabilities.auth.logout`; not advertised. | -| `session/new` | S | ✅ | ✅ | ✅ | Maps to `agents.create`; requires an absolute `cwd` (becomes the session workspace); rejects non-empty `additionalDirectories` / `mcpServers`. | -| `session/load` | S | ✅ | ✅ | ✅ | Maps to `agents.resume` + full event-log replay; validates persisted `cwd` before constructing the agent. | -| `session/resume` | S | ❌ | ✅ | ✅ | Reconnect WITHOUT replay; gated by `sessionCapabilities.resume`. Not advertised. | -| `session/close` | S | ❌ | ✅ | ✅ | No `session/close` handler — the SDK dispatch returns `method_not_found`. The bridge tears sessions down on client disconnect / Cordis disposal (cross-cutting, see [§8](#8-cross-cutting)), but that is not the on-demand per-session method. | -| `session/prompt` | S | ✅ | ✅ | ✅ | A flattened prompt beginning with `/` dispatches through `ctx.commands` without a model request; ordinary input maps to `agent.followup`. One request is in flight per session. | -| `session/cancel` | S | ✅ | ✅ | ✅ | Aborts the exact direct command, or applies queue-aware `agent.cancel` and settles its prompt `cancelled`, scoped to one session. | -| `session/set_mode` | S | ✅ | ✅ | ✅ | Composed opportunistically: with `@deepseek-ai/dsh-plan-mode` mounted, `session/new`/`session/load` advertise the fixed `default` / `plan` projection and `session/set_mode` records the boolean pending intent (optimistic `current_mode_update`; logged `plan/mode` lands at the turn boundary). Without the plugin: no `modes` advertised, `set_mode` rejected (see [§6 Modes](#6-session-modes--config-options--models)). | -| `session/set_config_option` | S | ✅ | ✅ | ✅ | A provider/model select is present for a complete registered target; one `permission` select is added when `ctx.permission` is composed. Every response carries the complete refreshed state. | -| model selection | S | ✅ | ✅ | ✅ | No distinct stable `session/set_model` — model is the `model`-category `session/set_config_option`. Values preserve the provider/model pair, catalogs come from `ctx.llm`, selection is per session, and `session/load` restores the last requested pair. Codex also supports the legacy `unstable_setSessionModel` ext method. | -| `session/list` | S | ✅ | ✅ | ✅ | Uses live-preferred `ctx.sessionQuery`; returns absolute-cwd sessions newest-first with optional folded title and exact cwd filtering. Pagination is not emitted; supplied cursors are rejected. | -| `session/delete` | S | ❌ | ✅ | ✅ | Gated by `sessionCapabilities.delete`. | -| `session/fork` | U | ❌ | ✅ | ❌ | Claude ships `unstable_forkSession`; Codex does not. | - -## 2. Client methods the agent CALLS (agent → client) - -These are capabilities the bridge would *drive* on the editor. The harness runs tools in-process (its own `dsh-bash` executor, direct file I/O), so it does not yet delegate to the editor for any of these. - -| Method | Stable | Bridge | Claude | Codex | Notes | -|---|---|---|---|---|---| -| `session/update` | S | ✅ | ✅ | ✅ | The bridge's primary output channel (see [§4](#4-sessionupdate-variants)). | -| `session/request_permission` | S | ✅ | ✅ | ✅ | The bridge answers the [`ctx.approval`](../user-approval/README.md) seam for the agents it owns: an `ask` from a hook/plugin becomes an editor prompt attached to the streamed tool call, one-shot `allow_once`/`reject_once` options only. Whether a call asks is policy (nothing asks by default); `allow_always` is deferred (grant storage). | -| `fs/read_text_file` | S | ❌ | ✅ | ❌ | The harness reads files directly (it does not see the editor's unsaved buffer state). Claude delegates; Codex does not. | -| `fs/write_text_file` | S | ❌ | ✅ | ❌ | Same — direct writes, no editor delegation. | -| `terminal/create` | S | ❌ | ❌ | ❌ | Neither reference adapter drives the client terminal API either — both, like the bridge, render shell output as tool-call content + a `_meta` channel (see [§5 Terminal](#terminal-rendering)). | -| `terminal/output` | S | ❌ | ❌ | ❌ | As above. | -| `terminal/wait_for_exit` | S | ❌ | ❌ | ❌ | As above. | -| `terminal/kill` | S | ❌ | ❌ | ❌ | As above. | -| `terminal/release` | S | ❌ | ❌ | ❌ | As above. | -| `elicitation/create` · `elicitation/complete` | U | ⚠️ | ✅ | ⚠️ | The bridge drives `unstable_createElicitation` for `ask_user_question` form prompts (session-scoped, no URL-mode flow yet). Claude calls the `unstable_*` elicitation methods for MCP server elicitations; Codex maps elicitations onto `session/request_permission`. | - -## 3. Capabilities - -### 3a. `agentCapabilities` (advertised by the bridge) - -| Capability | Stable | Bridge | Claude | Codex | Notes | -|---|---|---|---|---|---| -| `loadSession` | S | ✅ | ✅ | ✅ | Advertised `true`; backs `session/load`. | -| `promptCapabilities.image` | S | ❌ | ✅ | ✅ | Bridge advertises `image: false`; image prompt blocks are rejected. | -| `promptCapabilities.audio` | S | ❌ | ❌ | ❌ | `audio: false`; neither adapter accepts audio either. | -| `promptCapabilities.embeddedContext` | S | ❌ | ✅ | ✅ | `embeddedContext: false`; embedded `resource` blocks rejected. | -| `mcpCapabilities.{http,sse}` | S | ❌ | ✅ | ⚠️ | No MCP passthrough; `mcpServers` is rejected. Claude advertises http+sse, Codex http only. | -| `sessionCapabilities.*` | S | ⚠️ | ✅ | ✅ | `list` is advertised; delete/resume/close/additionalDirectories/fork remain off. | -| `auth.logout` | S | ❌ | ✅ | ✅ | Not advertised. | -| `authMethods[]` | S | ⚠️ | ✅ | ✅ | Advertised as empty (no auth required to reach the model). | -| `agentInfo` (name/version) | S | ✅ | ✅ | ✅ | Fixed literals: `deepseek-harness-acp` / `0.0.1` (not config). | -| `_meta` custom caps | S | ❌ | ✅ | — | E.g. Claude's `claudeCode.promptQueueing`. The bridge advertises no custom `_meta`. | - -### 3b. `clientCapabilities` (consumed by the bridge) - -| Capability | Stable | Bridge | Notes | -|---|---|---|---| -| `fs.{readTextFile,writeTextFile}` | S | ❌ | Not consulted (the bridge never calls `fs/*`). | -| `terminal` | S | ❌ | Not consulted; the bridge keys terminal rendering off the Zed `_meta.terminal_output` cap instead. | -| `_meta.terminal_output` (Zed) | S (`_meta`) | ✅ | Snapshotted per session at create/load; gates terminal-card rendering. | - -## 4. `session/update` variants - -| `sessionUpdate` | Stable | Bridge | Claude | Codex | Notes | -|---|---|---|---|---|---| -| `agent_message_chunk` | S | ✅ | ✅ | ✅ | From `assistant/chunk` text-delta. | -| `agent_thought_chunk` | S | ✅ | ✅ | ✅ | From `assistant/chunk` reasoning-delta. | -| `user_message_chunk` | S | ✅ | ✅ | ✅ | Emitted during `session/load` replay to reconstruct the user side. | -| `tool_call` | S | ✅ | ✅ | ✅ | Tool-owned presentation (`presentCall`); see [§5](#5-tool-call-rendering). | -| `tool_call_update` | S | ✅ | ✅ | ✅ | From appended `tool/result` via `presentResult`; replacement results rewrite model context and do not duplicate or overwrite execution presentation. | -| `plan` | S | ❌ | ✅ | ✅ | No agent plan emitted. Both adapters emit real plan entries (Codex's `CodexEventHandler.updatePlan` maps `turn/plan/updated` → `{ sessionUpdate: 'plan', entries }`). | -| `available_commands_update` | S | ✅ | ✅ | ✅ | Full effective snapshot after create/load and registry changes; names, descriptions, and unstructured-input hints come from `ctx.commands`. | -| `current_mode_update` | S | ✅ | ✅ | ✅ | Echoed optimistically on `session/set_mode` and re-notified when a logged `plan/mode` maps to a different wire id (covers the `exit_plan_mode` tool flipping the session back). | -| `config_option_update` | S | ❌ | ✅ | ✅ | Config options exist (advertised in `session/new`/`session/load`, switched via `session/set_config_option`), but the bridge never pushes agent-initiated changes — an operator default drift is narrated to the MODEL, not echoed to the editor. Future work in the [sandbox Agent Note § Per-session mode switching](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md). | -| `usage_update` | S | ❌ | ✅ | ✅ | Token/cost reporting not surfaced (the harness records token usage internally on `assistant/message`). | -| `session_info_update` | S | ✅ | ⚠️ | ⚠️ | Log-backed title events push title and event time; load replay uses the same mapping. | - -## 5. Tool-call rendering - -Tool-call presentation is **owned by each tool** (`presentCall` / `presentResult` on the `dsh-tools` definition), not special-cased in the bridge — see the [terminal-and-tool-rendering Agent Note](../../../.agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md). - -| Feature | Stable | Bridge | Claude | Codex | Notes | -|---|---|---|---|---|---| -| `ToolCallKind` mapping | S | ✅ | ✅ | ✅ | `execute`/`read`/`edit` declared by each tool's `presentCall`; presenter-less tools render `other` (no name sniffing); richer mapping possible. | -| `ToolCallStatus` | S | ✅ | ✅ | ✅ | `in_progress` → `completed`/`failed`. | -| `content` blocks | S | ✅ | ✅ | ✅ | Text content; the description renders above the card. | -| `diff` content | S | ✅ | ✅ | ✅ | The `write`/`edit` tools declare a `diff` render intent: `presentCall` → a call-time `{ card: 'diff' }` snippet, and `presentResult` → a result-time `{ card: 'diff' }`. For an edit or an overwrite it carries the applied hunk(s) with surrounding context (one per `replace_all` site), computed from the before/after text and persisted on the `tool/result` event as `meta`; for a create (no before-image) it is an args-derived whole-file diff. The bridge emits `{ type: 'diff', path, oldText, newText }` content blocks; a successful mutation ALWAYS returns the result diff (an ACP `tool_call_update.content` replaces the call's content, so the result diff — not the model-facing text — is what survives). | -| `terminal` content | S | ✅ | ✅ | ✅ | Via the Zed `_meta` terminal convention (see below), not the spec `terminal/*` sub-protocol. | -| `locations` (follow-along) | S | ✅ | ✅ | ✅ | The `read`/`write`/`edit` tools emit `{ path, line? }` file-location hints via `presentCall`. | -| `rawInput` | S | ✅ | ⚠️ | ✅ | Parsed tool args surfaced as `rawInput`. | -| `rawOutput` | S | ❌ | ⚠️ | ✅ | Not emitted. | - -### Terminal rendering - -⚠️ Implemented via the **Zed `_meta` convention** (`terminal_info` / `terminal_output` / `terminal_exit`), gated on the client advertising `_meta.terminal_output` — NOT the spec's `terminal/create` sub-protocol (which would make the editor execute the command, bypassing `dsh-bash`'s sandbox / env-scrub / ownership / cwd). Both reference adapters take the same `_meta` approach. Live incremental streaming (`terminal_output_delta`, which Codex negotiates) is a follow-up — the bridge currently sends the full captured output once on the result. - -## 6. Session modes / config options / models - -Session modes ✅ (the [plan-mode Agent Note](../../../.agents/notes/implemented/feature/2026-07-07-plan-mode.md)): ACP owns the fixed `default` / `plan` wire vocabulary and projects it onto `ctx.planMode`'s boolean `{ active, pending? }` state; `session/set_mode` calls `set()` and `current_mode_update` tracks the optimistic selection plus each distinct committed `plan/mode` flip. Config options ✅: the bridge advertises a `model` select from the advisory LLM provider/model catalog, preserving each provider/model pair in an opaque value and grouping multiple providers. A selected pair is isolated to one session, snapshotted with the prompt for each step, applied through `agent/request`, and restored from the logged request header on load. When `ctx.permission` is composed, the bridge also advertises one `permission` select whose values come from the deployment preset table and whose current value derives from the session log; idle permission switches anchor at the next `agent/prompt-submit` inside its open turn. The division is picker-to-collaboration-state / knobs-to-config-options: individual environment knobs and the provider/model selector are not modes. See the [model-catalog Agent Note](../../../.agents/notes/implemented/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md) and [sandbox Agent Note](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md). - -## 7. Content blocks - -| Block | Stable | In prompts | In updates | Notes | -|---|---|---|---|---| -| `text` | S | ✅ | ✅ | Baseline. | -| `resource_link` | S | ✅ | ⚠️ | Accepted in prompts and rendered into text (`acpPromptToText`); not emitted as a structured update block. | -| `image` | S | ❌ | ❌ | Rejected in prompts (`promptCapabilities.image: false`). | -| `audio` | S | ❌ | ❌ | Rejected. | -| `resource` (embedded) | S | ❌ | ❌ | Rejected (`embeddedContext: false`). | - -The bridge rejects unsupported prompt blocks rather than silently dropping them (`promptHasUnsupportedContent`), per the "explicit over implicit" convention. - -## 8. Cross-cutting - -| Feature | Stable | Bridge | Notes | -|---|---|---|---| -| `StopReason` mapping | S | ✅ | `turnEndToStopReason` is total over harness turn-end reasons → `end_turn`/`max_tokens`/`cancelled`. | -| Multi-session (N per connection) | S | ✅ | Strict per-session demux; concurrent streams never interleave. See the [multi-session Agent Note](../../../.agents/notes/implemented/feature/2026-06-14-acp-multi-session.md). | -| Disconnect / disposal teardown | S | ✅ | Quiesces every live session on client disconnect or Cordis disposal. | -| `_meta` extensibility | S | ⚠️ | Consumed for the Zed terminal cap and emitted for terminal cards. Listed sessions add `deepseek-harness/sessionReference` with a canonical URI when cross-session references are mounted. | -| Background-task ownership isolation | — | ✅ | Generic `task_output`/`task_kill` reject tasks whose branded owner `SessionId` belongs to another session. | -| stdout-is-the-protocol guarantee | S | ✅ | The bridge runs in an example with no stdout logger. | - -## Gap summary - -Ranked by how commonly the reference adapters ship them and how much UX they unlock: - -1. **Session lifecycle** — `session/delete`, then `session/resume` / `session/close`. -2. **Agent plan** (`sessionUpdate: 'plan'`) — surface the loop's plan as structured entries. -3. **MCP passthrough** (`mcpServers` on `session/new` + `mcpCapabilities`). -4. **Richer prompt content** — image / embedded `resource` blocks (needs a multimodal model path). -5. **Usage reporting** (`usage_update`) — the harness already records token usage internally (on `assistant/message`). -6. **Editor filesystem delegation** (`fs/read_text_file` / `fs/write_text_file`) — lets the agent see unsaved buffers; lower priority since the harness has direct disk access. - -## Out of scope - -Unstable/draft ACP features that **neither** reference adapter ships are not tracked above: `providers/*` (LLM provider selection), `mcp/connect`·`mcp/message`·`mcp/disconnect` (client-side MCP passthrough), `nes/*` (Next Edit Suggestion), `document/did*` (LSP-style document sync), the v2 plan model (`plan_update` / `plan_removed`), boolean config options, `$/cancel_request`, and the draft Streamable-HTTP transport. They can be added if a target editor adopts them. - -## Sources - -- Stable spec: `schema/v1/schema.json` (schema `1.14.0`) and `docs/protocol/v1/*.mdx` in the [agent-client-protocol](https://github.com/agentclientprotocol/agent-client-protocol) repo. -- Reference adapters: [`claude-agent-acp`](https://github.com/zed-industries/claude-code-acp) and [`codex-acp`](https://github.com/zed-industries/codex-acp). -- Bridge: [`README.md`](README.md), [`src/index.ts`](src/index.ts), and the ACP Agent Notes under [`.agents/notes/`](../../../.agents/notes/README.md). diff --git a/packages/ui/acp/package.json b/packages/ui/acp/package.json deleted file mode 100644 index 3fb7bd5d28..0000000000 --- a/packages/ui/acp/package.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "name": "@deepseek-ai/dsh-acp", - "description": "Agent Client Protocol (ACP) bridge: drive DeepSeek Harness SDK agents from an ACP editor over JSON-RPC stdio", - "version": "0.0.1", - "private": true, - "type": "module", - "main": "lib/index.js", - "types": "lib/types/index.d.ts", - "exports": { - ".": { - "types": "./lib/types/index.d.ts", - "default": "./lib/index.js" - }, - "./invariant": { - "types": "./lib/types/invariant.d.ts", - "default": "./lib/invariant.js" - }, - "./src/*": "./src/*", - "./package.json": "./package.json" - }, - "files": [ - "lib/index.js", - "lib/invariant.js", - "lib/types/**/*.d.ts", - "lib/types/**/*.d.ts.map", - "src" - ], - "license": "BSD-3-Clause", - "dependencies": { - "@agentclientprotocol/sdk": "0.25.1", - "schemastery": "^3.17.0", - "zod": "^4.0.0" - }, - "peerDependencies": { - "@deepseek-ai/dsh-agent": "^0.0.1", - "@deepseek-ai/dsh-bash": "^0.0.1", - "@deepseek-ai/dsh-commands": "^0.0.1", - "@deepseek-ai/dsh-invariants": "^0.0.1", - "@deepseek-ai/dsh-llm": "^0.0.1", - "@deepseek-ai/dsh-llm-retry": "^0.0.1", - "@deepseek-ai/dsh-plan-mode": "^0.0.1", - "@deepseek-ai/dsh-permission": "^0.0.1", - "@deepseek-ai/dsh-sandbox": "^0.0.1", - "@deepseek-ai/dsh-session": "^0.0.1", - "@deepseek-ai/dsh-session-reference": "^0.0.1", - "@deepseek-ai/dsh-session-query": "^0.0.1", - "@deepseek-ai/dsh-session-title": "^0.0.1", - "@deepseek-ai/dsh-session-persistence": "^0.0.1", - "@deepseek-ai/dsh-system-prompt": "^0.0.1", - "@deepseek-ai/dsh-tools": "^0.0.1", - "@deepseek-ai/dsh-user-approval": "^0.0.1", - "@deepseek-ai/dsh-user-interaction": "^0.0.1", - "cordis": "^4.0.0-rc.7" - }, - "devDependencies": { - "@deepseek-ai/dsh-agent": "workspace:^", - "@deepseek-ai/dsh-agent-loop": "workspace:^", - "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", - "@deepseek-ai/dsh-bash": "workspace:^", - "@deepseek-ai/dsh-bash-local": "workspace:^", - "@deepseek-ai/dsh-commands": "workspace:^", - "@deepseek-ai/dsh-fs-local": "workspace:^", - "@deepseek-ai/dsh-fs-policy": "workspace:^", - "@deepseek-ai/dsh-invariants": "workspace:^", - "@deepseek-ai/dsh-llm": "workspace:^", - "@deepseek-ai/dsh-llm-retry": "workspace:^", - "@deepseek-ai/dsh-plan-mode": "workspace:^", - "@deepseek-ai/dsh-permission": "workspace:^", - "@deepseek-ai/dsh-sandbox": "workspace:^", - "@deepseek-ai/dsh-session": "workspace:^", - "@deepseek-ai/dsh-session-reference": "workspace:^", - "@deepseek-ai/dsh-session-query": "workspace:^", - "@deepseek-ai/dsh-session-title": "workspace:^", - "@deepseek-ai/dsh-session-persistence": "workspace:^", - "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", - "@deepseek-ai/dsh-system-prompt": "workspace:^", - "@deepseek-ai/dsh-tool-ask-user": "workspace:^", - "@deepseek-ai/dsh-tool-bash": "workspace:^", - "@deepseek-ai/dsh-tool-fs": "workspace:^", - "@deepseek-ai/dsh-tool-todo": "workspace:^", - "@deepseek-ai/dsh-tools": "workspace:^", - "@deepseek-ai/dsh-user-approval": "workspace:^", - "@deepseek-ai/dsh-user-interaction": "workspace:^", - "cordis": "^4.0.0-rc.7" - } -} diff --git a/packages/ui/acp/snapshot-replay.md b/packages/ui/acp/snapshot-replay.md deleted file mode 100644 index 9c716148aa..0000000000 --- a/packages/ui/acp/snapshot-replay.md +++ /dev/null @@ -1,27 +0,0 @@ -<!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand. - Run `pnpm run gen-doc-graphs` to regenerate. --> - -# ACP Snapshot Replay - -This graph explains what a snapshot scenario proves: recorded real-model session logs are replayed keylessly, ACP stdout is normalized and diffed, and scenario workspaces preserve tool side effects that the UI stream alone cannot prove. - -```mermaid -sequenceDiagram - participant Recorder as Real API recording - participant Fixture as snapshot fixture - participant Workspace - participant Replay as llm-replay adapter - participant ACP as acp-agent subprocess - participant Expected as stdout expected output - Recorder->>Fixture: session.jsonl + workspace inputs - Fixture->>Workspace: seed files and hook configs - Fixture->>Replay: recorded StreamChunk script - Replay->>ACP: deterministic <code>llm/stream</code> chunks - ACP->>Workspace: bash, fs, and hook side effects - ACP->>Expected: normalized sessionUpdate stream - Expected-->>ACP: diff must be empty -``` - -The fs and hook snapshot matrix is valuable because it proves world state, hook decisions, and failed tool-card rendering, not just that replay returns text. - -Maintenance mode: curated Mermaid sequence based on the snapshot test harness. diff --git a/packages/ui/acp/src/codec.ts b/packages/ui/acp/src/codec.ts deleted file mode 100644 index 91453e3387..0000000000 --- a/packages/ui/acp/src/codec.ts +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Pure, total translation between harness vocabulary and ACP wire types. - * @module @deepseek-ai/dsh-acp/codec - */ - -import type { ContentBlock } from '@deepseek-ai/dsh-llm' -import type { TurnEndReason } from '@deepseek-ai/dsh-session' -import { - SESSION_REFERENCE_SCHEME, - decodeSessionReferenceUri, - parseSessionReferenceText, - type SessionReferenceInput, -} from '@deepseek-ai/dsh-session-reference' -import type { ContentBlock as AcpContentBlock, StopReason } from '@agentclientprotocol/sdk' - -/** - * Map a harness {@link TurnEndReason} to the ACP `StopReason` wire enum. - * - * `completed` and the defensive `error` case map to `end_turn`; - * `max-tokens` maps to `max_tokens`; `aborted`, `disposed`, and `rejected` map - * to `cancelled`. The bridge rejects error turns before this mapping. Unknown - * merge-extensible kinds use legal fallback `end_turn` rather than breaking - * the prompt RPC. - * @param reason - the harness turn-end reason to translate. - * @returns the legal ACP wire value per the mapping above. - */ -export function turnEndToStopReason(reason: TurnEndReason): StopReason { - switch (reason.kind) { - case 'completed': - return 'end_turn' - case 'max-tokens': - return 'max_tokens' - case 'aborted': - return 'cancelled' - case 'disposed': - return 'cancelled' - case 'rejected': - return 'cancelled' - case 'error': - return 'end_turn' - // Merge-extensible: an unknown future TurnEndReason kind still has to produce a legal wire - // value (the SDK rejects unknown stopReason), so default to end_turn rather than - // assertNever. - default: - return 'end_turn' - } -} - -/** - * Map replayable text to ACP message content. Other block kinds use their - * prompt, thought-stream, or tool-update paths. - * @param block - the harness content block to translate. - * @returns the ACP block, or `undefined` for a kind with no message-content mapping. - */ -export function harnessBlockToAcpContent(block: ContentBlock): AcpContentBlock | undefined { - switch (block.type) { - case 'text': - return { type: 'text', text: block.text } - // reasoning → streamed as agent_thought_chunk, not a message block - // tool-call / tool-result → the tool_call / tool_call_update path - // plugin-added block types → not surfaced - default: - return undefined - } -} - -/** - * Extract plain text from an ACP prompt's content blocks. Text blocks are - * concatenated verbatim; resource links become explicit textual references so - * baseline ACP clients can point at files without the bridge silently dropping - * that context. - * @param prompt - the ACP prompt blocks to flatten. - * @returns the concatenated text, with resource links rendered as bracketed references. - */ -export function acpPromptToText(prompt: readonly AcpContentBlock[]): string { - return prompt - .flatMap((block): string[] => { - switch (block.type) { - case 'text': - return [block.text] - case 'resource_link': - return [`\n[resource_link name=${JSON.stringify(block.name)} uri=${JSON.stringify(block.uri)}]\n`] - default: - return [] - } - }) - .join('') -} - -/** ACP prompt text plus structured session references extracted from text and resource links. */ -export interface AcpReferencedPrompt { - /** Readable prompt text with opaque session URIs removed. */ - text: string - /** Structured session references in ACP block and inline appearance order. */ - references: SessionReferenceInput[] -} - -/** - * Extract canonical session references while preserving ordinary ACP resource links. - * @param prompt - already-supported ACP prompt blocks. - * @returns readable text and structured references. - * @throws when any observed `dsh-session:` URI is malformed. - */ -export function acpPromptToReferencedPrompt(prompt: readonly AcpContentBlock[]): AcpReferencedPrompt { - const references: SessionReferenceInput[] = [] - const text = prompt.flatMap((block): string[] => { - switch (block.type) { - case 'text': { - const parsed = parseSessionReferenceText(block.text) - references.push(...parsed.references) - return [parsed.text] - } - case 'resource_link': { - if (!block.uri.startsWith(SESSION_REFERENCE_SCHEME)) { - return [`\n[resource_link name=${JSON.stringify(block.name)} uri=${JSON.stringify(block.uri)}]\n`] - } - const sessionId = decodeSessionReferenceUri(block.uri) - const label = block.name === '' ? sessionId : block.name - references.push({ sessionId, label }) - return [`@${label}`] - } - default: - return [] - } - }).join('') - return { text, references } -} - -/** - * Whether an ACP prompt contains content the bridge cannot accept. Baseline ACP - * requires `text` and `resource_link`; richer inline payloads (`resource`, - * image, audio, …) are rejected rather than silently dropped. - * @param prompt - the ACP prompt blocks to inspect. - * @returns `true` when any block is neither `text` nor `resource_link`. - */ -export function promptHasUnsupportedContent(prompt: readonly AcpContentBlock[]): boolean { - return prompt.some(block => block.type !== 'text' && block.type !== 'resource_link') -} diff --git a/packages/ui/acp/src/index.ts b/packages/ui/acp/src/index.ts deleted file mode 100644 index dcc32f1c6f..0000000000 --- a/packages/ui/acp/src/index.ts +++ /dev/null @@ -1,1759 +0,0 @@ -/** - * Multi-session ACP bridge over JSON-RPC stdio. Creates or resumes agents, - * routes session-scoped events and approvals, and settles prompts by turn. - * Stdout is reserved for protocol frames. - * - * @module @deepseek-ai/dsh-acp - */ - -import type { Context } from 'cordis' -import { Readable, Writable } from 'node:stream' -import { randomUUID } from 'node:crypto' -import { isAbsolute, relative as relativePath, resolve as resolvePath, sep as pathSep } from 'node:path' -import Schema from 'schemastery' -import { - AgentSideConnection, - ndJsonStream, - PROTOCOL_VERSION, - RequestError, - type Agent as AcpAgent, - type AnyMessage, - type AuthenticateRequest, - type AvailableCommand, - type CancelNotification, - type ContentBlock as AcpContentBlock, - type CreateElicitationRequest, - type ElicitationContentValue, - type EnumOption, - type InitializeRequest, - type InitializeResponse, - type ListSessionsRequest, - type ListSessionsResponse, - type LoadSessionRequest, - type LoadSessionResponse, - type NewSessionRequest, - type NewSessionResponse, - type Plan, - type PlanEntry, - type PromptRequest, - type PromptResponse, - type SessionConfigOption, - type SessionModeState, - type SessionConfigSelectGroup, - type SessionConfigSelectOption, - type SessionNotification, - type SetSessionConfigOptionRequest, - type SetSessionConfigOptionResponse, - type SetSessionModeRequest, - type SetSessionModeResponse, - type Stream, - type StopReason, -} from '@agentclientprotocol/sdk' -import type { ContentBlock, LlmModelInfo, LlmProviderInfo } from '@deepseek-ai/dsh-llm' -import { assertNever, CallId } from '@deepseek-ai/dsh-llm' -import type {} from '@deepseek-ai/dsh-llm-retry' -import { - installAgentLlmTarget, - type Agent, - type AgentLlmTarget as LlmTarget, - type AgentLlmTargetRef as LlmTargetRef, -} from '@deepseek-ai/dsh-agent' -import type {} from '@deepseek-ai/dsh-commands' -import { encodeSessionReferenceUri } from '@deepseek-ai/dsh-session-reference' -import { displayPromptContent, SessionId, type JsonValue } from '@deepseek-ai/dsh-session' -// Side-effect type import: resolves `ctx.get('permission')` to the service. -import type {} from '@deepseek-ai/dsh-permission' -import type { SessionEvent, TodoItem, TurnEndReason } from '@deepseek-ai/dsh-session' -// Side-effect type import: adds the log-only session/title event translated below. -import type {} from '@deepseek-ai/dsh-session-title' -import type { ToolCallView, ToolRegistry, ToolResultView, TerminalResultView } from '@deepseek-ai/dsh-tools' -// Side-effect type import: declaration-merges `ctx.sessionPersistence` onto -// Context (the bridge injects it and reads `list()` for load cwd validation). -import type {} from '@deepseek-ai/dsh-session-persistence' -// Side-effect type import: declaration-merges the exact-read service used by -// session/list for live-preferred title folding. -import type {} from '@deepseek-ai/dsh-session-query' -// Type-only edge: resolves `ctx.get('planMode')` when dsh-plan-mode is composed; -// the runtime read stays opportunistic. -import type {} from '@deepseek-ai/dsh-plan-mode' -// Side-effect type import: declaration-merges prompt assembly onto Context and -// the scoped waterfall used to keep persona variables aligned with requests. -import type {} from '@deepseek-ai/dsh-system-prompt' -// Side-effect type import: declaration-merges the `approval/request` waterfall -// the bridge answers for its own agents (see the approval answerer below). -import type {} from '@deepseek-ai/dsh-user-approval' -import { - UserInteractionError, - type AskUserQuestionAnswer, - type AskUserQuestionAnswerItem, - type AskUserQuestionItem, - type AskUserQuestionOption, - type AskUserQuestionRequest, -} from '@deepseek-ai/dsh-user-interaction' -import { - acpPromptToText, - acpPromptToReferencedPrompt, - harnessBlockToAcpContent, - promptHasUnsupportedContent, - turnEndToStopReason, -} from './codec.ts' - -export const name = 'acp' -// Interface services back loading, presentation, interaction, and prompt assembly. -export const inject = ['agents', 'commands', 'sessionPersistence', 'sessionQuery', 'tools', 'userInteraction', 'llm', 'systemPrompt'] - -/** ACP `SessionInfo._meta` key carrying a ready-to-submit session-reference URI. */ -export const ACP_SESSION_REFERENCE_META_KEY = 'deepseek-harness/sessionReference' - -/** Preserve invalid-parameter detail in the SDK wire error message. */ -function invalidParams(detail: string): RequestError { - return RequestError.invalidParams(undefined, detail) -} - -const DEFAULT_SESSION_MODE_ID = 'default' -const PLAN_SESSION_MODE_ID = 'plan' -const AVAILABLE_SESSION_MODES = [ - { id: DEFAULT_SESSION_MODE_ID, name: DEFAULT_SESSION_MODE_ID }, - { id: PLAN_SESSION_MODE_ID, name: PLAN_SESSION_MODE_ID }, -] - -/** Map plan state onto ACP's named collaboration-mode protocol. */ -function sessionModeId(active: boolean): string { - return active ? PLAN_SESSION_MODE_ID : DEFAULT_SESSION_MODE_ID -} - -/** Render arbitrary thrown values without trusting their string coercion. */ -function renderThrown(value: unknown): string { - try { - return String(value) - } catch { - return '<unrenderable thrown value>' - } -} - -/** Return a server-created session id carried by an outbound success response. */ -function responseSessionId(message: AnyMessage): SessionId | undefined { - if (!('result' in message) || typeof message.result !== 'object' || message.result === null - || !('sessionId' in message.result) || typeof message.result.sessionId !== 'string') { - return undefined - } - return SessionId(message.result.sessionId) -} - -/** Observe messages only after the wrapped ACP transport has written them. */ -function observeOutbound(stream: Stream, onWritten: (message: AnyMessage) => void): Stream { - const writer = stream.writable.getWriter() - return { - readable: stream.readable, - writable: new WritableStream<AnyMessage>({ - async write(message) { - await writer.write(message) - onWritten(message) - }, - /* v8 ignore start -- the ACP SDK never closes or aborts its outbound stream; - preserve the wrapped Stream contract for other consumers nonetheless */ - close: () => writer.close(), - abort: (reason: unknown) => writer.abort(reason), - /* v8 ignore stop */ - }), - } -} - -/** Preserve failed-turn detail; plain handler errors become a generic wire internal error. */ -function internalError(detail: string): RequestError { - return RequestError.internalError(undefined, detail) -} - -function sameWorkspaceCwd(left: string, right: string): boolean { - return resolvePath(left) === resolvePath(right) -} - -function optionDescription(option: AskUserQuestionOption): string { - return option.description === undefined - ? option.label - : `${option.label}: ${option.description}` -} - -function requireStringContent( - content: Record<string, ElicitationContentValue> | null | undefined, - key: string, -): string | undefined { - const value = content?.[key] - return typeof value === 'string' && value.trim().length > 0 ? value : undefined -} - -function askAbortError(): UserInteractionError { - return new UserInteractionError('ask_user_question was aborted before the user answered', 'ASK_ABORTED') -} - -function withAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> { - if (signal === undefined) return promise - if (signal.aborted) return Promise.reject(askAbortError()) - return new Promise<T>((resolve, reject) => { - const onAbort = (): void => { - signal.removeEventListener('abort', onAbort) - reject(askAbortError()) - } - signal.addEventListener('abort', onAbort, { once: true }) - promise.then( - (value) => { - signal.removeEventListener('abort', onAbort) - resolve(value) - }, - (error: unknown) => { - signal.removeEventListener('abort', onAbort) - reject(new Error(String(error), { cause: error })) - }, - ) - }) -} - -function elicitationForQuestion( - sessionId: SessionId, - question: AskUserQuestionItem, - options: AskUserQuestionOption[], -): CreateElicitationRequest { - const title = question.header ?? 'Question' - const message = question.detail === undefined - ? question.question - : `${question.question}\n\n${question.detail}` - if (options.length === 0) { - return { - sessionId, - mode: 'form', - message, - requestedSchema: { - type: 'object', - title, - properties: { - custom: { type: 'string', title: question.question }, - }, - required: ['custom'], - }, - } - } - - const choiceOptions: EnumOption[] = options.map(option => ({ - const: option.label, - title: optionDescription(option), - })) - const choice = question.multiSelect === true - ? { - type: 'array' as const, - title: question.question, - description: 'Choose one or more options, or fill a custom answer below.', - items: { - anyOf: choiceOptions, - }, - } - : { - type: 'string' as const, - title: question.question, - description: 'Choose one option, or fill a custom answer below.', - oneOf: choiceOptions, - } - return { - sessionId, - mode: 'form', - message, - requestedSchema: { - type: 'object', - title, - properties: { - choice, - custom: { - type: 'string', - title: 'Custom answer', - description: 'Optional free-form answer. Leave empty to use the selected option.', - }, - }, - required: [], - }, - } -} - -function stringArrayContent( - content: Record<string, ElicitationContentValue> | null | undefined, - key: string, -): string[] { - const value = content?.[key] - if (Array.isArray(value)) return value.filter((item): item is string => typeof item === 'string' && item.length > 0) - return typeof value === 'string' && value.length > 0 ? [value] : [] -} - -/** Plugin config: the agent template ACP sessions are created from. */ -export interface AcpConfig { - /** Provider route for created agents. */ - provider?: string - /** Model name for created agents (must have a registered adapter). */ - model?: string - /** Runtime-only transport override; production uses stdio. */ - stream?: Stream -} - -export const Config: Schema<AcpConfig> = Schema.object({ - provider: Schema.string(), - model: Schema.string(), -}) - -/** One resolved ACP model selector plus its opaque value lookup. */ -interface ModelDirectory { - option: Extract<SessionConfigOption, { type: 'select' }> | undefined - targets: ReadonlyMap<string, LlmTarget> -} - -/** One provider and its adapter-advertised models, detached for one RPC. */ -interface ModelCatalogEntry { - provider: LlmProviderInfo - models: LlmModelInfo[] -} - -/** Per-session bridge state keyed by ACP session id. */ -interface SessionRecord { - agent: Agent - /** Exact owned-agent disposer; resolves after registry, loop, and session teardown. */ - dispose: () => Promise<void> - /** Per-session tool presentation and call/result correlation. */ - presenter: ToolPresenter - /** Terminal capability snapshot shared by matching call and result updates. */ - terminalEnabled: boolean - /** - * The last mode id this session sent to the client (advertised at - * session/new+load, echoed optimistically on session/set_mode, re-notified on - * each logged `plan/mode` that differs). `undefined` when dsh-plan-mode is - * not composed, so no mode surface is advertised or notified. - */ - lastModeId: string | undefined - /** Session-local provider/model selection and the current step snapshot. */ - target: LlmTargetRef - /** In-flight prompt and its captured turn number for exact settlement. */ - inflight: { - resolve: (reason: StopReason) => void - reject: (error: Error) => void - turn: number | undefined - } | undefined - /** Abort owner for a direct slash-command request, mutually exclusive with `inflight`. */ - commandAbort: AbortController | undefined - /** Abort owner while referenced sessions are snapshotted before enqueue. */ - promptPreparation: AbortController | undefined - /** Last idle switch per knob, anchored before the next prompt assembles. */ - pendingSwitches: { preset?: string } -} - -/** - * Drive the in-flight prompt's settle from the harness event stream. The bridge - * settles off the durable `turn/end` event for the prompt's own turn. Session - * contains post-commit observers independently, and this listener performs - * correlation in a `finally` so presentation failure cannot starve settlement. - */ -export function apply(ctx: Context, config: AcpConfig): void { - // ACP handlers execute outside this plugin's injection scope, so capture - // injected services during apply(); lazy service reads in a handler fail. - const agents = ctx.agents - const commands = ctx.commands - const llm = ctx.llm - const sessionPersistence = ctx.sessionPersistence - const logger = ctx.logger - const tools = ctx.tools - const userInteraction = ctx.userInteraction - // Presenter callbacks are contained so display failures cannot break protocol handling. - const makePresenter = (agent?: Agent): ToolPresenter => new ToolPresenter(tools, (message) => { logger.warn(message) }, agent) - - /** Resolve a complete target only; partial config remains available to other request listeners. */ - const configuredTarget = (): LlmTarget | undefined => config.provider !== undefined && config.model !== undefined - ? { provider: config.provider, model: config.model } - : undefined - - /** Install the ACP target as an agent-scoped prompt/request override. */ - const installTarget = (agentCtx: Context, target: LlmTargetRef): void => { - const agent = agentCtx.agent - /* v8 ignore next -- setup is invoked only with the freshly created agent's scoped context. */ - if (agent === undefined) throw new Error('acp: agent setup has no scoped agent') - const logged = agent.session.requestHeader()?.config - if (logged !== undefined) target.current = { provider: logged.provider, model: logged.model } - - installAgentLlmTarget(agentCtx, target) - } - - /** Opaque ACP value preserving both routing dimensions. */ - const targetValue = (target: LlmTarget): string => JSON.stringify([target.provider, target.model]) - - /** Read one detached advisory catalog snapshot before mutating session state. */ - const readModelCatalog = async (): Promise<ModelCatalogEntry[]> => Promise.all( - llm.listProviders().map(async provider => ({ - provider, - models: await llm.listModels(provider.id), - })), - ) - - /** Resolve one catalog snapshot into the ACP model selector for a session. */ - const modelDirectory = (catalog: readonly ModelCatalogEntry[], current: LlmTarget | undefined): ModelDirectory => { - if (current === undefined) return { option: undefined, targets: new Map() } - const models = catalog.map(entry => ({ provider: entry.provider, models: [...entry.models] })) - const currentProvider = models.find(entry => entry.provider.id === current.provider) - if (currentProvider === undefined) return { option: undefined, targets: new Map() } - if (!currentProvider.models.some(model => model.id === current.model)) { - currentProvider.models = [...currentProvider.models, { - provider: current.provider, - id: current.model, - name: current.model, - }] - } - - const targets = new Map<string, LlmTarget>() - const groups = models.flatMap(({ provider, models: entries }) => { - if (entries.length === 0) return [] - const options = entries.map((model): SessionConfigSelectOption => { - const target = { provider: model.provider, model: model.id } - const value = targetValue(target) - targets.set(value, target) - return { - value, - name: model.name, - ...model.description === undefined ? {} : { description: model.description }, - } - }) - return [{ group: provider.id, name: provider.name, options } satisfies SessionConfigSelectGroup] - }) - return { - option: { - id: 'model', - name: 'Model', - description: 'Sets this session\'s provider and model.', - category: 'model', - type: 'select', - currentValue: targetValue(current), - options: groups.length === 1 ? groups.flatMap(group => group.options) : groups, - }, - targets, - } - } - - const sessions = new Map<SessionId, SessionRecord>() - // Reserve an id before resume so pipelined load/new requests cannot duplicate it. - const loadingIds = new Set<SessionId>() - // A new-session response introduces its server-generated id to the client; - // keep its initial command snapshot pending until that response is written. - const pendingCommandSnapshots = new Map<SessionId, SessionRecord>() - // Async creation checks this after awaits to avoid publishing after teardown. - let closed = false - // Each new or loaded session snapshots the latest connection capability. - let terminalOutputCap = false - - // Assigned at the bottom, before any agent event can fire (a session only - // exists after `newSession`, which the client calls after construction), so - // `notify` never observes it unset — no undefined guard needed. - let conn: AgentSideConnection - - /** Return the bridge-owned record for an agent, rejecting same-id impostors. */ - const ownedRecord = (agent: Agent): SessionRecord | undefined => { - const rec = sessions.get(agent.session.id) - return rec?.agent === agent ? rec : undefined - } - - userInteraction.registerProvider({ - async ask(request: AskUserQuestionRequest): Promise<AskUserQuestionAnswer> { - if (request.agent === undefined) { - throw new UserInteractionError('ACP user questions must come from an agent-owned request', 'NO_AGENT') - } - const rec = ownedRecord(request.agent) - if (rec === undefined) { - throw new UserInteractionError('ACP user question has no matching session', 'NO_SESSION') - } - const answers: AskUserQuestionAnswerItem[] = [] - for (const question of request.questions) { - const options = question.options ?? [] - const response = await withAbort(conn.unstable_createElicitation( - elicitationForQuestion(rec.agent.session.id, question, options), - ), request.signal).catch((error: unknown) => { - if (error instanceof UserInteractionError) throw error - throw new UserInteractionError('ACP elicitation request failed', 'ASK_FAILED', { cause: error }) - }) - if (response.action !== 'accept') { - throw new UserInteractionError('ask_user_question was cancelled by the user', 'ASK_CANCELLED') - } - const custom = requireStringContent(response.content, 'custom') - const selected = stringArrayContent(response.content, 'choice') - if (custom === undefined && selected.length === 0) { - throw new UserInteractionError('ask_user_question returned no answer', 'NO_ANSWER') - } - answers.push({ - id: question.id, - selected: custom === undefined ? selected : [], - ...custom !== undefined ? { custom } : {}, - }) - } - return { answers } - }, - }) - - /** - * Reject any RPC after the bridge has torn down. The `AgentSideConnection` - * receive loop can outlive the plugin fiber — under an ACP-only HMR reload the - * `agents`/`agent-loop` services stay up while the bridge's `ctx.on` listeners - * and disposer are gone — so a late `session/new`/`load`/`prompt` could create - * or drive an agent the bridge can no longer stream or settle. Every - * state-affecting handler calls this first. (`initialize`/`authenticate` are - * pure/stateless and may answer harmlessly.) - */ - const assertOpen = (): void => { - if (closed) throw internalError('the ACP bridge has been disposed') - } - - /** Resolve the live record for a sessionId, or throw an ACP error. */ - const requireSession = (sessionId: SessionId): SessionRecord => { - const rec = sessions.get(sessionId) - if (rec === undefined) { - throw invalidParams(`unknown session: ${sessionId}`) - } - return rec - } - - /** Push a `session/update` notification, swallowing post-close rejections. */ - const notify = (notification: SessionNotification): void => { - // sessionUpdate returns a promise; a closed connection rejects it. The - // update is best-effort UI feed, never load-bearing for correctness, so a - // throwing/rejecting send must not break the turn (the chunk is emitted - // inside the model step — see docs/defensive-patterns.md "contain callback exceptions"). - /* v8 ignore next 3 -- the rejection only fires on a stdout/connection write - failure (closed pipe), which the in-memory test transport never induces; - the swallow is a defensive best-effort guard like the loop's emit traps */ - void Promise.resolve(conn.sessionUpdate(notification)).catch((error: unknown) => { - logger.warn(`acp: session/update failed: ${String(error)}`) - }) - } - - /** Project the effective registry view onto ACP discovery metadata. */ - const availableCommands = (agent: Agent): AvailableCommand[] => commands.list(agent).map(command => ({ - name: command.name, - description: command.description, - ...command.input === undefined ? {} : { input: { hint: command.input.hint } }, - })) - - /** Push the protocol's full-snapshot command catalog for one live session. */ - const notifyCommands = (rec: SessionRecord): void => { - notify({ - sessionId: rec.agent.session.id, - update: { - sessionUpdate: 'available_commands_update', - availableCommands: availableCommands(rec.agent), - }, - }) - } - - /** Enqueue a new session's first command snapshot behind its written RPC response. */ - const announceInitialCommands = (message: AnyMessage): void => { - const sessionId = responseSessionId(message) - if (sessionId === undefined) return - const rec = pendingCommandSnapshots.get(sessionId) - if (rec === undefined) return - pendingCommandSnapshots.delete(sessionId) - notifyCommands(rec) - } - - // Registration and HMR removal can affect global or one scoped view; refresh - // every announced bridge-owned session and let the registry resolve each - // exact agent. A pending new-session snapshot will read the latest registry. - ctx.on('commands/change', () => { - for (const rec of sessions.values()) { - if (!pendingCommandSnapshots.has(rec.agent.session.id)) notifyCommands(rec) - } - }) - - /** Settle the in-flight prompt with a stop reason, exactly once (no-op if none pending). */ - const settlePrompt = (rec: SessionRecord, reason: StopReason): void => { - const inflight = rec.inflight - if (inflight === undefined) return - rec.inflight = undefined - inflight.resolve(reason) - } - - /** Apply the single ACP prompt-settlement mapping for a completed turn. */ - const settleFromTurnEnd = ( - inflight: NonNullable<SessionRecord['inflight']>, - reason: TurnEndReason, - ): void => { - if (reason.kind === 'error') { - inflight.reject(internalError(`turn failed: ${'failure' in reason ? reason.failure.message : reason.message}`)) - } else { - inflight.resolve(turnEndToStopReason(reason)) - } - } - - // --- Stream the harness event taxonomy to ACP session/update -------------- - - // --- Session modes (dsh-plan-mode, opportunistic) ------------------------- - // ACP's generic mode picker projects the one plan capability as the fixed - // `default` / `plan` vocabulary. A selection is echoed optimistically; the - // logged `plan/mode` follows at the boundary and tool-driven exits are - // re-notified from that event. Environment knobs remain config options. - const modesStateFor = (agent: Agent): SessionModeState | undefined => { - const planMode = ctx.get('planMode') - if (planMode === undefined) return undefined - const { active, pending } = planMode.get(agent) - return { - availableModes: AVAILABLE_SESSION_MODES, - currentModeId: sessionModeId(pending ?? active), - } - } - - // All content streaming AND the prompt settle flow through `session/event`, - // the canonical log: every assistant/chunk and tool/call/result is logged, so - // translating from the log makes live streaming and `session/load` replay - // share the identical path (streamSessionEventUpdate). Both the owning-turn - // capture and the settle key off the log's own `turn/start`/`turn/end` — the - // durable boundary events (there is no agent/* turn mirror). `closeTurn` - // appends `turn/end` to the log unconditionally, and `turn/start` is appended - // before any step runs, so within this one listener we always see the - // prompt's turn-start (tag `inflight.turn`) then its turn-end (settle). A - // `turn/end` settles the prompt ONLY when it is the prompt's OWN turn - // (`inflight.turn === event.data.turn`) — a previous, already-cancelled turn - // whose end arrives late is ignored (see - // SessionRecord.inflight). A turn that ends `error` REJECTS the prompt (ACP - // has no error stop reason); other reasons resolve via the codec. Demux - // strictly by session id: concurrent updates may alternate on the shared - // connection, but they retain the owning id and never cross-settle. - ctx.on('session/event', (session, event: SessionEvent) => { - const rec = sessions.get(session.header.id) - if (rec === undefined) return - try { - streamSessionEventUpdate(rec.agent.session.id, event, notify, rec.presenter, { - enabled: rec.terminalEnabled, - cwd: session.header.cwd, - }, { includeUserMessages: false }) - } finally { - // Re-notify from the EVENT's value, not from planMode.get(): the service - // holds one coalesced pending slot (every flush reads the latest - // selection, so a flush can never be stale against the picker), and for - // any other writer — the exit tool, a test, a foreign plugin — the logged - // value IS the truth the picker should track, in log order. Inside the - // containment `finally` like the prompt settlement: a throwing presenter - // must not desync the picker. - if (event.type === 'plan/mode') { - const modeId = sessionModeId(event.data.active) - if (modeId !== rec.lastModeId) { - rec.lastModeId = modeId - notify({ sessionId: rec.agent.session.id, update: { sessionUpdate: 'current_mode_update', currentModeId: modeId } }) - } - } - const inflight = rec.inflight - if (inflight !== undefined && event.type === 'turn/start') { - // The first message-triggered turn after prompt installation owns the - // prompt; injection-triggered turns must not settle it early. - if (inflight.turn === undefined && event.data.trigger.kind === 'message') { - inflight.turn = event.data.turn - } - } else if (inflight !== undefined && event.type === 'turn/end' && inflight.turn === event.data.turn) { - rec.inflight = undefined - settleFromTurnEnd(inflight, event.data.reason) - } - } - }) - - // --- Approval answerer ----------------------------------------------------- - // The bridge is the approval channel for the agents it owns: an `ask` routed - // through `ctx.approval` (dsh-tools asks and sandbox escalation) becomes - // an editor permission prompt attached to the already-streamed tool call. The - // listener occupies the single decision slot ONLY for its own agents — a - // foreign or call-less request delegates via next() so another answerer (or - // the fail-closed `unavailable` default) takes the question. A rejected - // `requestPermission` (client gone, bridge torn down) propagates and the - // ApprovalService contains it as `unavailable`. Options are one-shot only: - // allow_always is a grant-storage design the approval Agent Note defers, so the - // prompt never offers a durable grant the harness could not honor. - ctx.on('approval/request', (req, next) => { - const rec = ownedRecord(req.agent) - // The protocol requires `toolCall` (the prompt renders attached to it), so - // a request without a callId has nothing to attach to — delegate. - if (rec === undefined || req.callId === undefined) return next() - return conn.requestPermission({ - sessionId: rec.agent.session.id, - toolCall: { toolCallId: req.callId }, - options: [ - { optionId: 'allow-once', name: 'Allow once', kind: 'allow_once' }, - { optionId: 'reject-once', name: 'Reject', kind: 'reject_once' }, - ], - }).then(({ outcome }) => { - if (outcome.outcome === 'cancelled') return 'cancelled' - // Only the two advertised options exist; an unknown optionId from a - // non-conforming client counts as a rejection, never a grant. - return outcome.optionId === 'allow-once' ? 'allowed-once' : 'rejected' - }) - }) - - // --- The ACP Agent method surface ----------------------------------------- - - /** Build every ACP session option from the model directory and live services. */ - const configOptionsFor = ( - agent: Agent, - directory: ModelDirectory, - pending: SessionRecord['pendingSwitches'] = {}, - ): SessionConfigOption[] => { - const options = directory.option === undefined ? [] : [directory.option] - const presets = ctx.get('permission') - if (presets === undefined) return options - const currentValue = pending.preset ?? presets.current(agent.session.events) - return [...options, { - id: 'permission', - name: 'Permissions', - description: 'The session permission preset: each choice bundles a sandbox mode and an approval policy.', - category: 'mode', - type: 'select', - currentValue, - options: [ - ...presets.names.map((name: string) => presets.optionOf(name)), - // `custom` echoes the current derived state but is never a target. - ...currentValue === 'custom' ? [presets.optionOf('custom')] : [], - ], - }] - } - - /** Whether the log has an open turn in which a config switch can be enclosed. */ - const isTurnOpen = (agent: Agent): boolean => { - const events = agent.session.events - for (let index = events.length - 1; index >= 0; index -= 1) { - const type = (events[index] as SessionEvent).type - if (type === 'turn/start') return true - if (type === 'turn/end') return false - } - return false - } - - /** Anchor last-write-wins idle switches into a just-opened turn. */ - const flushPendingSwitches = (rec: SessionRecord): void => { - const pending = rec.pendingSwitches - rec.pendingSwitches = {} - if (pending.preset === undefined) return - const presets = ctx.get('permission') - /* v8 ignore next -- a pending preset exists only if the service answered the - switch; it cannot unmount between that and the next turn in any composition. */ - if (presets === undefined) return - presets.set(rec.agent.session, pending.preset) - } - - // Prompt-submit is inside the new turn but before prompt assembly. Promptless - // injection turns leave the switch pending because they execute no request. - ctx.on('agent/prompt-submit', (agent, _content, _source, _signal, next) => { - const rec = ownedRecord(agent) - if (rec !== undefined) flushPendingSwitches(rec) - return next() - }) - - const makeAgent = (connection: AgentSideConnection): AcpAgent => { - conn = connection - return { - initialize(params: InitializeRequest): Promise<InitializeResponse> { - // Echo the client's version if we support it, else our own. We support - // exactly PROTOCOL_VERSION; any other requested version negotiates - // down to ours (the client disconnects if it can't speak it). - const protocolVersion = params.protocolVersion === PROTOCOL_VERSION ? params.protocolVersion : PROTOCOL_VERSION - // Remember the Zed terminal-output `_meta` capability: when set, bash and - // other shell tools render as a terminal card (see streamSessionEventUpdate - // + the terminal-rendering Agent Note). `_meta` is `{[k]: unknown} | null`, so - // narrow defensively to a strict boolean true. - terminalOutputCap = params.clientCapabilities?._meta?.['terminal_output'] === true - return Promise.resolve({ - protocolVersion, - // Fixed server identity: this bridge IS the harness ACP server, so the - // branding is a literal, not config (no shipped surface sets it). - agentInfo: { name: 'deepseek-harness-acp', version: '0.0.1' }, - agentCapabilities: { - loadSession: true, - sessionCapabilities: { list: {} }, - // Baseline prompt blocks only: text plus resource_link rendered as - // text. No image/audio/embeddedContext, no mcpCapabilities. - promptCapabilities: { image: false, audio: false, embeddedContext: false }, - }, - authMethods: [], - }) - }, - - authenticate(_params: AuthenticateRequest): Promise<void> { - // No auth methods advertised; nothing to do. Present because the SDK - // Agent interface requires it. - return Promise.resolve() - }, - - async listSessions(params: ListSessionsRequest): Promise<ListSessionsResponse> { - assertOpen() - if (params.cursor !== undefined && params.cursor !== null) { - throw invalidParams('session/list does not paginate; omit cursor') - } - if (params.cwd !== undefined && params.cwd !== null && !isAbsolute(params.cwd)) { - throw invalidParams('session/list cwd must be absolute') - } - const records = (await ctx.sessionQuery.listSessions()).flatMap((record) => { - const cwd = record.header.cwd - if (cwd === undefined) return [] - if (params.cwd !== undefined && params.cwd !== null && !sameWorkspaceCwd(cwd, params.cwd)) return [] - return [{ record, cwd }] - }) - const titles = await Promise.all(records.map(({ record }) => ctx.sessionQuery.readTitle(record.header.id))) - assertOpen() - const referencesAvailable = ctx.get('sessionReferences') !== undefined - return { - sessions: records.map(({ record, cwd }, index) => ({ - sessionId: record.header.id, - cwd, - ...titles[index] === undefined ? {} : { title: titles[index].title }, - ...referencesAvailable - ? { - _meta: { - [ACP_SESSION_REFERENCE_META_KEY]: { - uri: encodeSessionReferenceUri(record.header.id), - }, - }, - } - : {}, - })), - } - }, - - async newSession(params: NewSessionRequest): Promise<NewSessionResponse> { - assertOpen() - validateWorkspaceParams(params) - validateMcpServers(params) - const sessionId = SessionId(randomUUID()) - const target: LlmTargetRef = { current: configuredTarget(), assembled: undefined } - const directory = modelDirectory(await readModelCatalog(), target.current) - assertOpen() - const handle = await agents.create({ - sessionId, - meta: { cwd: params.cwd }, - agentOptions: agentOptions(config), - setup: (agentCtx) => { installTarget(agentCtx, target) }, - }) - // Agent creation may resolve after the bridge closes; dispose the handle - // instead of publishing a record that teardown could not observe. - /* v8 ignore next 4 -- the in-memory transport rejects the in-flight RPC - immediately on close; real stdio may let the handler resume */ - if (closed) { - await handle.dispose() - throw internalError('connection closed during session/new') - } - const modes = modesStateFor(handle.agent) - const record: SessionRecord = { - agent: handle.agent, - dispose: () => handle.dispose(), - presenter: makePresenter(handle.agent), - terminalEnabled: terminalOutputCap, - lastModeId: modes?.currentModeId, - target, - inflight: undefined, - commandAbort: undefined, - promptPreparation: undefined, - pendingSwitches: {}, - } - sessions.set(sessionId, record) - pendingCommandSnapshots.set(sessionId, record) - const configOptions = configOptionsFor(handle.agent, directory) - return { - sessionId, - ...modes !== undefined ? { modes } : {}, - ...configOptions.length > 0 ? { configOptions } : {}, - } - }, - - async loadSession(params: LoadSessionRequest): Promise<LoadSessionResponse> { - assertOpen() - // The wire `params.sessionId` is a raw protocol string; brand it once at - // this entry so the session collections and the resume factory see a SessionId. - const sessionId = SessionId(params.sessionId) - if (sessions.has(sessionId) || loadingIds.has(sessionId)) { - throw invalidParams(`session ${sessionId} is already loaded`) - } - validateWorkspaceParams(params) - validateMcpServers(params) - // Reserve THIS id's load slot BEFORE the await. Without it, two pipelined - // loads for the same id could both pass the guard above while the first - // resume() is pending, then both install a record and leak a second - // agent. (Distinct ids load concurrently — the set is keyed by id.) The - // slot is released in `finally` so a rejected load never wedges the id. - loadingIds.add(sessionId) - try { - // Validate the PERSISTED cwd BEFORE resuming — `list()` is a - // metadata-only read (no full-log parse), so this rejects a session we - // can't honor WITHOUT ever constructing/registering an agent (a - // post-resume reject would leak the registered agent — cancel() does not - // unregister it — and wedge the id against re-load). The session's bash - // workdir is derived from its persisted `header.cwd` and the request - // `cwd` does NOT override it (resume takes no cwd), so a session with no - // absolute persisted cwd would silently run bash in the SERVER's launch - // dir, not the client's workspace. A session created by this bridge - // always has a cwd (session/new requires it); reject the rest loudly. - // (An id unknown to `list()` falls through to resume, which rejects with - // the backend's not-found error.) - const meta = (await sessionPersistence.list()).find(m => m.id === sessionId) - if (meta !== undefined) { - const persistedCwd = meta.cwd - if (persistedCwd === undefined || !isAbsolute(persistedCwd)) { - throw invalidParams( - `session ${sessionId} has no absolute persisted cwd; cannot determine its workspace (it predates per-session cwd, or was created without one)`, - ) - } - if (!sameWorkspaceCwd(persistedCwd, params.cwd)) { - throw invalidParams(`session ${sessionId} cwd mismatch: persisted ${persistedCwd}, requested ${params.cwd}`) - } - } - const catalog = await readModelCatalog() - assertOpen() - const target: LlmTargetRef = { current: configuredTarget(), assembled: undefined } - const handle = await agents.resume({ - resumeSessionId: sessionId, - agentOptions: agentOptions(config), - setup: (agentCtx) => { installTarget(agentCtx, target) }, - }) - // The bridge may have torn down (disposal / client disconnect) while - // resume() was pending. Its listeners are gone, so installing a record - // now would resurrect a live agent the bridge can no longer drive. Bail — - // and tear down the just-resumed agent (unregister + stop + remove its - // session) before throwing, so it does not leak: it has no SessionRecord, - // so quiesce() would never see it. - /* v8 ignore next 4 -- the in-memory test transport rejects the in-flight - session/load request the instant it closes (before this post-await - code runs), so the guard can't be hit in tests; it protects the real - stdio path, where a closed pipe need not reject a mid-flight handler. */ - if (closed) { - await handle.dispose() - throw invalidParams('connection closed during session/load') - } - const directory = modelDirectory(catalog, target.current) - const agent = handle.agent - // Snapshot the terminal capability ONCE for this session (used by both - // the replay below and the post-load live stream) so a later - // `initialize` can't desync the call/result of a tool card. - const terminalEnabled = terminalOutputCap - const modes = modesStateFor(agent) - const record: SessionRecord = { - agent, - dispose: () => handle.dispose(), - presenter: makePresenter(agent), - terminalEnabled, - lastModeId: modes?.currentModeId, - target, - inflight: undefined, - commandAbort: undefined, - promptPreparation: undefined, - pendingSwitches: {}, - } - sessions.set(sessionId, record) - // Replay the persisted event log to the client as session/update. Use - // the raw event log (NOT deriveMessages, which drops assistant/chunk - // and trace events): RFC 010's load contract reconstructs the streamed - // turns — user prompts (user/message → user_message_chunk), assistant - // text and reasoning (assistant/chunk), and tool calls/results. - // - // Replay through a THROWAWAY presenter, NOT `record.presenter`: a - // historical turn that was interrupted mid-tool (a `tool/call` with no - // matching `tool/result` in the persisted log) would otherwise leave a - // stale in-flight entry on the live presenter, which then serves all - // future live events for this session. The throwaway pairs call→result - // as the log replays in order (same as live) and is discarded after, - // so the record's presenter starts clean for the post-load live stream. - const replayPresenter = makePresenter(agent) - const replayTerminal: TerminalRendering = { - enabled: terminalEnabled, - cwd: agent.session.header.cwd, - } - for (const event of agent.session.events) { - streamSessionEventUpdate(sessionId, event, notify, replayPresenter, replayTerminal) - } - notifyCommands(record) - const configOptions = configOptionsFor(agent, directory) - return { - ...modes !== undefined ? { modes } : {}, - ...configOptions.length > 0 ? { configOptions } : {}, - } - } finally { - loadingIds.delete(sessionId) - } - }, - - setSessionMode(params: SetSessionModeRequest): Promise<SetSessionModeResponse> { - assertOpen() - const rec = requireSession(SessionId(params.sessionId)) - const planMode = ctx.get('planMode') - if (planMode === undefined) throw invalidParams('session modes are not composed in this deployment') - if (params.modeId !== DEFAULT_SESSION_MODE_ID && params.modeId !== PLAN_SESSION_MODE_ID) { - throw invalidParams(`unknown session mode ${JSON.stringify(params.modeId)} — available modes: default, plan`) - } - planMode.set(rec.agent, params.modeId === PLAN_SESSION_MODE_ID) - // Optimistic echo: the pending mode IS the user's selection; the logged - // `plan/mode` lands at the next turn boundary and, matching lastModeId, - // is not re-notified. A no-op selection (already current) echoes too — - // cheap, idempotent, and the picker settles regardless. - rec.lastModeId = params.modeId - notify({ sessionId: rec.agent.session.id, update: { sessionUpdate: 'current_mode_update', currentModeId: params.modeId } }) - return Promise.resolve({}) - }, - - async prompt(params: PromptRequest): Promise<PromptResponse> { - assertOpen() - const rec = requireSession(SessionId(params.sessionId)) - if (rec.inflight !== undefined || rec.commandAbort !== undefined || rec.promptPreparation !== undefined) { - throw invalidParams('a prompt is already in flight for this session') - } - if (promptHasUnsupportedContent(params.prompt)) { - throw invalidParams('only text and resource_link prompt content is supported; image/audio/embedded resource blocks are rejected rather than silently dropped') - } - const flattenedText = acpPromptToText(params.prompt) - if (flattenedText.trim().length === 0) { - // Reject up front rather than calling send(): an empty prompt would - // queue no work, no turn would start, and the RPC would hang forever - // waiting for a settle that never comes. - throw invalidParams('empty prompt') - } - // Direct commands consume ordinary ACP flattening before reference - // extraction, so URI-shaped arguments remain opaque to the bridge. - const commandLine = flattenedText.startsWith('/') ? flattenedText : undefined - if (commandLine !== undefined) { - const controller = new AbortController() - rec.commandAbort = controller - try { - const result = await commands.execute(rec.agent, commandLine, controller.signal) - if (result !== undefined && result.text !== undefined && result.text !== '') { - notify({ - sessionId: rec.agent.session.id, - update: { - sessionUpdate: 'agent_message_chunk', - content: { - type: 'text', - text: result.kind === 'error' ? `Error: ${result.text}` : result.text, - }, - }, - }) - } else if (result === undefined) { - notify({ - sessionId: rec.agent.session.id, - update: { - sessionUpdate: 'agent_message_chunk', - content: { type: 'text', text: `Error: unknown command: ${commandLine}` }, - }, - }) - } - return { stopReason: 'end_turn' } - } catch (error: unknown) { - if (controller.signal.aborted) return { stopReason: 'cancelled' } - const rendered = renderThrown(error) - logger.warn(`acp: command failed: ${rendered}`) - notify({ - sessionId: rec.agent.session.id, - update: { - sessionUpdate: 'agent_message_chunk', - content: { type: 'text', text: `Error: command failed: ${rendered}` }, - }, - }) - return { stopReason: 'end_turn' } - } finally { - rec.commandAbort = undefined - } - } - let referencedPrompt: ReturnType<typeof acpPromptToReferencedPrompt> - try { - referencedPrompt = acpPromptToReferencedPrompt(params.prompt) - } catch (error: unknown) { - throw invalidParams(`invalid session reference: ${renderThrown(error)}`) - } - const { text } = referencedPrompt - let preparedContent: ContentBlock[] = [{ type: 'text', text }] - let preparedContexts: NonNullable<Parameters<Agent['followup']>[1]>['contexts'] = [] - if (referencedPrompt.references.length > 0) { - const sessionReferences = ctx.get('sessionReferences') - if (sessionReferences === undefined) { - throw invalidParams('session reference capability unavailable') - } - const controller = new AbortController() - rec.promptPreparation = controller - try { - const prepared = await sessionReferences.prepare( - rec.agent, - preparedContent, - referencedPrompt.references, - controller.signal, - ) - preparedContent = prepared.content - preparedContexts = prepared.contexts - } catch (error: unknown) { - if (controller.signal.aborted) return { stopReason: 'cancelled' } - throw invalidParams(`session reference preparation failed: ${renderThrown(error)}`) - } finally { - rec.promptPreparation = undefined - } - assertOpen() - } - // Install the in-flight slot BEFORE followup() (followup does not synchronously - // flip status to running; the session/event listener records the turn - // number and settle/rejects it). Capture the log length now as the - // A turn that ends in error rejects this promise (the codec never - // produces an error stop reason). - const stopReason = await new Promise<StopReason>((resolve, reject) => { - rec.inflight = { resolve, reject, turn: undefined } - rec.agent.followup(preparedContent, { contexts: preparedContexts }) - }) - return { stopReason } - }, - - cancel(params: CancelNotification): Promise<void> { - const rec = sessions.get(SessionId(params.sessionId)) - if (rec === undefined) return Promise.resolve() - // session/cancel maps to the queue-aware agent.cancel({ kind: 'user' }): it aborts - // a RUNNING step, clears the queued + steering FIFOs, and drops a - // turn that is about to start (the pre-step window) — so a queued-but- - // not-yet-started prompt never runs, while a prompt accepted afterward - // remains a separate queued turn. Scoped to THIS session's - // agent — a cancel in one session never touches another's stream or - // pending prompt (multi-session isolation). - // We ALSO settle the in-flight prompt - // as cancelled directly here: do NOT rely on the resulting turn/end to - // settle it, because cancel() may drop the turn before any turn/end is - // emitted, and removing this direct settle would move the RPC's - // resolution onto a later observer path, changing its timing. - if (rec.promptPreparation !== undefined) { - rec.promptPreparation.abort(new Error('session/cancel')) - } else if (rec.commandAbort !== undefined) { - rec.commandAbort.abort(new Error('session/cancel')) - } else { - rec.agent.cancel({ kind: 'user' }) - settlePrompt(rec, 'cancelled') - } - return Promise.resolve() - }, - - async setSessionConfigOption(params: SetSessionConfigOptionRequest): Promise<SetSessionConfigOptionResponse> { - assertOpen() - const rec = requireSession(SessionId(params.sessionId)) - // Every advertised option is a select, so the boolean-shaped variant - // is a protocol misuse regardless of configId. - if (typeof params.value !== 'string') { - throw invalidParams(`config option ${params.configId} is a select; boolean values are not accepted`) - } - let directory = modelDirectory(await readModelCatalog(), rec.target.current) - // Open-turn switches append immediately; idle switches wait for the - // next prompt-submit. Only values advertised by this composition are - // accepted, and the session log remains the durable store. - switch (params.configId) { - case 'model': { - const target = directory.targets.get(params.value) - if (target === undefined) { - throw invalidParams(`unknown model value ${JSON.stringify(params.value)}`) - } - rec.target.current = { ...target } - const option = directory.option - /* v8 ignore next -- `targets` is populated only while constructing - this selector; a found target therefore proves it exists. */ - if (option === undefined) throw internalError('model directory target has no selector') - directory = { - ...directory, - option: { ...option, currentValue: params.value }, - } - break - } - case 'permission': { - const presets = ctx.get('permission') - if (presets === undefined) { - throw invalidParams(`unknown permission value ${JSON.stringify(params.value)}`) - } - // A current-value echo is acknowledged without recording a switch. - const current = rec.pendingSwitches.preset ?? presets.current(rec.agent.session.events) - if (params.value === current) break - if (!presets.names.includes(params.value)) { - throw invalidParams(`unknown permission value ${JSON.stringify(params.value)}`) - } - if (isTurnOpen(rec.agent)) presets.set(rec.agent.session, params.value) - else rec.pendingSwitches.preset = params.value - break - } - default: - throw invalidParams(`unknown config option ${JSON.stringify(params.configId)}`) - } - // The spec requires the COMPLETE refreshed config state in the response - // (a change may cascade); ours are independent, but the contract holds. - return { configOptions: configOptionsFor(rec.agent, directory, rec.pendingSwitches) } - }, - } - } - - // --- Connection lifecycle -------------------------------------------------- - - // The transport stream. Production wires stdio (stdout carries the protocol); - // tests inject an in-memory pipe pair via config.stream to drive the bridge - // without a subprocess. ndJsonStream is the SDK's stdio framing helper. The - // AgentSideConnection constructor synchronously invokes makeAgent (assigning - // the outer `conn`), so `conn` is set before any agent method runs. - /* v8 ignore next 4 -- production stdio wiring; tests always inject config.stream */ - const stream: Stream = config.stream ?? ndJsonStream( - Writable.toWeb(process.stdout) as WritableStream<Uint8Array>, - Readable.toWeb(process.stdin) as ReadableStream<Uint8Array>, - ) - conn = new AgentSideConnection(makeAgent, observeOutbound(stream, announceInitialCommands)) - - /** - * Tear ALL live sessions down to quiescence (docs/defensive-patterns.md "dispose must reach - * quiescence"): for each session settle any pending prompt `cancelled`, then - * run that session's {@link AgentHandle} `dispose()` — which stops the loop - * (sets `disposed`, aborts the in-flight step), AWAITS the loop's exit (the - * final `turn/end` + `session/flush` are captured while the store-owned publication hooks are still - * attached), unregisters the agent, and removes its session from the store. - * The per-session disposes run in parallel. Idempotent — clears the `sessions` - * map first and memoizes, so a second call (close racing dispose) is a no-op. - * Shared by Cordis disposal AND client disconnect (`conn.closed`). - * - * Per-agent disposal closes the queued-before-run window through the DISPOSED - * path, not `cancel()`: the start-disposer resolves `handle.disposed`, which - * wakes the parked loop, and `isDisposed()` breaks the loop before a - * queued-but-not-yet-running turn can start (a turn cut off mid-flight ends - * with reason `disposed`, not `aborted`). A bare client disconnect (resolves - * `conn.closed` WITHOUT disposing the fiber) thus leaves NO registered agent - * and NO session-store entry — not an idled-but-still-registered one. When the - * fiber IS disposed (whole-context or an ACP-only HMR - * `acpFiber.dispose()`), this same memoized teardown runs first; the factory's - * register+start+session effects are ALSO bound to the bridge fiber (the - * factory is reached through this bridge's traceable service proxy, so - * `AgentLoop.start`'s `this.ctx.effect(...)` binds to the CALLER context — the - * bridge fiber), so any agent this path did not reach is still reclaimed by - * fiber disposal. - */ - let quiescing: Promise<void> | undefined - const quiesce = (): Promise<void> => { - // Memoize: disposal and client-disconnect can both fire. The first call owns - // the teardown; later callers await the SAME promise so `fiber.dispose()` - // never returns before an in-flight close teardown has finished. - if (quiescing !== undefined) return quiescing - // Mark closed BEFORE draining: a `session/load` mid-`resume()` (no record - // installed yet) must observe this after its await and refuse to install a - // post-teardown record. Set even when there are no live sessions. - closed = true - pendingCommandSnapshots.clear() - const recs = [...sessions.values()] - sessions.clear() - if (recs.length === 0) return Promise.resolve() - quiescing = (async () => { - await Promise.all(recs.map(async (rec) => { - settlePrompt(rec, 'cancelled') - rec.commandAbort?.abort(new Error('ACP connection closed')) - rec.promptPreparation?.abort(new Error('ACP connection closed')) - // Per-agent dispose (the AgentHandle disposer): unregister this agent, - // stop its loop (sets disposed + aborts the in-flight step), await - // quiescence (the loop exit + final flush), and remove its session — so - // a bare client disconnect leaves NO registered agent and NO - // session-store entry, not just an idled-but-still-registered one. - await rec.dispose() - })) - })() - return quiescing - } - - // Client disconnect: when the ACP transport closes (editor quits, pipe EOF), - // the in-flight turn would otherwise keep running and its `session/update` - // writes would be silently swallowed by `notify()`. Tear the session down so - // a vanished client does not leave an orphaned running agent. `conn.closed` - // rejects/resolves once; contain any teardown throw (nothing else can act on - // it — the connection is already gone). The Cordis disposer below still runs - // on normal shutdown and is idempotent with this. - /* v8 ignore start -- the .catch arrow is a defensive guard: conn.closed - settling rejected or quiesce() throwing on an already-closed connection is - not reproducible through the in-memory test transport (it never severs - mid-run), and there is nothing else to act on once the connection is gone — - the swallow mirrors notify(). */ - void conn.closed.then(quiesce).catch((error: unknown) => { - logger.warn(`acp: connection-close teardown failed: ${String(error)}`) - }) - /* v8 ignore stop */ - - ctx.effect(() => quiesce, 'acp.connection') -} - -/** - * Build per-agent options from the plugin config, omitting absent fields - * (exactOptionalPropertyTypes: never assign `undefined` to an optional key). - * Exported for unit coverage of both the present and absent branches. - * @param config - the plugin config carrying the optional provider/model target. - * @returns the per-agent options, with each configured target field present. - */ -export function agentOptions(config: AcpConfig): { provider?: string; model?: string } { - return { - ...config.provider !== undefined ? { provider: config.provider } : {}, - ...config.model !== undefined ? { model: config.model } : {}, - } -} - -/** - * Validate the `cwd`/`additionalDirectories` contract shared by `session/new` - * and `session/load`: `cwd` must be absolute (a relative path would be ambiguous - * as a workspace root). The persisted-cwd equality check for `session/load` - * happens after the metadata lookup; this validator only enforces request shape: - * - `session/new`: the validated `cwd` becomes the session's `SessionHeader.cwd` - * (via `agents.create({meta:{cwd}})`) and thus the default bash workdir. - * - `session/load`: the request `cwd` must be absolute AND must match the - * PERSISTED `header.cwd`, which stays authoritative for the bash workdir — - * the request cwd does not override it. - * Any absolute path is accepted (the per-session cwd flows to the bash executor - * — see `dsh-tool-bash`), so the server no longer has to launch in the - * workspace. `additionalDirectories` must still be empty: widening the - * tool/filesystem scope beyond the single cwd is a separate, unimplemented - * concern (a sandbox seam), and silently ignoring extra roots would desync the - * client's filesystem-scope UI. Both request shapes carry `cwd: string` and - * `additionalDirectories?: string[]`, so one validator covers both. - */ -function validateWorkspaceParams(params: { cwd: string; additionalDirectories?: string[] }): void { - if (!isAbsolute(params.cwd)) { - throw invalidParams(`cwd must be an absolute path: ${params.cwd}`) - } - if (params.additionalDirectories !== undefined && params.additionalDirectories.length > 0) { - throw invalidParams('additionalDirectories is not supported in this MVP') - } -} - -function validateMcpServers(params: { mcpServers?: unknown[] }): void { - if (params.mcpServers !== undefined && params.mcpServers.length > 0) { - throw invalidParams('mcpServers is not supported in this MVP') - } -} - -/** - * Translate a single harness {@link SessionEvent} into the `session/update` - * notification(s) it produces, pushing each via `notify`. Shared by live - * streaming (`session/event`) and `session/load` replay so both paths emit an - * identical update stream from the same event log. - * - * - `assistant/chunk` text-delta/reasoning-delta → message/thought chunks - * - `llm/retry` and terminal model failure → visible discarded-attempt markers - * - `user/message` → `user_message_chunk` during load replay only — so a - * loaded transcript reconstructs the USER side of each turn without echoing - * a live `session/prompt` back to the client - * - `tool/call` → `tool_call` (pending) - * - appended `tool/result` → `tool_call_update` (completed/failed) - * - replacement `tool/result` → no update (context rewrite, not execution) - * - * Tool-call presentation (title/kind/rawInput, and the completed-state content) - * is owned by each TOOL via `presentCall`/`presentResult` — the bridge never - * special-cases tool names. `presenter` resolves those from the tool registry - * and remembers each call's `(name, args)` so the completed `tool/result` (which - * carries neither) can find its tool. A {@link nullToolPresenter} gives the - * generic fallback (title = tool name, raw args as input) when no registry is - * available (e.g. pure translator tests). - * - * Other event types (turn/step boundaries, injected-context user messages, …) - * produce no client update. - * @param sessionId - the ACP session id stamped on every emitted notification. - * @param event - the harness session event to translate. - * @param notify - sink for each produced `session/update` notification; called - * zero or more times per event (best-effort UI feed, never load-bearing). - * @param presenter - resolves tool-owned render intent for tool events; - * defaults to the generic-fallback {@link nullToolPresenter}. - * @param terminal - the session's terminal-rendering context; defaults to - * disabled (the plain-text console-block fallback). - * @param options - `includeUserMessages` (default `true`): live streaming - * passes `false` so a prompt the client just sent is not echoed back. - */ -export function streamSessionEventUpdate( - sessionId: SessionId, - event: SessionEvent, - notify: (notification: SessionNotification) => void, - presenter: Pick<ToolPresenter, 'call' | 'result'> = nullToolPresenter, - terminal: TerminalRendering = noTerminalRendering, - options: { includeUserMessages?: boolean } = {}, -): void { - const includeUserMessages = options.includeUserMessages ?? true - switch (event.type) { - case 'assistant/chunk': { - const chunk = event.data.chunk - if (chunk.type === 'text-delta') { - notify({ sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: chunk.text } } }) - } else if (chunk.type === 'reasoning-delta') { - notify({ sessionId, update: { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: chunk.text } } }) - } - return - } - case 'llm/retry': { - const text = '\n\n[Previous model attempt discarded; retrying ' - + `${event.data.retry}/${event.data.maxRetries} in ${event.data.delayMs}ms: ` - + `${event.data.failure.message}]\n\n` - notify({ sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } } }) - return - } - case 'user/message': { - if (!includeUserMessages) return - // Only a direct human prompt replays as a user message; injected context - // (plugin/goal source) is not the user's turn and produces no update. - if (event.data.source.kind !== 'user') return - // Replay the user's prompt so a loaded session shows both sides of each - // turn. Live prompt turns suppress this path to avoid duplicating what - // the client just sent. - for (const block of displayPromptContent(event.data)) { - const content = harnessBlockToAcpContent(block) - if (content !== undefined) { - notify({ sessionId, update: { sessionUpdate: 'user_message_chunk', content } }) - } - } - return - } - case 'tool/call': { - const view = presenter.call(event.data.callId, event.data.name, event.data.arguments) - notify({ sessionId, update: toolCallUpdate(event.data.callId, view, terminal) }) - return - } - case 'tool/result': { - // Replacements (for example model-free pruning) are transcript rewrites, - // not repeated tool executions. Re-presenting one would consume no - // pending call and could clobber the original terminal/diff completion. - if (event.surfaceOp !== undefined && event.surfaceOp !== 'append') return - const view = presenter.result(event.data.callId, event.data.content, event.data.isError, event.data.meta) - notify({ sessionId, update: toolResultUpdate(event.data.callId, view, event.data.isError, terminal) }) - return - } - case 'todo/write': { - notify({ sessionId, update: { sessionUpdate: 'plan', ...todosToPlan(event.data.todos) } }) - return - } - case 'session/title': { - notify({ - sessionId, - update: { - sessionUpdate: 'session_info_update', - title: event.data.title, - updatedAt: new Date(event.time).toISOString(), - }, - }) - return - } - case 'turn/end': { - if (event.data.reason.kind !== 'error' || !('failure' in event.data.reason)) return - const text = `\n\n[Model attempt failed; any partial output above is discarded: ${event.data.reason.failure.message}]\n\n` - notify({ sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } } }) - return - } - // non-error turn/step boundaries, injected-context user messages, steering, - // assistant/message — no direct ACP client update. - default: - return - } -} - -/** - * Map a whole harness todo list to an ACP replacement plan, using medium - * priority because harness todos do not carry one. - * @param todos - complete harness todo list. - * @returns one ACP plan entry per todo. - */ -export function todosToPlan(todos: TodoItem[]): Plan { - return { entries: todos.map((todo): PlanEntry => ({ content: todo.content, priority: 'medium', status: todo.status })) } -} - -/** Per-session terminal capability and workspace used while translating updates. */ -export interface TerminalRendering { - enabled: boolean - /** The session workspace cwd (terminal-card header default); `undefined` when the session has none. */ - cwd: string | undefined -} - -/** Default: terminal rendering off (the ` ```console ` text fallback path). */ -const noTerminalRendering: TerminalRendering = { enabled: false, cwd: undefined } - -/** - * Resolve tool-owned call/result views with a generic fallback. Per-session - * state correlates results with call arguments; interrupted calls may retain an - * entry only until that session's presenter is discarded. - */ -export class ToolPresenter { - private readonly pending = new Map<CallId, { name: string; args: unknown; card: ToolCallView['card'] }>() - - /** - * @param tools - registry used to resolve executing definitions. - * @param onError - contained presenter-error sink before generic fallback. - * @param agent - optional scoped registry view for the executing agent. - */ - constructor( - private readonly tools: Pick<ToolRegistry, 'get'>, - private readonly onError: (message: string) => void = () => {}, - private readonly agent?: Agent, - ) {} - - /** - * Pending-state render intent for a `tool/call`; remembers `(name, args, card)` - * for the matching result. - * @param callId - the call id the matching `tool/result` will look up. - * @param name - the tool name, resolved against the registry for `presentCall`. - * @param argsJson - raw event arguments parsed for presentation. - * @returns the tool-owned view or generic fallback. - */ - call(callId: CallId, name: string, argsJson: string): ToolCallView { - const args = parseToolArguments(argsJson) - let present: ToolCallView | undefined - try { - present = this.tools.get(name, this.agent)?.presentCall?.(args) - } catch (error: unknown) { - // A throwing presentCall must not break streaming: log and fall back. - this.onError(`acp: tool "${name}" presentCall threw, using generic presentation: ${String(error)}`) - present = undefined - } - // Tool names never imply presentation kind; richer cards are tool-owned. - const view: ToolCallView = present ?? { card: 'generic', title: name, kind: 'other', rawInput: args } - this.pending.set(callId, { name, args, card: view.card }) - return view - } - - /** - * Completed-state render intent for a `tool/result`; consumes the remembered - * `(name, args, card)`. - * @param callId - matching call id; unknown or late ids use raw content. - * @param content - result content used by the fallback and fill-in body. - * @param isError - whether the result is an error, forwarded to `presentResult`. - * @param meta - the result's machine-readable meta, forwarded when present. - * @returns a normalized tool-owned view or raw-content fallback. - */ - result(callId: CallId, content: ContentBlock[], isError: boolean, meta?: JsonValue): ToolResultView { - const call = this.pending.get(callId) - this.pending.delete(callId) - // No remembered call (unknown/late callId) → nothing to present from; raw content. - if (call === undefined) return { card: 'generic', content } - let present: ToolResultView | undefined - try { - present = this.tools.get(call.name, this.agent) - ?.presentResult?.(call.args, { content, isError, ...meta !== undefined ? { meta } : {} }) - } catch (error: unknown) { - // A throwing presentResult must not break streaming/replay: log + fall back. - this.onError(`acp: tool "${call.name}" presentResult threw, using raw result: ${String(error)}`) - present = undefined - } - if (present === undefined) return { card: 'generic', content } - // Orphan guard: only honor a `terminal` result when the PENDING call was a - // terminal. A result-only terminal with no matching call-side terminal would - // orphan `_meta.terminal_output` to a terminal Zed never made — drop it back - // to the raw content. - if (present.card === 'terminal' && call.card !== 'terminal') return { card: 'generic', content } - // A generic result that reformats no content keeps the RAW result content - // (the tool replaced only the title); fill it so the card is never blanked. - if (present.card === 'generic' && present.content === undefined) return { ...present, content } - return present - } -} - -/** - * The no-op presenter used when no tool registry is available (e.g. the pure - * translator tests): every tool gets the generic fallback presentation, and - * results pass their raw content through unchanged. - */ -export const nullToolPresenter: Pick<ToolPresenter, 'call' | 'result'> = { - call: (_callId, name, argsJson) => ({ card: 'generic', title: name, kind: 'other', rawInput: parseToolArguments(argsJson) }), - result: (_callId, content) => ({ card: 'generic', content }), -} - -/** Parse a tool-call arguments JSON string for `rawInput`; raw string on failure. */ -function parseToolArguments(args: string): unknown { - try { - return args ? JSON.parse(args) : {} - } catch { - // The model produced non-JSON arguments; surface the raw string rather - // than dropping it. (The harness tool layer handles validation; here we - // only feed the client's tool-call UI.) - return args - } -} - -/** Map harness tool-result content blocks to ACP tool-call content (text only). */ -function toolResultContent(blocks: ContentBlock[]): { type: 'content'; content: AcpContentBlock }[] { - const out: { type: 'content'; content: AcpContentBlock }[] = [] - for (const block of blocks) { - const content = harnessBlockToAcpContent(block) - if (content !== undefined) out.push({ type: 'content', content }) - } - return out -} - -/** The `session/update` payload for a `tool_call` / `tool_call_update`. */ -type ToolCallSessionUpdate = SessionNotification['update'] - -/** An ACP tool-call content block (a text/image `content`, a `diff`, or a `terminal`). */ -type AcpToolCallContent = - | { type: 'content'; content: AcpContentBlock } - | { type: 'diff'; path: string; oldText: string | null; newText: string } - | { type: 'terminal'; terminalId: string } - -/** Relativize only in-workspace title text; location and diff paths stay raw. */ -function displayTitle(title: string, rawPath: string | undefined, sessionCwd: string | undefined): string { - if (rawPath === undefined || sessionCwd === undefined || !isAbsolute(rawPath) || !isAbsolute(sessionCwd)) return title - const rel = relativePath(sessionCwd, rawPath) - // Test the `..` segment, not a character prefix: `..cache/x` is in-workspace. - if (rel.length === 0 || rel === '..' || rel.startsWith(`..${pathSep}`)) return title - return title.split(rawPath).join(rel) -} - -/** - * Resolve the terminal card's header cwd. A `TerminalCallView.cwd` (a model - * `workdir`) wins when ABSOLUTE; a RELATIVE one resolves against the session cwd - * (matching how `dsh-tool-bash` resolves a relative workdir for execution, so the - * header matches where the command actually ran); when the view gives no cwd, the - * session workspace cwd is the default. Returns `undefined` only when neither the - * view nor the session supplies one (Zed then shows "current directory"). - */ -function terminalCwd(viewCwd: string | undefined, sessionCwd: string | undefined): string | undefined { - if (viewCwd === undefined) return sessionCwd - if (isAbsolute(viewCwd)) return viewCwd - return sessionCwd !== undefined ? resolvePath(sessionCwd, viewCwd) : viewCwd -} - -/** - * Build the `tool_call` (pending) `session/update` from a tool's render intent. - * Switches on `view.card`: a `generic` card maps title/kind/rawInput/content/ - * locations; a `diff` card emits `{ type: 'diff' }` content blocks (the editor's - * inline diff) plus follow-along locations; a `terminal` card renders as a - * terminal when the client is capable (a `terminal` content block + the - * `_meta.terminal_info` cwd header) and otherwise falls back to a generic execute - * card whose body is the description. File-card titles are relativized against the - * session cwd (see {@link displayTitle}). - */ -function toolCallUpdate(callId: CallId, view: ToolCallView, terminal: TerminalRendering): ToolCallSessionUpdate { - switch (view.card) { - case 'generic': - return { - sessionUpdate: 'tool_call', - toolCallId: callId, - // Relativize the title against the session cwd when the card carries a - // file location (a read/file card); a location-less card (bash, todo) - // has no path to relativize, so the title is used as-is. - title: displayTitle(view.title, view.locations?.[0]?.path, terminal.cwd), - kind: view.kind ?? 'other', - status: 'in_progress', - ...view.rawInput !== undefined ? { rawInput: view.rawInput } : {}, - ...view.locations !== undefined ? { locations: view.locations } : {}, - ...view.content !== undefined && view.content.length > 0 ? { content: toolResultContent(view.content) } : {}, - } - case 'diff': { - const rawPath = view.locations?.[0]?.path ?? view.diffs[0]?.path - const content: AcpToolCallContent[] = view.diffs.map(d => ({ type: 'diff', path: d.path, oldText: d.oldText, newText: d.newText })) - return { - sessionUpdate: 'tool_call', - toolCallId: callId, - title: displayTitle(view.title, rawPath, terminal.cwd), - kind: 'edit', - status: 'in_progress', - ...view.locations !== undefined ? { locations: view.locations } : {}, - ...content.length > 0 ? { content } : {}, - } - } - case 'terminal': { - // A terminal-rendered call gets a terminal CARD when the client supports it: - // the description renders ABOVE the card, then the terminal block, plus - // `_meta.terminal_info` (the cwd header). Without the capability it is an - // ordinary execute card whose body is the description and whose rawInput is - // the command; the output arrives as text on the result. - const asTerminal = terminal.enabled - const description: AcpToolCallContent[] = view.description !== undefined - ? [{ type: 'content', content: { type: 'text', text: view.description } }] - : [] - const content: AcpToolCallContent[] = [ - ...description, - ...asTerminal ? [{ type: 'terminal' as const, terminalId: callId }] : [], - ] - return { - sessionUpdate: 'tool_call', - toolCallId: callId, - title: view.title, - kind: 'execute', - status: 'in_progress', - rawInput: view.title, - ...content.length > 0 ? { content } : {}, - ...asTerminal - ? { _meta: { terminal_info: { terminal_id: callId, cwd: terminalCwd(view.cwd, terminal.cwd) } } } - : {}, - } - } - default: - return assertNever(view, 'ToolCallView.card') - } -} - -/** The `terminal_exit` `_meta` entry for a completed terminal call. */ -interface TerminalExitMeta { - terminal_exit?: { terminal_id: string; exit_code?: number; signal?: string } -} - -/** - * Build the optional `terminal_exit` portion of a `tool_call_update`'s `_meta` - * from a terminal result: a `signal` death yields `{signal}`, an `exitCode` - * yields `{exit_code}`, and neither yields nothing (the card simply shows no exit - * pill). Spread into the `_meta` object alongside `terminal_output`. - */ -function terminalExitMeta(callId: string, view: TerminalResultView): TerminalExitMeta { - if (view.signal !== undefined) return { terminal_exit: { terminal_id: callId, signal: view.signal } } - if (view.exitCode !== undefined) return { terminal_exit: { terminal_id: callId, exit_code: view.exitCode } } - return {} -} - -/** - * Build the `tool_call_update` (completed) `session/update` from a result render - * intent. A `generic` result sends its reformatted content (or the raw result); - * a `terminal` result rides its output/exit on `_meta` when the client is capable - * (the terminal card consumes them and `content` is OMITTED — a - * `tool_call_update.content` REPLACES the call's content collection in Zed, so - * re-sending would clobber the terminal block the call installed) and otherwise - * derives the fenced ```console fallback from `output`. A `diff` result emits its - * `{ type: 'diff' }` content blocks (an applied hunk, or a whole-file diff for a - * create), which replace the diff the call installed — so the model-facing result - * text can never clobber it. - */ -function toolResultUpdate(callId: CallId, view: ToolResultView, isError: boolean, terminal: TerminalRendering): ToolCallSessionUpdate { - const status = isError ? 'failed' as const : 'completed' as const - switch (view.card) { - case 'terminal': { - const output = view.output ?? '' - if (terminal.enabled) { - return { - sessionUpdate: 'tool_call_update', - toolCallId: callId, - status, - ...view.title !== undefined ? { title: view.title } : {}, - _meta: { - terminal_output: { terminal_id: callId, data: output }, - ...terminalExitMeta(callId, view), - }, - } - } - // No terminal capability: the bridge derives the fenced ```console fallback. - const fenced = `\`\`\`console\n${output.replace(/\n+$/, '')}\n\`\`\`` - return { - sessionUpdate: 'tool_call_update', - toolCallId: callId, - status, - content: [{ type: 'content', content: { type: 'text', text: fenced } }], - ...view.title !== undefined ? { title: view.title } : {}, - } - } - case 'generic': - return { - sessionUpdate: 'tool_call_update', - toolCallId: callId, - status, - // The presenter fills a generic result's content from the raw result, so - // `content` is always defined here; the guard keeps this total for a - // directly-constructed view. - /* v8 ignore next -- content always defined via the presenter (see above) */ - ...view.content !== undefined ? { content: toolResultContent(view.content) } : {}, - ...view.title !== undefined ? { title: view.title } : {}, - } - case 'diff': { - // A result-time diff: emit one `{ type: 'diff' }` content block per entry - // (an applied hunk for an edit/overwrite, or a whole-file diff for a - // create), mirroring the call-side diff arm. `tool_call_update.content` - // REPLACES the call's content in an editor, so this result diff supersedes - // the diff the pending card installed (and keeps the model-facing result - // text from clobbering it). - const content: AcpToolCallContent[] = view.diffs.map(d => ({ type: 'diff', path: d.path, oldText: d.oldText, newText: d.newText })) - // Relativize the replacement title against the session cwd from the diff - // path, exactly as the call-side card does — `tool_call_update.title` - // replaces the card header, so a raw absolute path here would undo the - // pending card's relativized title. - const title = view.title !== undefined ? displayTitle(view.title, view.diffs[0]?.path, terminal.cwd) : undefined - return { - sessionUpdate: 'tool_call_update', - toolCallId: callId, - status, - ...content.length > 0 ? { content } : {}, - ...title !== undefined ? { title } : {}, - } - } - default: - return assertNever(view, 'ToolResultView.card') - } -} diff --git a/packages/ui/acp/tests/approval.spec.ts b/packages/ui/acp/tests/approval.spec.ts deleted file mode 100644 index 65679cd905..0000000000 --- a/packages/ui/acp/tests/approval.spec.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { CallId } from '@deepseek-ai/dsh-llm' -import { type Agent } from '@deepseek-ai/dsh-agent' - -import ApprovalService, { type ApprovalRequest } from '@deepseek-ai/dsh-user-approval' -import { makeBridgeHarness, type BridgeHarness } from './harness.ts' -import { SessionId } from '@deepseek-ai/dsh-session' - -/** - * The bridge's `approval/request` answerer: an ask for an agent the bridge - * owns becomes a `session/request_permission` prompt attached to the tool - * call; foreign or call-less requests delegate down to the fail-closed - * default. Driven through `ctx.approval` — the same path dsh-tools' ask - * routing takes — against the harness's scriptable client. - */ -describe('acp bridge — approval answerer', () => { - let storageDir: string - let harness: BridgeHarness | undefined - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-approval-')) }) - afterEach(async () => { - await harness?.dispose() - harness = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - async function ownedAgentRequest( - h: BridgeHarness, overrides: Partial<ApprovalRequest> = {}, - ): Promise<{ agent: Agent; request: ApprovalRequest }> { - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = h.ctx.agents.get(SessionId(sessionId)) - if (agent === undefined) throw new Error('newSession created no agent') - // In production an ask always fires mid-turn (tool execution); open one so - // request()'s turn-enclosure precondition holds for the direct drive below. - agent.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) - return { agent, request: { agent, toolName: 'echo', callId: CallId('call-9'), ...overrides } } - } - - it('prompts the editor for an owned agent and maps allow-once → allowed-once', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.ctx.plugin(ApprovalService) - harness.onPermission = () => ({ outcome: { outcome: 'selected', optionId: 'allow-once' } }) - - const { request } = await ownedAgentRequest(harness) - await expect(harness.ctx.approval.request(request)).resolves.toBe('allowed-once') - - expect(harness.permissionRequests).toHaveLength(1) - const wire = harness.permissionRequests[0] - expect(wire?.toolCall).toEqual({ toolCallId: 'call-9' }) - expect(wire?.options.map(o => ({ optionId: o.optionId, kind: o.kind }))).toEqual([ - { optionId: 'allow-once', kind: 'allow_once' }, - { optionId: 'reject-once', kind: 'reject_once' }, - ]) - }) - - it('maps reject-once → rejected', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.ctx.plugin(ApprovalService) - harness.onPermission = () => ({ outcome: { outcome: 'selected', optionId: 'reject-once' } }) - - const { request } = await ownedAgentRequest(harness) - await expect(harness.ctx.approval.request(request)).resolves.toBe('rejected') - }) - - it('maps a client cancellation → cancelled', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.ctx.plugin(ApprovalService) - harness.onPermission = () => ({ outcome: { outcome: 'cancelled' } }) - - const { request } = await ownedAgentRequest(harness) - await expect(harness.ctx.approval.request(request)).resolves.toBe('cancelled') - }) - - it('treats an unknown optionId from a non-conforming client as a rejection, never a grant', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.ctx.plugin(ApprovalService) - harness.onPermission = () => ({ outcome: { outcome: 'selected', optionId: 'allow-always-i-insist' } }) - - const { request } = await ownedAgentRequest(harness) - await expect(harness.ctx.approval.request(request)).resolves.toBe('rejected') - }) - - it('delegates a foreign agent down to the fail-closed default', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.ctx.plugin(ApprovalService) - harness.onPermission = () => ({ outcome: { outcome: 'selected', optionId: 'allow-once' } }) - - const { agent } = await ownedAgentRequest(harness) - // Even an impostor that claims the bridge-owned session id must delegate: - // ownership requires the exact Agent object stored in the session record. - const foreign = { - session: { id: agent.session.id, events: [{ type: 'turn/start' }], append: () => ({}) }, - } as unknown as Agent - await expect(harness.ctx.approval.request({ agent: foreign, toolName: 'echo', callId: CallId('c') })) - .resolves.toBe('unavailable') - expect(harness.permissionRequests).toHaveLength(0) - }) - - it('delegates a call-less request — the protocol prompt must attach to a tool call', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.ctx.plugin(ApprovalService) - harness.onPermission = () => ({ outcome: { outcome: 'selected', optionId: 'allow-once' } }) - - const { agent } = await ownedAgentRequest(harness) - await expect(harness.ctx.approval.request({ agent, toolName: 'echo' })).resolves.toBe('unavailable') - expect(harness.permissionRequests).toHaveLength(0) - }) -}) diff --git a/packages/ui/acp/tests/bridge.spec.ts b/packages/ui/acp/tests/bridge.spec.ts deleted file mode 100644 index 6e24acce24..0000000000 --- a/packages/ui/acp/tests/bridge.spec.ts +++ /dev/null @@ -1,468 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { makeBridgeHarness, textResponse, toolCallResponse, type BridgeHarness } from './harness.ts' -import { SessionId } from '@deepseek-ai/dsh-session' -import { encodeSessionReferenceUri, formatSessionReferenceMention } from '@deepseek-ai/dsh-session-reference' - -/** - * End-to-end bridge specs over an in-memory transport: a real - * ClientSideConnection drives the bridge's AgentSideConnection, so every - * assertion exercises actual JSON-RPC framing and the harness event taxonomy. - */ -describe('acp bridge', () => { - let storageDir: string - let harness: BridgeHarness | undefined - - beforeEach(async () => { - storageDir = await mkdtemp(join(tmpdir(), 'acp-test-')) - }) - - afterEach(async () => { - // e2e/integration tests own their resources (docs/testing.md): dispose even on - // failure so a flaky run never leaks a context or persistence dir. - if (harness) await harness.dispose() - harness = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - it('initialize negotiates the protocol version and advertises capabilities', async () => { - harness = await makeBridgeHarness({ storageDir }) - const res = await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - expect(res.protocolVersion).toBe(PROTOCOL_VERSION) - expect(res.agentCapabilities?.loadSession).toBe(true) - expect(res.agentCapabilities?.promptCapabilities).toMatchObject({ image: false, audio: false }) - expect(res.agentInfo).toEqual({ name: 'deepseek-harness-acp', version: '0.0.1' }) - }) - - it('session/new creates a session and a full prompt turn streams text then settles end_turn', async () => { - harness = await makeBridgeHarness({ storageDir, script: [textResponse('hello there')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(sessionId).toBeTruthy() - - const res = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'hi' }] }) - expect(res.stopReason).toBe('end_turn') - - // The streamed text arrived as agent_message_chunk updates. - const text = harness.updates - .filter(u => u.sessionUpdate === 'agent_message_chunk') - .map(u => (u.content.type === 'text' ? u.content.text : '')) - .join('') - expect(text).toBe('hello there') - }) - - it('routes ask_user_question through ACP form elicitation and continues with the selected option', async () => { - harness = await makeBridgeHarness({ - storageDir, - withAskUser: true, - script: [ - toolCallResponse('ask-1', 'ask_user_question', { - questions: [{ - id: 'language', - header: 'Project config', - question: 'Which language should I use?', - options: [ - { label: 'TypeScript', description: 'Good for UI apps' }, - { label: 'Python', description: 'Good for scripts' }, - ], - }], - }), - textResponse('Python it is.'), - ], - }) - harness.onElicitation = () => ({ action: 'accept', content: { choice: 'Python' } }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - const result = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'ask me' }] }) - - expect(result.stopReason).toBe('end_turn') - expect(harness.elicitationRequests).toHaveLength(1) - expect(harness.elicitationRequests[0]).toMatchObject({ - sessionId, - mode: 'form', - message: 'Which language should I use?', - requestedSchema: { - title: 'Project config', - properties: { - choice: { - oneOf: [ - { const: 'TypeScript', title: 'TypeScript: Good for UI apps' }, - { const: 'Python', title: 'Python: Good for scripts' }, - ], - }, - custom: { type: 'string' }, - }, - required: [], - }, - }) - const toolResult = harness.ctx.agents.get(SessionId(sessionId))!.session.events.find(event => event.type === 'tool/result') - const toolResultBlock = toolResult?.type === 'tool/result' ? toolResult.data.content[0] : undefined - const toolResultText = toolResultBlock?.type === 'text' ? toolResultBlock.text : undefined - expect(toolResultText).toBe('{"answers":[{"id":"language","selected":["Python"]}]}') - }) - - it('routes optionless ask_user_question through an ACP free-form answer field', async () => { - harness = await makeBridgeHarness({ - storageDir, - withAskUser: true, - script: [ - toolCallResponse('ask-1', 'ask_user_question', { - questions: [{ id: 'name', question: 'What should I name it?' }], - }), - textResponse('Name recorded.'), - ], - }) - harness.onElicitation = () => ({ action: 'accept', content: { custom: 'apollo' } }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'ask me' }] }) - - expect(harness.elicitationRequests[0]).toMatchObject({ - requestedSchema: { - properties: { custom: { type: 'string', title: 'What should I name it?' } }, - required: ['custom'], - }, - }) - const toolResult = harness.ctx.agents.get(SessionId(sessionId))!.session.events.find(event => event.type === 'tool/result') - expect(JSON.stringify(toolResult)).toContain('apollo') - }) - - it('supports ACP custom answers alongside choices', async () => { - harness = await makeBridgeHarness({ storageDir, withAskUser: true }) - harness.onElicitation = () => ({ action: 'accept', content: { custom: 'Use Zig' } }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - - const result = await harness.ctx.userInteraction.ask({ - agent, - questions: [{ - id: 'language', - question: 'Which language?', - detail: 'Choose the implementation language for this project.', - options: [{ label: 'TypeScript' }], - }], - }) - - expect(result).toEqual({ answers: [{ id: 'language', selected: [], custom: 'Use Zig' }] }) - expect(harness.elicitationRequests[0]).toMatchObject({ - message: 'Which language?\n\nChoose the implementation language for this project.', - requestedSchema: { - properties: { - choice: { - title: 'Which language?', - description: 'Choose one option, or fill a custom answer below.', - oneOf: [{ const: 'TypeScript', title: 'TypeScript' }], - }, - custom: { type: 'string' }, - }, - required: [], - }, - }) - }) - - it('treats ACP custom answers as overriding selected choices', async () => { - harness = await makeBridgeHarness({ storageDir, withAskUser: true }) - harness.onElicitation = () => ({ action: 'accept', content: { choice: 'TypeScript', custom: 'Use Zig' } }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - - await expect(harness.ctx.userInteraction.ask({ - agent, - questions: [{ - id: 'language', - question: 'Which language?', - options: [{ label: 'TypeScript' }], - }], - })).resolves.toEqual({ answers: [{ id: 'language', selected: [], custom: 'Use Zig' }] }) - }) - - it('supports ACP multi-select answers', async () => { - harness = await makeBridgeHarness({ storageDir, withAskUser: true }) - harness.onElicitation = () => ({ action: 'accept', content: { choice: ['Tests', 'Docs'] } }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - - await expect(harness.ctx.userInteraction.ask({ - agent, - questions: [{ - id: 'targets', - question: 'Pick', - options: [{ label: 'Tests' }, { label: 'Docs' }], - multiSelect: true, - }], - })).resolves.toEqual({ answers: [{ id: 'targets', selected: ['Tests', 'Docs'] }] }) - }) - - it('reports ACP ask-user routing and answer failures as structured errors', async () => { - harness = await makeBridgeHarness({ storageDir, withAskUser: true }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - - await expect(harness.ctx.userInteraction.ask({ questions: [{ id: 'x', question: 'No agent?' }] })) - .rejects.toMatchObject({ name: 'UserInteractionError', code: 'NO_AGENT' }) - const impostor = { session: { id: agent.session.id } } as typeof agent - await expect(harness.ctx.userInteraction.ask({ agent: impostor, questions: [{ id: 'x', question: 'No session?' }] })) - .rejects.toMatchObject({ code: 'NO_SESSION' }) - - harness.onElicitation = () => ({ action: 'cancel' }) - await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Cancel?' }] })) - .rejects.toMatchObject({ code: 'ASK_CANCELLED' }) - - harness.onElicitation = () => ({ action: 'accept', content: {} }) - await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Empty?' }] })) - .rejects.toMatchObject({ code: 'NO_ANSWER' }) - - harness.onElicitation = () => { throw new Error('client boom') } - await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Client fails?' }], signal: new AbortController().signal })) - .rejects.toMatchObject({ code: 'ASK_FAILED' }) - }) - - it('aborts ACP ask-user requests before and while waiting for elicitation', async () => { - harness = await makeBridgeHarness({ storageDir, withAskUser: true }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - - const alreadyAborted = new AbortController() - alreadyAborted.abort() - await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Already?' }], signal: alreadyAborted.signal })) - .rejects.toMatchObject({ code: 'ASK_ABORTED' }) - - let abortedReads = 0 - const racingAbort = { - get aborted() { return abortedReads++ > 0 }, - addEventListener() {}, - removeEventListener() {}, - dispatchEvent() { return false }, - onabort: null, - reason: undefined, - throwIfAborted() {}, - } as AbortSignal - await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Raced?' }], signal: racingAbort })) - .rejects.toMatchObject({ code: 'ASK_ABORTED' }) - - let release: ((value: { action: 'accept'; content: { custom: string } }) => void) | undefined - harness.onElicitation = () => new Promise((resolve) => { release = resolve }) - const pendingAbort = new AbortController() - const ask = harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Pending?' }], signal: pendingAbort.signal }) - await new Promise(resolve => setImmediate(resolve)) - pendingAbort.abort() - - await expect(ask).rejects.toMatchObject({ code: 'ASK_ABORTED' }) - release?.({ action: 'accept', content: { custom: 'too late' } }) - }) - - it('allows multiple concurrent sessions, each with a distinct id', async () => { - harness = await makeBridgeHarness({ storageDir, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const b = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(a.sessionId).toBeTruthy() - expect(b.sessionId).toBeTruthy() - expect(a.sessionId).not.toBe(b.sessionId) - // Both agents are live and independently registered. - expect(harness.ctx.agents.get(SessionId(a.sessionId))).toBeDefined() - expect(harness.ctx.agents.get(SessionId(b.sessionId))).toBeDefined() - }) - - it('rejects a non-absolute cwd but accepts any absolute cwd (per-session workspace)', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - // Relative cwd is still rejected (it becomes the session header / bash workdir). - await expect(harness.client.newSession({ cwd: 'relative/path', mcpServers: [] })) - .rejects.toThrow(/absolute/) - // An absolute cwd that differs from the server launch dir is now ACCEPTED — - // the per-session cwd is honored (routed to the bash workdir), so the server - // no longer has to launch in the workspace. - const res = await harness.client.newSession({ cwd: '/tmp', mcpServers: [] }) - expect(res.sessionId).toBeTruthy() - // The session header records that cwd, so its bash tools run there. - expect(harness.ctx.agents.get(SessionId(res.sessionId))!.session.header.cwd).toBe('/tmp') - }) - - it('rejects non-empty additionalDirectories', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(harness.client.newSession({ cwd: process.cwd(), mcpServers: [], additionalDirectories: ['/x'] })) - .rejects.toThrow(/additionalDirectories/) - }) - - it('rejects an empty prompt without hanging', async () => { - harness = await makeBridgeHarness({ storageDir, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: ' ' }] })) - .rejects.toThrow(/empty prompt/) - }) - - it('rejects image content in a prompt (text-only capabilities)', async () => { - harness = await makeBridgeHarness({ storageDir, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await expect(harness.client.prompt({ - sessionId, - prompt: [{ type: 'image', mimeType: 'image/png', data: 'AA==' }], - })).rejects.toThrow(/text/) - }) - - it('accepts a resource_link prompt by rendering the link into the text sent to the agent', async () => { - harness = await makeBridgeHarness({ storageDir, script: [textResponse('ok')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const result = await harness.client.prompt({ - sessionId, - prompt: [ - { type: 'text', text: 'fix the bug in' }, - { type: 'resource_link', uri: 'file:///x.ts', name: 'x.ts' }, - ], - }) - expect(result.stopReason).toBe('end_turn') - const user = harness.ctx.agents.get(SessionId(sessionId))!.session.events.find(event => event.type === 'user/message') - expect(JSON.stringify(user)).toContain('resource_link') - }) - - it('rejects canonical session references when the optional capability is not mounted', async () => { - harness = await makeBridgeHarness({ storageDir, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await expect(harness.client.prompt({ - sessionId, - prompt: [{ type: 'resource_link', uri: encodeSessionReferenceUri(SessionId('source')), name: 'source' }], - })).rejects.toThrow(/session reference capability unavailable/) - expect(harness.ctx.agents.get(SessionId(sessionId))?.session.events).toHaveLength(0) - }) - - it('reports malformed inline session references at the ACP request boundary', async () => { - harness = await makeBridgeHarness({ storageDir, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await expect(harness.client.prompt({ - sessionId, - prompt: [{ type: 'text', text: 'use dsh-session:IiJ' }], - })).rejects.toThrow(/invalid session reference/) - expect(harness.ctx.agents.get(SessionId(sessionId))?.session.events).toHaveLength(0) - }) - - it('prepares ACP session resource links and inline mentions before one atomic send', async () => { - harness = await makeBridgeHarness({ storageDir, withSessionReferences: true, script: [textResponse('ok')] }) - const source = harness.ctx.sessions.create(SessionId('source'), { meta: { cwd: '/source' } }) - source.append('user/message', { - content: [{ type: 'text', text: 'source background' }], - source: { kind: 'user' }, - }, { surfaceOp: 'append' }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const mention = formatSessionReferenceMention({ sessionId: source.id, label: 'source-inline' }) - const result = await harness.client.prompt({ - sessionId, - prompt: [ - { type: 'text', text: `use ${mention} and ` }, - { type: 'resource_link', uri: encodeSessionReferenceUri(source.id), name: 'source-link' }, - ], - }) - expect(result.stopReason).toBe('end_turn') - - const target = harness.ctx.agents.get(SessionId(sessionId))!.session - const user = target.events.find(event => event.type === 'user/message') - expect(user?.type === 'user/message' && user.data.envelope).toMatchObject({ - displayContent: [{ type: 'text', text: 'use @source-inline and @source-link' }], - prefixContexts: [{ - source: { kind: 'plugin', plugin: 'session-reference' }, - meta: { - kind: 'session-reference', - references: [{ sessionId: 'source', label: 'source-inline' }], - }, - }], - }) - expect(target.events.some(event => event.type === 'user/message' && event.data.source.kind !== 'user')).toBe(false) - const request = JSON.stringify(harness.adapter.requests[0]?.messages) - expect(request).toContain('untrusted, read-only snapshot') - expect(request).toContain('source background') - expect(request.indexOf('source background')).toBeLessThan(request.indexOf('## My request:')) - expect(request.indexOf('## My request:')).toBeLessThan(request.indexOf('use @source-inline and @source-link')) - }) - - it('rejects a failed referenced-session read before starting a turn', async () => { - harness = await makeBridgeHarness({ storageDir, withSessionReferences: true, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await expect(harness.client.prompt({ - sessionId, - prompt: [{ type: 'resource_link', uri: encodeSessionReferenceUri(SessionId('missing')), name: 'missing' }], - })).rejects.toThrow(/preparation failed/) - expect(harness.ctx.agents.get(SessionId(sessionId))?.session.events).toHaveLength(0) - }) - - it('cancels reference preparation before a turn is created', async () => { - harness = await makeBridgeHarness({ storageDir, withSessionReferences: true, script: [] }) - const source = harness.ctx.sessions.create(SessionId('source')) - const snapshot = await harness.ctx.sessionQuery.readSurface(source.id) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - let releaseRead: (() => void) | undefined - const readSurface = vi.spyOn(harness.ctx.sessionQuery, 'readSurface').mockImplementationOnce(async () => { - await new Promise<void>((resolve) => { releaseRead = resolve }) - return snapshot - }) - const pending = harness.client.prompt({ - sessionId, - prompt: [{ type: 'resource_link', uri: encodeSessionReferenceUri(source.id), name: 'source' }], - }) - await vi.waitFor(() => { expect(releaseRead).toBeTypeOf('function') }) - await harness.client.cancel({ sessionId }) - await expect(pending).resolves.toEqual({ stopReason: 'cancelled' }) - expect(harness.ctx.agents.get(SessionId(sessionId))?.session.events).toHaveLength(0) - releaseRead?.() - await Promise.resolve() - readSurface.mockRestore() - }) - - it('rejects a prompt for an unknown session', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(harness.client.prompt({ sessionId: 'nope', prompt: [{ type: 'text', text: 'hi' }] })) - .rejects.toThrow(/unknown session/) - }) - - it('negotiates an unsupported protocol version down to the supported one', async () => { - harness = await makeBridgeHarness({ storageDir }) - const res = await harness.client.initialize({ protocolVersion: 999, clientCapabilities: {} }) - expect(res.protocolVersion).toBe(PROTOCOL_VERSION) - }) - - it('a cancel for an unknown/absent session is a silent no-op', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - // No session created yet — cancel must not throw. - await expect(harness.client.cancel({ sessionId: 'nope' })).resolves.toBeUndefined() - }) - - it('authenticate is a no-op (no auth methods advertised)', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(harness.client.authenticate({ methodId: 'whatever' })).resolves.toBeDefined() - }) - - it('renders the deployment persona into ACP-created agents\' requests', async () => { - harness = await makeBridgeHarness({ - storageDir, - script: [textResponse('ok')], - persona: 'be terse', - }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - // Create + prompt so the system-prompt plugin's persona section reaches - // the model request of an agent the BRIDGE created (session/new). - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'hi' }] }) - expect(harness.adapter.requests[0]?.system).toContain('be terse') - }) -}) diff --git a/packages/ui/acp/tests/codec.spec.ts b/packages/ui/acp/tests/codec.spec.ts deleted file mode 100644 index 9cd2ca33a1..0000000000 --- a/packages/ui/acp/tests/codec.spec.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' -import type { TurnEndReason } from '@deepseek-ai/dsh-session' -import { SessionId } from '@deepseek-ai/dsh-session' -import { encodeSessionReferenceUri, formatSessionReferenceMention } from '@deepseek-ai/dsh-session-reference' -import type { ContentBlock as AcpContentBlock } from '@agentclientprotocol/sdk' -import { - acpPromptToReferencedPrompt, - acpPromptToText, - harnessBlockToAcpContent, - promptHasUnsupportedContent, - turnEndToStopReason, -} from '../src/codec.ts' - -describe('turnEndToStopReason', () => { - // The SDK rejects an unknown stopReason, so this must be total over every - // TurnEndReason kind and always produce a legal wire value. - it('maps every known TurnEndReason kind to a legal StopReason', () => { - expect(turnEndToStopReason({ kind: 'completed' })).toBe('end_turn') - expect(turnEndToStopReason({ kind: 'max-tokens' })).toBe('max_tokens') - expect(turnEndToStopReason({ kind: 'aborted' })).toBe('cancelled') - expect(turnEndToStopReason({ kind: 'disposed' })).toBe('cancelled') - expect(turnEndToStopReason({ kind: 'rejected', reason: 'blocked by hook' })).toBe('cancelled') - expect(turnEndToStopReason({ kind: 'error', step: 1, message: 'boom' })).toBe('end_turn') - }) - - it('falls back to end_turn for an unknown (merge-extensible) future kind', () => { - // A plugin-added TurnEndReason variant the bridge does not yet know about - // must still produce a legal wire value, not throw into the SDK. - const future = { kind: 'refusal' } as unknown as TurnEndReason - expect(turnEndToStopReason(future)).toBe('end_turn') - }) -}) - -describe('harnessBlockToAcpContent', () => { - it('maps a text block to ACP text content', () => { - expect(harnessBlockToAcpContent({ type: 'text', text: 'hi' })).toEqual({ type: 'text', text: 'hi' }) - }) - - it('returns undefined for non-text blocks (reasoning / plugin-added)', () => { - expect(harnessBlockToAcpContent({ type: 'reasoning', text: 'think' })).toBeUndefined() - expect(harnessBlockToAcpContent({ type: 'chart', data: 'x' } as unknown as ContentBlock)).toBeUndefined() - }) -}) - -describe('acpPromptToText', () => { - it('concatenates text blocks and renders resource links explicitly', () => { - const prompt: AcpContentBlock[] = [ - { type: 'text', text: 'hello ' }, - { type: 'resource_link', uri: 'file:///x', name: 'x' }, - { type: 'text', text: 'world' }, - ] - expect(acpPromptToText(prompt)).toBe('hello \n[resource_link name="x" uri="file:///x"]\nworld') - }) - - it('returns empty string for a prompt with no text blocks', () => { - expect(acpPromptToText([{ type: 'image', mimeType: 'image/png', data: 'AA==' }])).toBe('') - }) -}) - -describe('acpPromptToReferencedPrompt', () => { - it('extracts resource links and inline mentions while preserving ordinary links', () => { - const sessionId = SessionId('source/会话') - const prompt: AcpContentBlock[] = [ - { type: 'text', text: `compare ${formatSessionReferenceMention({ sessionId, label: 'inline' })} with ` }, - { type: 'resource_link', uri: encodeSessionReferenceUri(sessionId), name: 'linked' }, - { type: 'resource_link', uri: 'file:///x', name: 'x' }, - ] - expect(acpPromptToReferencedPrompt(prompt)).toEqual({ - text: 'compare @inline with @linked\n[resource_link name="x" uri="file:///x"]\n', - references: [{ sessionId, label: 'inline' }, { sessionId, label: 'linked' }], - }) - }) - - it('rejects malformed session resource links', () => { - expect(() => acpPromptToReferencedPrompt([ - { type: 'resource_link', uri: 'dsh-session:%%%', name: 'bad' }, - ])).toThrow(/invalid session reference URI/) - }) - - it('uses the decoded id for an empty resource name and ignores unsupported direct inputs', () => { - const sessionId = SessionId('source') - expect(acpPromptToReferencedPrompt([ - { type: 'resource_link', uri: encodeSessionReferenceUri(sessionId), name: '' }, - { type: 'image', mimeType: 'image/png', data: 'AA==' }, - ])).toEqual({ text: '@source', references: [{ sessionId, label: 'source' }] }) - }) -}) - -describe('promptHasUnsupportedContent', () => { - it('detects image, audio, and embedded resource blocks', () => { - expect(promptHasUnsupportedContent([{ type: 'image', mimeType: 'image/png', data: 'AA==' }])).toBe(true) - expect(promptHasUnsupportedContent([{ type: 'audio', mimeType: 'audio/wav', data: 'AA==' }])).toBe(true) - expect(promptHasUnsupportedContent([{ type: 'resource', resource: { uri: 'file:///x', text: 'x' } }])).toBe(true) - }) - - it('passes baseline text and resource_link prompt blocks', () => { - expect(promptHasUnsupportedContent([{ type: 'text', text: 'hi' }])).toBe(false) - expect(promptHasUnsupportedContent([{ type: 'resource_link', uri: 'file:///x', name: 'x' }])).toBe(false) - }) -}) diff --git a/packages/ui/acp/tests/commands.spec.ts b/packages/ui/acp/tests/commands.spec.ts deleted file mode 100644 index 45926e2b57..0000000000 --- a/packages/ui/acp/tests/commands.spec.ts +++ /dev/null @@ -1,299 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { SessionId } from '@deepseek-ai/dsh-session' -import { encodeSessionReferenceUri } from '@deepseek-ai/dsh-session-reference' -import { makeBridgeHarness, textResponse, type BridgeHarness } from './harness.ts' - -function commandUpdates(harness: BridgeHarness, sessionId: string) { - return harness.sessionUpdates.filter(update => update.sessionId === sessionId - && update.update.sessionUpdate === 'available_commands_update') -} - -function messageText(harness: BridgeHarness, sessionId: string): string { - return harness.sessionUpdates - .filter(update => update.sessionId === sessionId && update.update.sessionUpdate === 'agent_message_chunk') - .map(({ update }) => update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text' - ? update.content.text : '') - .join('') -} - -describe('ACP plugin commands', () => { - let storageDir: string - let harness: BridgeHarness | undefined - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-command-')) }) - afterEach(async () => { - if (harness !== undefined) await harness.dispose() - harness = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - it('publishes a full command snapshot after session creation and refreshes it dynamically', async () => { - harness = await makeBridgeHarness({ storageDir }) - harness.ctx.commands.register({ - name: 'inspect', - description: 'Inspect the session', - input: { hint: '<target>' }, - handler: () => ({ kind: 'success' }), - }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - await vi.waitFor(() => { - expect(commandUpdates(harness!, sessionId).at(-1)?.update).toEqual({ - sessionUpdate: 'available_commands_update', - availableCommands: [{ - name: 'inspect', - description: 'Inspect the session', - input: { hint: '<target>' }, - }], - }) - }) - - const dispose = harness.ctx.commands.register({ - name: 'alpha', - description: 'Alpha command', - handler: () => ({ kind: 'success' }), - }) - await vi.waitFor(() => { - expect(commandUpdates(harness!, sessionId).at(-1)?.update).toMatchObject({ - availableCommands: [{ name: 'alpha' }, { name: 'inspect' }], - }) - }) - dispose() - await vi.waitFor(() => { - expect(commandUpdates(harness!, sessionId).at(-1)?.update).toMatchObject({ - availableCommands: [{ name: 'inspect' }], - }) - }) - }) - - it('re-advertises commands after loading a persisted session', async () => { - const live = await makeBridgeHarness({ storageDir, script: [textResponse('persisted')] }) - await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'persist this session' }] }) - await live.dispose() - - harness = await makeBridgeHarness({ storageDir }) - harness.ctx.commands.register({ - name: 'loaded', description: 'Loaded command', handler: () => ({ kind: 'success' }), - }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await harness.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - - expect(commandUpdates(harness, sessionId).at(-1)?.update).toMatchObject({ - availableCommands: [{ name: 'loaded', description: 'Loaded command' }], - }) - }) - - it('coalesces registry changes before a new session command snapshot is announced', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - harness.ctx.commands.register({ - name: 'raced', description: 'Registered after the response', handler: () => ({ kind: 'success' }), - }) - - await vi.waitFor(() => { - expect(commandUpdates(harness!, sessionId)).toHaveLength(1) - expect(commandUpdates(harness!, sessionId)[0]?.update).toMatchObject({ - availableCommands: [{ name: 'raced' }], - }) - }) - }) - - it('executes a known single-text command directly and never sends it to the model', async () => { - harness = await makeBridgeHarness({ storageDir }) - const seen = vi.fn(() => ({ kind: 'success' as const, text: 'DIRECT RESULT' })) - harness.ctx.commands.register({ name: 'direct', description: 'Run directly', handler: seen }) - harness.ctx.commands.register({ - name: 'silent', description: 'Return no text', handler: () => ({ kind: 'success' }), - }) - harness.ctx.commands.register({ - name: 'empty', description: 'Return empty text', handler: () => ({ kind: 'success', text: '' }), - }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - const response = await harness.client.prompt({ - sessionId, - prompt: [{ type: 'text', text: '/direct raw args ' }], - }) - - expect(response.stopReason).toBe('end_turn') - expect(seen).toHaveBeenCalledWith(expect.objectContaining({ rawInput: ' raw args ' })) - expect(messageText(harness, sessionId)).toContain('DIRECT RESULT') - const updatesAfterText = harness.sessionUpdates.length - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: '/silent' }] }) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: '/empty' }] }) - expect(harness.sessionUpdates).toHaveLength(updatesAfterText) - expect(harness.adapter.requests).toHaveLength(0) - expect(harness.ctx.agents.get(SessionId(sessionId))?.session.events).toHaveLength(0) - }) - - it('renders expected command errors and rejects unknown slash commands without model fallback', async () => { - harness = await makeBridgeHarness({ storageDir }) - harness.ctx.commands.register({ - name: 'denied', - description: 'Deny directly', - handler: () => ({ kind: 'error', text: 'not allowed now' }), - }) - harness.ctx.commands.register({ - name: 'throws', - description: 'Throw an ordinary error', - handler: () => { throw new Error('handler exploded') }, - }) - harness.ctx.commands.register({ - name: 'hostile', - description: 'Throw a hostile value', - handler: () => { - throw { toString(): string { throw new Error('coercion exploded') } } - }, - }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: '/denied' }] })) - .resolves.toEqual({ stopReason: 'end_turn' }) - await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: '/missing input' }] })) - .resolves.toEqual({ stopReason: 'end_turn' }) - await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: '/throws' }] })) - .resolves.toEqual({ stopReason: 'end_turn' }) - await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: '/hostile' }] })) - .resolves.toEqual({ stopReason: 'end_turn' }) - - expect(messageText(harness, sessionId)).toContain('Error: not allowed now') - expect(messageText(harness, sessionId)).toContain('Error: unknown command: /missing input') - expect(messageText(harness, sessionId)).toContain('Error: command failed: Error: handler exploded') - expect(messageText(harness, sessionId)).toContain('Error: command failed: <unrenderable thrown value>') - expect(harness.adapter.requests).toHaveLength(0) - }) - - it('flattens supported command prompt blocks without invoking the model', async () => { - harness = await makeBridgeHarness({ storageDir }) - const command = vi.fn(() => ({ kind: 'success' as const, text: 'combined' })) - harness.ctx.commands.register({ name: 'direct', description: 'Direct', handler: command }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - await expect(harness.client.prompt({ - sessionId, - prompt: [ - { type: 'text', text: '/direct' }, - { type: 'text', text: ' extra' }, - { type: 'resource_link', name: 'input', uri: 'file:///workspace/input.txt' }, - ], - })).resolves.toEqual({ stopReason: 'end_turn' }) - expect(command).toHaveBeenCalledWith(expect.objectContaining({ - rawInput: ' extra\n[resource_link name="input" uri="file:///workspace/input.txt"]\n', - })) - expect(messageText(harness, sessionId)).toContain('combined') - expect(harness.adapter.requests).toHaveLength(0) - }) - - it('keeps session-reference syntax opaque in direct command arguments', async () => { - harness = await makeBridgeHarness({ storageDir }) - const command = vi.fn(() => ({ kind: 'success' as const })) - harness.ctx.commands.register({ name: 'direct', description: 'Direct', handler: command }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const sourceUri = encodeSessionReferenceUri(SessionId('source')) - - await expect(harness.client.prompt({ - sessionId, - prompt: [ - { type: 'text', text: `/direct valid=${sourceUri} malformed=dsh-session:IiJ` }, - { type: 'resource_link', name: 'source', uri: sourceUri }, - ], - })).resolves.toEqual({ stopReason: 'end_turn' }) - expect(command).toHaveBeenCalledWith(expect.objectContaining({ - rawInput: ` valid=${sourceUri} malformed=dsh-session:IiJ\n[resource_link name="source" uri=${JSON.stringify(sourceUri)}]\n`, - })) - expect(harness.adapter.requests).toHaveLength(0) - expect(harness.ctx.agents.get(SessionId(sessionId))?.session.events).toHaveLength(0) - }) - - it('maps session cancellation to the in-flight command signal and isolates other sessions', async () => { - harness = await makeBridgeHarness({ storageDir }) - let started!: () => void - const ready = new Promise<void>((resolve) => { started = resolve }) - harness.ctx.commands.register({ - name: 'wait', - description: 'Wait for cancellation', - handler: ({ signal }) => { - started() - return new Promise((resolve) => { - signal.addEventListener('abort', () => { resolve({ kind: 'error', text: 'late abort result' }) }, { once: true }) - }) - }, - }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const b = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - const waiting = harness.client.prompt({ sessionId: a.sessionId, prompt: [{ type: 'text', text: '/wait' }] }) - await ready - await expect(harness.client.prompt({ sessionId: a.sessionId, prompt: [{ type: 'text', text: '/wait' }] })) - .rejects.toThrow(/already in flight/) - await harness.client.cancel({ sessionId: a.sessionId }) - - await expect(waiting).resolves.toEqual({ stopReason: 'cancelled' }) - await expect(harness.client.prompt({ sessionId: b.sessionId, prompt: [{ type: 'text', text: '/missing' }] })) - .resolves.toEqual({ stopReason: 'end_turn' }) - expect(messageText(harness, a.sessionId)).not.toContain('late abort result') - }) - - it('aborts an in-flight command when the ACP bridge is disposed', async () => { - harness = await makeBridgeHarness({ storageDir }) - let started!: () => void - const ready = new Promise<void>((resolve) => { started = resolve }) - let commandSignal: AbortSignal | undefined - harness.ctx.commands.register({ - name: 'wait-dispose', - description: 'Wait for bridge disposal', - handler: ({ signal }) => { - commandSignal = signal - started() - return new Promise<never>(() => {}) - }, - }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - const waiting = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: '/wait-dispose' }] }) - await ready - await harness.acpFiber.dispose() - - expect(commandSignal?.aborted).toBe(true) - await expect(waiting).resolves.toEqual({ stopReason: 'cancelled' }) - }) - - it('resolves scoped command catalogs and execution independently per session', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const b = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agentA = harness.ctx.agents.get(SessionId(a.sessionId)) - if (agentA === undefined) throw new Error('session A has no agent') - await agentA.ctx.inject(['commands'], (commandCtx) => { - commandCtx.commands.register({ - name: 'private', description: 'Only session A', - handler: () => ({ kind: 'success', text: 'A ONLY' }), - }) - }) - - await vi.waitFor(() => { - expect(commandUpdates(harness!, a.sessionId).at(-1)?.update).toMatchObject({ availableCommands: [{ name: 'private' }] }) - }) - expect(commandUpdates(harness, b.sessionId).at(-1)?.update).toMatchObject({ availableCommands: [] }) - await harness.client.prompt({ sessionId: a.sessionId, prompt: [{ type: 'text', text: '/private' }] }) - await harness.client.prompt({ sessionId: b.sessionId, prompt: [{ type: 'text', text: '/private' }] }) - expect(messageText(harness, a.sessionId)).toContain('A ONLY') - expect(messageText(harness, b.sessionId)).toContain('unknown command') - }) -}) diff --git a/packages/ui/acp/tests/config-options.spec.ts b/packages/ui/acp/tests/config-options.spec.ts deleted file mode 100644 index c6d385185c..0000000000 --- a/packages/ui/acp/tests/config-options.spec.ts +++ /dev/null @@ -1,420 +0,0 @@ -/** - * Exercises the bridge's per-session Permissions option: validation, idle - * turn anchoring, isolation, and persistence through `session/load`. - */ - -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import InvariantService from '@deepseek-ai/dsh-invariants' -import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' -import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant' -import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant' -import ApprovalService from '@deepseek-ai/dsh-user-approval' -import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' -import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' -import PermissionService from '@deepseek-ai/dsh-permission' -import { makeBridgeHarness, textResponse, type BridgeHarness } from './harness.ts' - -/** - * Advertises the real executor through the `sandboxMode` capability without - * loading a kernel sandbox, which these bridge tests do not exercise. - */ -class SandboxedLocalExecutor extends LocalBashExecutor { - override get sandboxMode(): SandboxMode { - return 'workspace-write' - } -} - -async function mountInvariants(ctx: BridgeHarness['ctx']): Promise<void> { - await ctx.plugin(InvariantService) - await ctx.plugin(SessionInvariant) - await ctx.plugin(AgentInvariant) - await ctx.plugin(AgentLoopInvariant) -} - -function permissionOption(currentValue: string): object { - return { - id: 'permission', - name: 'Permissions', - description: 'The session permission preset: each choice bundles a sandbox mode and an approval policy.', - category: 'mode', - type: 'select', - currentValue, - options: [ - { value: 'workspace-write', name: 'workspace-write', description: 'Write inside the workspace and permitted temporary directories; wider retries require approval.' }, - { value: 'danger-full-access', name: 'danger-full-access', description: 'Full file access without approval prompts.' }, - ], - } -} - -function modelValue(provider = 'mock', model = 'mock'): string { - return JSON.stringify([provider, model]) -} - -function modelOption(currentValue = modelValue()): object { - return { - id: 'model', - name: 'Model', - description: 'Sets this session\'s provider and model.', - category: 'model', - type: 'select', - currentValue, - options: [{ value: modelValue(), name: 'Mock' }], - } -} - -function optionsWithPermission(currentValue: string): object[] { - return [modelOption(), permissionOption(currentValue)] -} - -describe('acp bridge — session config options', () => { - let storageDir: string - let h: BridgeHarness | undefined - let loader: BridgeHarness | undefined - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-config-')) }) - afterEach(async () => { - if (h) await h.dispose() - if (loader) await loader.dispose() - h = loader = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - async function presetStack(options: { script?: NonNullable<Parameters<typeof makeBridgeHarness>[0]>['script'] } = {}): Promise<BridgeHarness> { - const harness = await makeBridgeHarness({ storageDir, ...options.script !== undefined ? { script: options.script } : {} }) - // Make an out-of-turn switch fail in this suite. - await mountInvariants(harness.ctx) - await harness.ctx.plugin(SandboxedLocalExecutor, { timeoutMs: 10_000 }) - await harness.ctx.plugin(ApprovalService) - await harness.ctx.plugin(PermissionService) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - return harness - } - - it('advertises the model selector without requiring the permission service', async () => { - h = await makeBridgeHarness({ storageDir }) - await h.ctx.plugin(SandboxedLocalExecutor, { timeoutMs: 10_000 }) - await h.ctx.plugin(ApprovalService) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const res = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(res.configOptions).toEqual([modelOption()]) - }) - - it('groups models by provider and switches routing plus prompt variables as one session target', async () => { - h = await makeBridgeHarness({ - storageDir, - script: [textResponse('ok')], - config: { provider: 'alpha', model: 'a1' }, - persona: 'Route {{provider}} / {{model}}', - catalog: { - providers: [{ id: 'alpha', name: 'Alpha' }, { id: 'beta', name: 'Beta' }], - models: [ - { provider: 'alpha', id: 'a1', name: 'Alpha One', description: 'Fast' }, - { provider: 'beta', id: 'b1', name: 'Beta One' }, - ], - }, - }) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const created = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(created.configOptions).toEqual([{ - id: 'model', - name: 'Model', - description: 'Sets this session\'s provider and model.', - category: 'model', - type: 'select', - currentValue: modelValue('alpha', 'a1'), - options: [ - { group: 'alpha', name: 'Alpha', options: [{ value: modelValue('alpha', 'a1'), name: 'Alpha One', description: 'Fast' }] }, - { group: 'beta', name: 'Beta', options: [{ value: modelValue('beta', 'b1'), name: 'Beta One' }] }, - ], - }]) - - const switched = await h.client.setSessionConfigOption({ - sessionId: created.sessionId, - configId: 'model', - value: modelValue('beta', 'b1'), - }) - expect(switched.configOptions?.[0]).toMatchObject({ currentValue: modelValue('beta', 'b1') }) - await h.client.prompt({ sessionId: created.sessionId, prompt: [{ type: 'text', text: 'use beta' }] }) - expect(h.adapter.requests[0]).toMatchObject({ - provider: 'beta', - model: 'b1', - }) - expect(h.adapter.requests[0]?.system).toContain('Route beta / b1') - expect(h.ctx.agents.list()[0]?.session.requestHeader()?.config).toMatchObject({ provider: 'beta', model: 'b1' }) - }) - - it('adds the configured private model to an advisory catalog and ignores empty non-current groups', async () => { - h = await makeBridgeHarness({ - storageDir, - config: { provider: 'alpha', model: 'private-model' }, - catalog: { - providers: [{ id: 'alpha', name: 'Alpha' }, { id: 'empty', name: 'Empty' }], - models: [{ provider: 'alpha', id: 'public-model', name: 'Public Model' }], - }, - }) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const res = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(res.configOptions?.[0]).toMatchObject({ - currentValue: modelValue('alpha', 'private-model'), - options: [ - { value: modelValue('alpha', 'public-model'), name: 'Public Model' }, - { value: modelValue('alpha', 'private-model'), name: 'private-model' }, - ], - }) - }) - - it('omits model selection without a complete or registered current target', async () => { - h = await makeBridgeHarness({ storageDir, config: { model: undefined } }) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const missing = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(missing.configOptions).toBeUndefined() - await h.dispose() - - h = await makeBridgeHarness({ storageDir, config: { provider: 'unregistered', model: 'm' } }) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const unknown = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(unknown.configOptions).toBeUndefined() - }) - - it('leaves model-less agents available to another agent/request supplier', async () => { - h = await makeBridgeHarness({ storageDir, config: { model: undefined }, script: [textResponse('ok')] }) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = h.ctx.agents.list()[0] - if (agent === undefined) throw new Error('expected an agent') - agent.ctx.on('agent/request', async (_agent, _turn, _step, callConfig, _signal, _next) => ({ - ...callConfig, - provider: 'mock', - model: 'mock', - })) - await h.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'supplied elsewhere' }] }) - expect(h.adapter.requests[0]).toMatchObject({ provider: 'mock', model: 'mock' }) - }) - - it('advertises the Permissions select with the default preset current', async () => { - h = await presetStack() - const res = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(res.configOptions).toEqual(optionsWithPermission('workspace-write')) - }) - - it('an idle switch is pending (overlaid, not yet logged), then anchors inside the next prompt\'s turn', async () => { - h = await presetStack({ script: [textResponse('ok')] }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - const after = await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' }) - expect(after.configOptions).toEqual(optionsWithPermission('danger-full-access')) - - const session = h.ctx.agents.list()[0]?.session - expect(session?.events.some(e => e.type === 'permission/preset' || e.type === 'sandbox/mode' || e.type === 'approval/policy')).toBe(false) - - await h.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'anchor' }] }) - const events = session?.events ?? [] - expect(events.filter(e => e.type === 'permission/preset').map(e => e.data)).toEqual([{ preset: 'danger-full-access' }]) - expect(events.filter(e => e.type === 'sandbox/mode').map(e => e.data)).toEqual([{ mode: 'danger-full-access' }]) - expect(events.filter(e => e.type === 'approval/policy').map(e => e.data)).toEqual([{ policy: 'never' }]) - const turnStart = events.findIndex(e => e.type === 'turn/start') - const anchored = events.findIndex(e => e.type === 'permission/preset') - expect(turnStart).toBeGreaterThanOrEqual(0) - expect(anchored).toBeGreaterThan(turnStart) - }) - - it('an idle flip-flop anchors as one switch (last write wins)', async () => { - h = await presetStack({ script: [textResponse('ok')] }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' }) - const again = await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' }) - expect(again.configOptions).toEqual(optionsWithPermission('danger-full-access')) - await h.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'anchor' }] }) - const events = h.ctx.agents.list()[0]?.session.events ?? [] - expect(events.filter(e => e.type === 'permission/preset')).toHaveLength(1) - // A closed turn does not make a later idle switch appendable. - await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'workspace-write' }) - expect(h.ctx.agents.list()[0]?.session.events.filter(e => e.type === 'permission/preset')).toHaveLength(1) - }) - - it('a net-zero idle flip-flop anchors nothing (switches are recorded, select clicks are not)', async () => { - h = await presetStack({ script: [textResponse('ok')] }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' }) - const back = await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'workspace-write' }) - expect(back.configOptions).toEqual(optionsWithPermission('workspace-write')) - await h.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'anchor' }] }) - const events = h.ctx.agents.list()[0]?.session.events ?? [] - expect(events.some(e => e.type === 'permission/preset' || e.type === 'sandbox/mode' || e.type === 'approval/policy')).toBe(false) - }) - - it('a no-op switch (the value already shown) records nothing and keeps a live pending', async () => { - h = await presetStack({ script: [textResponse('ok')] }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const echo = await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'workspace-write' }) - expect(echo.configOptions).toEqual(optionsWithPermission('workspace-write')) - await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' }) - const repeat = await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' }) - expect(repeat.configOptions).toEqual(optionsWithPermission('danger-full-access')) - await h.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'anchor' }] }) - const events = h.ctx.agents.list()[0]?.session.events ?? [] - expect(events.filter(e => e.type === 'permission/preset').map(e => e.data)).toEqual([{ preset: 'danger-full-access' }]) - }) - - it('a mid-turn switch anchors immediately (the open turn encloses it)', async () => { - h = await presetStack({ script: ['hang'] }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const hung = h.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - // Give the loop a tick to open the turn (the turns.spec hang idiom). - await new Promise(resolve => setTimeout(resolve, 30)) - await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' }) - const events = h.ctx.agents.list()[0]?.session.events ?? [] - const turnStart = events.findIndex(e => e.type === 'turn/start') - const anchored = events.findIndex(e => e.type === 'permission/preset') - expect(turnStart).toBeGreaterThanOrEqual(0) - expect(anchored).toBeGreaterThan(turnStart) - expect(events.some(e => e.type === 'sandbox/mode')).toBe(true) - expect(events.some(e => e.type === 'approval/policy')).toBe(true) - await h.client.cancel({ sessionId }) - await hung - }) - - it('rejects unknown ids, unadvertised ids, boolean values, and out-of-vocabulary values', async () => { - h = await makeBridgeHarness({ storageDir }) - await h.ctx.plugin(ApprovalService) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - - await expect(h.client.setSessionConfigOption({ sessionId, configId: 'reasoning-effort', value: 'max' })) - .rejects.toThrow(/unknown config option/) - // This composition never advertised `permission`. - await expect(h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' })) - .rejects.toThrow(/unknown permission value/) - await expect(h.client.setSessionConfigOption({ sessionId, configId: 'model', value: modelValue('mock', 'missing') })) - .rejects.toThrow(/unknown model value/) - await expect(h.client.setSessionConfigOption({ sessionId, configId: 'permission', type: 'boolean', value: true })) - .rejects.toThrow(/select; boolean values are not accepted/) - }) - - it('rejects an out-of-vocabulary preset on an advertising composition', async () => { - h = await presetStack() - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await expect(h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'plan' })) - .rejects.toThrow(/unknown permission value/) - }) - - it('a switch in one session never leaks into a concurrent one (state and pending both per-session)', async () => { - h = await presetStack() - const a = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const b = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await h.client.setSessionConfigOption({ sessionId: a.sessionId, configId: 'permission', value: 'danger-full-access' }) - const bAfter = await h.client.setSessionConfigOption({ sessionId: b.sessionId, configId: 'permission', value: 'workspace-write' }) - expect(bAfter.configOptions).toEqual(optionsWithPermission('workspace-write')) - const aAfter = await h.client.setSessionConfigOption({ sessionId: a.sessionId, configId: 'permission', value: 'danger-full-access' }) - expect(aAfter.configOptions).toEqual(optionsWithPermission('danger-full-access')) - }) - - it('keeps model targets isolated across concurrent sessions', async () => { - h = await makeBridgeHarness({ - storageDir, - script: [textResponse('a'), textResponse('b')], - config: { provider: 'mock', model: 'one' }, - catalog: { - providers: [{ id: 'mock', name: 'Mock' }], - models: [ - { provider: 'mock', id: 'one', name: 'One' }, - { provider: 'mock', id: 'two', name: 'Two' }, - ], - }, - }) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const b = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await h.client.setSessionConfigOption({ sessionId: a.sessionId, configId: 'model', value: modelValue('mock', 'two') }) - await h.client.prompt({ sessionId: a.sessionId, prompt: [{ type: 'text', text: 'a' }] }) - await h.client.prompt({ sessionId: b.sessionId, prompt: [{ type: 'text', text: 'b' }] }) - expect(h.adapter.requests.map(request => request.model)).toEqual(['two', 'one']) - }) - - it('a knob drifted outside the table derives a visible-but-untargetable custom current', async () => { - h = await presetStack() - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - // Simulate a plugin calling the public knob setter inside a valid turn. - const agent = h.ctx.agents.list()[0] - if (agent === undefined) throw new Error('expected an agent') - agent.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) - agent.session.append('sandbox/mode', { mode: 'read-only' }) - agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) - const echo = await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'custom' }) - const option = echo.configOptions?.find(entry => entry.id === 'permission') - expect(option).toMatchObject({ currentValue: 'custom' }) - if (option === undefined || !('options' in option)) throw new Error('expected a select option') - expect(option.options.map(o => 'value' in o ? o.value : o)).toEqual(['workspace-write', 'danger-full-access', 'custom']) - const away = await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' }) - const afterOption = away.configOptions?.find(entry => entry.id === 'permission') - expect(afterOption).toMatchObject({ currentValue: 'danger-full-access' }) - if (afterOption === undefined || !('options' in afterOption)) throw new Error('expected a select option') - expect(afterOption.options.map(o => 'value' in o ? o.value : o)).toEqual(['workspace-write', 'danger-full-access']) - await expect(h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'custom' })) - .rejects.toThrow(/unknown permission value/) - }) - - it('session/load reports a resumed session\'s preset from its own log', async () => { - h = await presetStack({ script: [textResponse('ok')] }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await h.client.setSessionConfigOption({ sessionId, configId: 'permission', value: 'danger-full-access' }) - // One turn checkpoints the log (the switch events flush with it). - await h.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'persist me' }] }) - await h.dispose() - h = undefined - - loader = await presetStack() - const res = await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - expect(res.configOptions).toEqual(optionsWithPermission('danger-full-access')) - }) - - it('session/load restores the last requested provider/model from the request header', async () => { - const catalog = { - providers: [{ id: 'mock', name: 'Mock' }], - models: [ - { provider: 'mock', id: 'one', name: 'One' }, - { provider: 'mock', id: 'two', name: 'Two' }, - ], - } - h = await makeBridgeHarness({ - storageDir, - script: [textResponse('ok')], - config: { provider: 'mock', model: 'one' }, - catalog, - }) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await h.client.setSessionConfigOption({ sessionId, configId: 'model', value: modelValue('mock', 'two') }) - await h.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'persist target' }] }) - await h.dispose() - h = undefined - - loader = await makeBridgeHarness({ storageDir, config: { provider: 'mock', model: 'one' }, catalog }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const loaded = await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - expect(loaded.configOptions?.find(option => option.id === 'model')).toMatchObject({ - currentValue: modelValue('mock', 'two'), - }) - }) - - it('session/load omits config options when the persisted session has no target or permission service', async () => { - h = await makeBridgeHarness({ storageDir, config: { model: undefined } }) - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = h.ctx.agents.list()[0] - if (agent === undefined) throw new Error('expected an agent') - agent.inject([{ type: 'text', text: 'checkpoint' }], { source: { kind: 'plugin', plugin: 'test' } }) - await agent.whenIdle() - await h.dispose() - h = undefined - - loader = await makeBridgeHarness({ storageDir, config: { model: undefined } }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const loaded = await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - expect(loaded.configOptions).toBeUndefined() - }) -}) diff --git a/packages/ui/acp/tests/dispose.spec.ts b/packages/ui/acp/tests/dispose.spec.ts deleted file mode 100644 index bcfb177b16..0000000000 --- a/packages/ui/acp/tests/dispose.spec.ts +++ /dev/null @@ -1,320 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { SessionId } from '@deepseek-ai/dsh-session' -import { makeBridgeHarness, textResponse } from './harness.ts' - -describe('acp bridge — disposal & HMR safety', () => { - let storageDir: string - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-dispose-')) }) - afterEach(async () => { await rm(storageDir, { recursive: true, force: true }) }) - - it('disposal reaches quiescence: a running turn is aborted and awaited before dispose returns', async () => { - const harness = await makeBridgeHarness({ storageDir, script: ['hang'] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - - // Start a prompt that hangs in the model stream. - const promptDone = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - await new Promise(r => setTimeout(r, 30)) - expect(agent.status).toBe('running') - - // Dispose the whole context. The bridge's teardown must abort the agent and - // AWAIT whenIdle() — so right after dispose resolves, the agent is settled - // (not still running). Proves disposal waited, not just requested. - await harness.ctx.fiber.dispose() - expect(agent.status).not.toBe('running') - - // The in-flight prompt settled (cancelled) rather than hanging forever. - const res = await promptDone - expect(res.stopReason).toBe('cancelled') - }) - - it('after an ACP-only HMR dispose, a late session/new creates no orphan agent (closed guard)', async () => { - // Dispose JUST the bridge's fiber (an HMR reload) while agents/agent-loop - // stay up and the transport is still live. A late session/new must hit the - // `closed` guard and reject — NOT create an agent the disposed bridge can no - // longer stream or settle. Verify the world: no agent appeared. - const harness = await makeBridgeHarness({ storageDir, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const before = harness.ctx.agents.list().length - await harness.acpFiber.dispose() // tear down ONLY the bridge - await expect(harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })) - .rejects.toThrow(/disposed/) - expect(harness.ctx.agents.list().length).toBe(before) - await harness.dispose() - }) - - it('an agent created through the bridge is unregistered when ONLY the bridge fiber is disposed', async () => { - // The factory (`ctx.agents.create`) is reached through the bridge's - // traceable service proxy, so `AgentLoop.start`'s `this.ctx.effect(...)` - // registration binds to the CALLER context — the bridge fiber — not the - // AgentLoop fiber. Disposing JUST the bridge fiber (an ACP-only HMR reload) - // must therefore reclaim the agent's registry entry, even though agents/ - // agent-loop stay up. This pins the fiber-ownership the bridge's teardown - // doc comment relies on; if a refactor rebinds the registration to the - // AgentLoop fiber, the agent would survive bridge dispose and this fails. - const harness = await makeBridgeHarness({ storageDir, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(harness.ctx.agents.get(SessionId(sessionId))).toBeDefined() - - await harness.acpFiber.dispose() // tear down ONLY the bridge - expect(harness.ctx.agents.get(SessionId(sessionId))).toBeUndefined() - await harness.dispose() - }) - - it('no agent is created by a session/new after the bridge has closed (closed guard)', async () => { - // After teardown (here a client disconnect sets `closed`), a late - // `session/new` must NOT create an orphan agent the bridge can no longer - // drive/settle. The transport is gone so the RPC rejects; assert the world: - // no new agent appeared in the registry. - const harness = await makeBridgeHarness({ storageDir, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const before = harness.ctx.agents.list().length - await harness.closeClientTransport() // teardown → closed = true - await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }).catch(() => {}) - await new Promise(r => setTimeout(r, 10)) - expect(harness.ctx.agents.list().length).toBe(before) - await harness.dispose() - }) - - it('a client disconnect mid-prompt disposes the session (no registered agent left)', async () => { - // The ACP transport closes (editor quits) while a turn runs. The bridge must - // settle the in-flight prompt cancelled and DISPOSE the agent (the session's - // per-agent AgentHandle teardown) rather than leaving an orphaned running — - // or even idled-but-still-registered — agent whose updates are swallowed. - const harness = await makeBridgeHarness({ storageDir, script: ['hang'] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - // Start a prompt that hangs in the model stream. The prompt RPC will never - // return (its transport is severed), so do not await it. - void harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }).catch(() => {}) - await new Promise(r => setTimeout(r, 30)) - expect(agent.status).toBe('running') - - // Sever the transport — the bridge's conn.closed teardown runs and drives the - // agent's AgentHandle dispose to quiescence on its OWN (before any dispose()). - await harness.closeClientTransport() - await agent.whenIdle() - // The agent's loop has stopped: status `disposed`. - expect(agent.status).toBe('disposed') - - // Await the bridge teardown to completion WITHOUT tearing down the root - // agents/sessions services (so we can still query them). acpFiber.dispose() - // invokes the SAME memoized quiesce() the disconnect started and awaits its - // promise — which resolves only after every rec.dispose() (loop exit + - // session removal) has finished, closing the whenIdle()/owned.dispose() - // microtask race. The AgentHandle dispose has run: the agent is unregistered - // and its session removed from the store, not merely idled (the old - // behavior). The services live on the root ctx, so they survive this. - await harness.acpFiber.dispose() - expect(harness.ctx.agents.get(SessionId(sessionId))).toBeUndefined() - expect(harness.ctx.sessions.get(SessionId(sessionId))).toBeUndefined() - await harness.dispose() - }) - - it('a client disconnect racing fiber dispose both reach quiescence (shared teardown)', async () => { - // conn.closed teardown and ctx.fiber.dispose() can fire near-simultaneously. - // They must share one teardown promise: dispose() must NOT return before the - // disconnect teardown's whenIdle() has settled (a `record === undefined`-only - // guard would let the second caller return early mid-teardown). - const harness = await makeBridgeHarness({ storageDir, script: ['hang'] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - void harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }).catch(() => {}) - await new Promise(r => setTimeout(r, 30)) - expect(agent.status).toBe('running') - - // Fire both teardown paths without awaiting the first, then await both. - const close = harness.closeClientTransport() - const dispose = harness.ctx.fiber.dispose() - await Promise.all([close, dispose]) - // After BOTH settle, the agent has fully drained (not still running). - expect(agent.status).not.toBe('running') - }) - - it('after dispose, session/update listeners are gone (no further updates emitted)', async () => { - const harness = await makeBridgeHarness({ storageDir, script: [] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const session = harness.ctx.agents.get(SessionId(sessionId))!.session - - await harness.ctx.fiber.dispose() - const before = harness.updates.length - // Append an event directly to the (now-detached) session: the bridge's - // session/event listener should have been disposed, so no update fires. - session.append('turn/start', { turn: 99, trigger: { kind: 'message', source: { kind: 'user' } } }) - await new Promise(r => setTimeout(r, 10)) - expect(harness.updates.length).toBe(before) - }) - - it('the final turn closing events are persisted across an AgentHandle dispose (durability)', async () => { - // The teardown-ORDER guarantee: a per-agent dispose must stop the loop, - // AWAIT its exit (so the loop's final `turn/end` + `session/flush` fire - // through the still-attached store observer → `session/event`), and only - // THEN remove its publication hooks and session entry. If the order were inverted - // (detach first), the closing events would never reach persistence. Drive a - // CLEAN turn to completion, dispose JUST the bridge, then re-load the - // persisted log from disk and assert the closing turn/end is on disk — the - // world, not the agent's self-report. - const harness = await makeBridgeHarness({ storageDir, script: [textResponse('done')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - const liveEvents = harness.ctx.agents.get(SessionId(sessionId))!.session.events.length - expect(liveEvents).toBeGreaterThan(0) - - // Tear down JUST the bridge (the AgentHandle dispose runs to quiescence). - await harness.acpFiber.dispose() - expect(harness.ctx.agents.get(SessionId(sessionId))).toBeUndefined() - - // Re-load the session from disk: every live event (incl. the closing - // turn/end) was flushed before the session was detached. - const reloaded = await harness.ctx.sessionPersistence.load(SessionId(sessionId)) - expect(reloaded.events.length).toBe(liveEvents) - const last = reloaded.events.at(-1)! - expect(last.type).toBe('turn/end') - await harness.dispose() - }) - - it('a turn aborted BY the dispose still flushes its closing turn/end to disk (durability, mid-turn)', async () => { - // The teardown-order contract only earns its keep when the closing events are - // produced BY the dispose itself. Here the model stream HANGS, so the turn is - // still open when teardown runs: the composite agent effect stops the loop, - // the loop unwinds and appends `turn/end {disposed}` + runs its final - // `session/flush` — all while the store-owned publication hooks are still attached (the session - // detach is the LAST disposer in the same effect's LIFO chain) — and only - // THEN is the session detached. If the order were inverted (or the session - // were a racing SIBLING effect), the abort-produced `turn/end` would never - // reach disk and a re-load would instead show crash-recovery's synthetic - // `interrupted` closer. Re-load from disk and assert the REAL `disposed` - // reason landed — proving the loop's own closing event was captured, not a - // recovered substitute. - const harness = await makeBridgeHarness({ storageDir, script: ['hang'] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - void harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }).catch(() => {}) - await new Promise(r => setTimeout(r, 30)) - expect(agent.status).toBe('running') - // The turn is OPEN in the log (turn/start appended, no turn/end yet). - const openTurnEnds = agent.session.events.filter(e => e.type === 'turn/end').length - - // Dispose JUST the bridge: a fiber unload that must STILL honor the ordered - // teardown (the composite effect runs its disposer chain as a unit). - await harness.acpFiber.dispose() - expect(harness.ctx.agents.get(SessionId(sessionId))).toBeUndefined() - - // The loop's own `turn/end {disposed}` is on disk (re-load: the world, not - // self-report) — NOT a crash-recovery `interrupted` substitute. - const reloaded = await harness.ctx.sessionPersistence.load(SessionId(sessionId)) - const persistedTurnEnds = reloaded.events.filter(e => e.type === 'turn/end') - expect(persistedTurnEnds.length).toBe(openTurnEnds + 1) - expect(persistedTurnEnds.at(-1)!.data.reason).toMatchObject({ kind: 'disposed' }) - await harness.dispose() - }) - - it('per-session AgentHandle dispose leaves sibling agents untouched', async () => { - // The factory returns a per-agent AgentHandle whose dispose() tears down - // EXACTLY that agent + its session — the registry's per-handle isolation - // contract. Create two agents - // directly through the registry factory (the same path the ACP bridge uses), - // dispose one handle, and assert the other survives, registered and - // queryable, with its session still in the store. - const harness = await makeBridgeHarness({ storageDir, script: [] }) - const handleA = await harness.ctx.agents.create({ - sessionId: SessionId('sib-a'), agentOptions: { provider: 'mock', model: 'mock' }, - }) - const handleB = await harness.ctx.agents.create({ - sessionId: SessionId('sib-b'), agentOptions: { provider: 'mock', model: 'mock' }, - }) - expect(harness.ctx.agents.get(SessionId('sib-a'))).toBe(handleA.agent) - expect(harness.ctx.agents.get(SessionId('sib-b'))).toBe(handleB.agent) - - await handleA.dispose() - // A is gone — unregistered AND its session removed from the store. - expect(harness.ctx.agents.get(SessionId('sib-a'))).toBeUndefined() - expect(harness.ctx.sessions.get(SessionId('sib-a'))).toBeUndefined() - expect(handleA.agent.status).toBe('disposed') - // B is wholly unaffected. - expect(harness.ctx.agents.get(SessionId('sib-b'))).toBe(handleB.agent) - expect(harness.ctx.sessions.get(SessionId('sib-b'))).toBeDefined() - expect(handleB.agent.status).not.toBe('disposed') - await harness.dispose() - }) - - it('a throwing agent/disposed listener does not prevent session removal (composite-effect containment)', async () => { - // The AgentHandle teardown folds session-detach, register, and loop-stop - // into ONE composite effect whose disposers run as a `.then()` chain. The - // register disposer emits `agent/disposed`; if a listener throws and the - // emit is UNCONTAINED, the rejected chain skips the LATER session-detach - // disposer — stranding the session in the store with its publication hooks attached (a - // leak AND a durability hole, since the new design relies on detach - // running). The emit must be contained. Register a throwing listener, drive - // a clean turn, dispose, and assert the session was STILL removed. - const harness = await makeBridgeHarness({ storageDir, script: [textResponse('ok')] }) - harness.ctx.on('agent/disposed', () => { throw new Error('boom disposed listener') }) - const handle = await harness.ctx.agents.create({ - sessionId: SessionId('guard-a'), agentOptions: { provider: 'mock', model: 'mock' }, - }) - handle.agent.followup([{ type: 'text', text: 'go' }]) - await handle.agent.whenIdle() - expect(harness.ctx.sessions.get(SessionId('guard-a'))).toBeDefined() - - // Dispose: the throwing listener must NOT break the chain before detach. - await handle.dispose() - expect(harness.ctx.agents.get(SessionId('guard-a'))).toBeUndefined() - expect(harness.ctx.sessions.get(SessionId('guard-a'))).toBeUndefined() // detach still ran - await harness.dispose() - }) - - it('concurrent AgentHandle dispose() calls all await the SAME teardown (memoized)', async () => { - // The handle's dispose() must memoize: the underlying cordis effect disposer - // is single-shot, so a second dispose() while the first is mid-teardown would - // otherwise resolve IMMEDIATELY (effect epoch already cleared) — before the - // first call's await agent.done + final flush finished. Every caller must - // observe the same quiescence boundary. - const harness = await makeBridgeHarness({ storageDir, script: ['hang'] }) - const handle = await harness.ctx.agents.create({ - sessionId: SessionId('conc-a'), agentOptions: { provider: 'mock', model: 'mock' }, - }) - // Drive a turn that hangs in the model stream, so the loop is mid-turn when - // disposed — its exit runs a final session/flush we can gate to hold the - // teardown observably in-flight. - handle.agent.followup([{ type: 'text', text: 'go' }]) - await new Promise(r => setTimeout(r, 30)) - expect(handle.agent.status).toBe('running') - let releaseFlush!: () => void - const flushGate = new Promise<void>((resolve) => { releaseFlush = resolve }) - harness.ctx.on('session/flush', () => flushGate) - - // First dispose enters teardown (aborts the hanging step) and blocks in the - // gated final flush. - const first = handle.dispose() - let firstSettled = false - void first.then(() => { firstSettled = true }) - await new Promise(r => setTimeout(r, 20)) - expect(firstSettled).toBe(false) - - // Second dispose MUST await the same in-flight teardown, not resolve early. - const second = handle.dispose() - let secondSettled = false - void second.then(() => { secondSettled = true }) - await new Promise(r => setTimeout(r, 20)) - expect(secondSettled).toBe(false) // memoized: still pending with the first - - // Release the flush; both resolve together and the session is gone. - releaseFlush() - await Promise.all([first, second]) - expect(harness.ctx.agents.get(SessionId('conc-a'))).toBeUndefined() - expect(harness.ctx.sessions.get(SessionId('conc-a'))).toBeUndefined() - await harness.dispose() - }) -}) diff --git a/packages/ui/acp/tests/edges.spec.ts b/packages/ui/acp/tests/edges.spec.ts deleted file mode 100644 index ac85fbd7e0..0000000000 --- a/packages/ui/acp/tests/edges.spec.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { SessionId } from '@deepseek-ai/dsh-session' -import { makeBridgeHarness, textResponse, type BridgeHarness } from './harness.ts' - -describe('acp bridge — demux & config edges', () => { - let storageDir: string - let harness: BridgeHarness | undefined - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-edge-')) }) - afterEach(async () => { - if (harness) await harness.dispose() - harness = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - it('ignores events from an agent the bridge does not own (strict id demux)', async () => { - // A second agent created directly on the registry (NOT via the bridge) runs - // a turn. Its session events must NOT produce ACP updates and - // must not settle anything — the bridge demuxes strictly by its own id. - harness = await makeBridgeHarness({ storageDir, script: [textResponse('foreign')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await vi.waitFor(() => { - expect(harness!.updates.some(update => update.sessionUpdate === 'available_commands_update')).toBe(true) - }) - const before = harness.updates.length - - const { agent: foreign } = await harness.ctx.agents.create({ sessionId: SessionId('foreign-session'), agentOptions: { provider: 'mock', model: 'mock' } }) - foreign.followup([{ type: 'text', text: 'hi' }]) - await foreign.whenIdle() - await new Promise(r => setTimeout(r, 10)) - - // No update was emitted for the foreign agent's stream. - expect(harness.updates.length).toBe(before) - }) - - it('survives a session/update that the client rejects (best-effort notify)', async () => { - harness = await makeBridgeHarness({ storageDir, script: [textResponse('ok')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - // Make the client reject every update — the bridge's notify() must swallow - // the rejection and the prompt must still settle normally. - harness.onSessionUpdateError = () => { throw new Error('client update rejected') } - const res = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - expect(res.stopReason).toBe('end_turn') - }) - - it('accepts session/new with additionalDirectories empty', async () => { - // Exercises the defined-but-empty additionalDirectories branch (length 0 → allowed). - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [], additionalDirectories: [] }) - expect(a.sessionId).toBeTruthy() - }) - - it('rejects non-empty mcpServers until MCP wiring is implemented', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(harness.client.newSession({ - cwd: process.cwd(), - mcpServers: [{ name: 'fs', command: 'npx', args: ['server'], env: [] }], - })).rejects.toThrow(/mcpServers/) - }) -}) diff --git a/packages/ui/acp/tests/harness.ts b/packages/ui/acp/tests/harness.ts deleted file mode 100644 index 155ccb5b34..0000000000 --- a/packages/ui/acp/tests/harness.ts +++ /dev/null @@ -1,343 +0,0 @@ -/** - * Shared non-spec fixture that mounts the full in-memory agent/persistence stack and connects the - * ACP bridge to a real SDK client over memory streams. Tests exercise the same protocol path as an - * editor without a subprocess or stdio. - */ - -import { Context } from 'cordis' -import { CallId, type GenerateOptions, type LlmModelInfo, type LlmProviderInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' -import { LlmAdapter } from '@deepseek-ai/dsh-llm' -import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' -import CommandService from '@deepseek-ai/dsh-commands' -import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' -import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' -import LocalFileSystem from '@deepseek-ai/dsh-fs-local' -import * as FsPolicy from '@deepseek-ai/dsh-fs-policy' -import * as ToolBash from '@deepseek-ai/dsh-tool-bash' -import * as ToolFs from '@deepseek-ai/dsh-tool-fs' -import * as ToolTodo from '@deepseek-ai/dsh-tool-todo' -import PlanModeService from '@deepseek-ai/dsh-plan-mode' -import { - ClientSideConnection, - ndJsonStream, - type Agent as AcpAgent, - type Client, - type CreateElicitationRequest, - type CreateElicitationResponse, - type RequestPermissionRequest, - type RequestPermissionResponse, - type SessionNotification, - type Stream, -} from '@agentclientprotocol/sdk' -import UserInteractionService from '@deepseek-ai/dsh-user-interaction' -import SessionQueryService from '@deepseek-ai/dsh-session-query' -import SessionReferenceService from '@deepseek-ai/dsh-session-reference' -import * as ToolAskUser from '@deepseek-ai/dsh-tool-ask-user' -import * as AcpPlugin from '../src/index.ts' -import { type AcpConfig } from '../src/index.ts' - -class TestSessionQueryService extends SessionQueryService { - override searchSessions( - ..._args: Parameters<SessionQueryService['searchSessions']> - ): ReturnType<SessionQueryService['searchSessions']> { - return Promise.resolve({ items: [] }) - } - - override searchEvents( - ...args: Parameters<SessionQueryService['searchEvents']> - ): ReturnType<SessionQueryService['searchEvents']> { - return this.readSurface(args[0].sessionId).then(surface => ({ - session: surface.session, - items: [], - })) - } -} - -/** A scripted mock adapter (mirrors the agent-loop test adapter). */ -class MockAdapter extends LlmAdapter { - requests: GenerateOptions[] = [] - constructor( - private script: (StreamChunk[] | 'hang')[], - private readonly providers: readonly LlmProviderInfo[], - private readonly models: readonly LlmModelInfo[], - ) { - super() - } - - override providerInfo(provider: string): LlmProviderInfo { - const info = this.providers.find(entry => entry.id === provider) - if (info === undefined) throw new Error(`MockAdapter: unknown provider ${provider}`) - return info - } - - override listModels(provider: string): Promise<readonly LlmModelInfo[]> { - return Promise.resolve(this.models.filter(model => model.provider === provider)) - } - - async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> { - this.requests.push(options) - const entry = this.script.shift() - if (!entry) throw new Error('MockAdapter: script exhausted') - if (entry === 'hang') { - yield { type: 'block-start', index: 0, blockType: 'text' } - yield { type: 'text-delta', index: 0, text: 'partial' } - await new Promise<void>((_resolve, reject) => { - if (options.signal?.aborted) { reject(new Error('aborted')); return } - options.signal?.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true }) - }) - return - } - for (const chunk of entry) { - if (options.signal?.aborted) throw new Error('aborted') - yield chunk - } - } -} - -/** Scripted text response ending in a clean `stop` finish. */ -export function textResponse(text: string): StreamChunk[] { - return [ - { type: 'block-start', index: 0, blockType: 'text' }, - ...Array.from(text, (char): StreamChunk => ({ type: 'text-delta', index: 0, text: char })), - { type: 'block-end', index: 0, block: { type: 'text', text } }, - { type: 'usage', usage: { inputTokens: 5, outputTokens: text.length } }, - { type: 'finish', reason: { kind: 'stop' } }, - ] -} - -/** Scripted response ending at the output-token ceiling (max-tokens finish). */ -export function maxTokensResponse(text: string): StreamChunk[] { - return [ - { type: 'block-start', index: 0, blockType: 'text' }, - ...Array.from(text, (char): StreamChunk => ({ type: 'text-delta', index: 0, text: char })), - { type: 'block-end', index: 0, block: { type: 'text', text } }, - { type: 'finish', reason: { kind: 'max-tokens' } }, - ] -} - -/** Scripted response that fails mid-turn with a finish-error chunk. */ -export function errorResponse(message: string): StreamChunk[] { - return [ - { type: 'block-start', index: 0, blockType: 'text' }, - { type: 'text-delta', index: 0, text: 'partial' }, - { type: 'finish', reason: { kind: 'error', failure: { message, code: 'PROVIDER_ERROR' } } }, - ] -} - -/** Scripted single tool call (no follow-up step scripted by default). */ -export function toolCallResponse(rawCallId: string, name: string, args: object): StreamChunk[] { - const argumentsJson = JSON.stringify(args) - const id = CallId(rawCallId) - return [ - { type: 'block-start', index: 0, blockType: 'tool-call' }, - { type: 'tool-call-delta', index: 0, id, name, argumentsDelta: argumentsJson }, - { type: 'block-end', index: 0, block: { type: 'tool-call', id, name, arguments: argumentsJson } }, - { type: 'finish', reason: { kind: 'tool-calls' } }, - ] -} - -/** A captured `session/update` notification (the update payload only). */ -export type CapturedUpdate = SessionNotification['update'] - -export interface BridgeHarness { - ctx: Context - client: ClientSideConnection - adapter: MockAdapter - /** Every `session/update` the bridge pushed, in order (payload only). */ - updates: CapturedUpdate[] - /** Same, but tagged with each update's `sessionId` (for multi-session demux assertions). */ - sessionUpdates: { sessionId: string; update: CapturedUpdate }[] - /** Permission requests the bridge issued (none until the gate lands). */ - permissionRequests: RequestPermissionRequest[] - /** Decide each permission request's outcome (default: cancelled). */ - onPermission: (req: RequestPermissionRequest) => RequestPermissionResponse - /** Elicitation requests the bridge issued for ask_user_question. */ - elicitationRequests: CreateElicitationRequest[] - /** Decide each elicitation response (default: cancel). */ - onElicitation: (req: CreateElicitationRequest) => CreateElicitationResponse | Promise<CreateElicitationResponse> - /** If set, the client's sessionUpdate throws this (tests notify error path). */ - onSessionUpdateError: (() => void) | undefined - /** - * Sever the client→agent transport (close the writable the agent reads), - * which ends the agent-side stream and resolves the bridge's `conn.closed` — - * simulating an editor disconnecting. Returns once the close is requested. - */ - closeClientTransport: () => Promise<void> - /** - * The child fiber the ACP bridge is mounted in. Disposing it tears down JUST - * the bridge (its `ctx.on` listeners + effect) while the rest of the harness - * stays up — an ACP-only HMR reload. - */ - acpFiber: Awaited<ReturnType<Context['plugin']>> - dispose: () => Promise<void> - storageDir: string -} - -/** Test-only overrides preserve explicit undefined to suppress harness defaults. */ -type AcpConfigOverrides = { [K in keyof AcpConfig]?: AcpConfig[K] | undefined } - -/** - * Build the bridge + a connected client over an in-memory transport pair. - * - * Two identity `TransformStream`s cross-wired (agent writes → client reads, - * client writes → agent reads) give a faithful bidirectional JSON-RPC channel. - * The bridge's `apply` receives the agent-side `Stream` via `config.stream`; - * the test holds the `ClientSideConnection`. - * - * Pass an explicit undefined route field to suppress its mock default. - */ -export async function makeBridgeHarness(options: { - script?: (StreamChunk[] | 'hang')[] - config?: AcpConfigOverrides - /** Provider-neutral directory exposed to ACP model-selection tests. */ - catalog?: { providers: LlmProviderInfo[]; models: LlmModelInfo[] } - /** Deployment persona for the tree (the system-prompt plugin's config). */ - persona?: string - storageDir: string - /** - * Plug the REAL `dsh-bash-local` executor + `dsh-tool-bash` tools (instead of - * a test's own inline tool). Lets a test drive the actual `bash` tool — its - * real `presentCall`/`presentResult` — through the bridge, so tool-call UI - * tests verify the SHIPPING tool, not a stand-in (docs/testing.md "prefer the real - * implementation over a mock in tests"). - */ - withBash?: boolean - /** Plug the REAL `ask_user_question` tool and ACP user-interaction provider. */ - withAskUser?: boolean - /** - * Plug the REAL `dsh-tool-todo` tool so a test can drive `todo_write` through - * the bridge and assert the resulting `plan` sessionUpdate — the shipping - * tool + the bridge's own todo/write→plan mapping, not a stand-in. - */ - withTodo?: boolean - /** Mount exact session reads and cross-session snapshot preparation before ACP. */ - withSessionReferences?: boolean - /** Plug the REAL `dsh-plan-mode` plugin so a test can drive the session-mode picker. */ - withModes?: boolean - /** - * Plug the REAL filesystem stack (`dsh-fs-local` + `dsh-fs-policy` + - * `dsh-tool-fs`) so a test can drive `read`/`write`/`edit` through the bridge - * and assert their tool-owned presentation (title/kind/`locations`) on the - * wire — the shipping tools, not a stand-in. `fsCwd` sets the local backend's - * base directory (default: `storageDir`). - */ - withFs?: boolean - fsCwd?: string -} = { storageDir: '' }): Promise<BridgeHarness> { - const catalog = options.catalog ?? { - providers: [{ id: 'mock', name: 'Mock' }], - models: [{ provider: 'mock', id: 'mock', name: 'Mock' }], - } - const adapter = new MockAdapter(options.script ?? [], catalog.providers, catalog.models) - - const ctx = new Context() - await mountAgentLoopTestDependencies(ctx, { - systemPrompt: { persona: options.persona ?? '' }, - }) - await ctx.plugin(CommandService) - await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionPersistenceJsonl, { root: options.storageDir }) - await ctx.plugin(TestSessionQueryService) - if (options.withSessionReferences) { - await ctx.plugin(SessionReferenceService) - } - await ctx.plugin(UserInteractionService) - if (options.withAskUser) { - await ctx.plugin(ToolAskUser) - } - if (options.withBash) { - await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) - await ctx.plugin(ToolBash) - } - if (options.withTodo) { - await ctx.plugin(ToolTodo) - } - if (options.withModes) { - await ctx.plugin(PlanModeService, { section: 'Test plan mode instructions.' }) - } - if (options.withFs) { - await ctx.plugin(LocalFileSystem, { cwd: options.fsCwd ?? options.storageDir }) - await ctx.plugin(FsPolicy) - await ctx.plugin(ToolFs) - } - ctx.llm.registerAdapter(catalog.providers.map(provider => provider.id), adapter) - - // Two identity byte pipes cross-wired into the two ndJsonStreams: bytes the agent writes flow - // to the client's reader and vice versa. (ndJsonStream takes (output, input): the agent - // writes to a2c and reads from c2a; the client writes to c2a and reads from a2c.) Holding the c2a - // writer lets tests EOF the agent reader and simulate editor disconnect. - const a2c = new TransformStream<Uint8Array, Uint8Array>() - const c2a = new TransformStream<Uint8Array, Uint8Array>() - const c2aWriter = c2a.writable.getWriter() - // A WritableStream the client writes into; each chunk is forwarded to the - // held c2a writer. `closeClientTransport` closes that writer directly. - const clientOutput = new WritableStream<Uint8Array>({ - write: chunk => c2aWriter.write(chunk), - }) - - const agentStream: Stream = ndJsonStream(a2c.writable, c2a.readable) - const clientStream: Stream = ndJsonStream(clientOutput, a2c.readable) - - const updates: CapturedUpdate[] = [] - const sessionUpdates: { sessionId: string; update: CapturedUpdate }[] = [] - const permissionRequests: RequestPermissionRequest[] = [] - const elicitationRequests: CreateElicitationRequest[] = [] - const harness: BridgeHarness = { - ctx, - adapter, - updates, - sessionUpdates, - permissionRequests, - onPermission: () => ({ outcome: { outcome: 'cancelled' } }), - elicitationRequests, - onElicitation: () => ({ action: 'cancel' }), - onSessionUpdateError: undefined, - client: undefined as unknown as ClientSideConnection, - acpFiber: undefined as unknown as BridgeHarness['acpFiber'], - // Close the writable the CLIENT writes to (c2a) — its readable, which the agent's - // ndJsonStream consumes, then EOFs cleanly, so the bridge's `conn.closed` resolves and it - // sees the client disconnect. - closeClientTransport: async () => { await c2aWriter.close() }, - dispose: async () => { await ctx.fiber.dispose() }, - storageDir: options.storageDir, - } - - const makeClient = (_agent: AcpAgent): Client => ({ - sessionUpdate(params: SessionNotification): Promise<void> { - updates.push(params.update) - sessionUpdates.push({ sessionId: params.sessionId, update: params.update }) - // Let a test force the bridge's notify() error path. - if (harness.onSessionUpdateError) return Promise.reject(new Error('client update rejected')) - return Promise.resolve() - }, - requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse> { - permissionRequests.push(params) - return Promise.resolve(harness.onPermission(params)) - }, - unstable_createElicitation(params: CreateElicitationRequest): Promise<CreateElicitationResponse> { - elicitationRequests.push(params) - return Promise.resolve(harness.onElicitation(params)) - }, - }) - - // Default route fields only when the caller omitted them; explicit undefined values must survive. - const cfg = { stream: agentStream, ...options.config } as AcpConfig - if (!(options.config && 'provider' in options.config)) cfg.provider = 'mock' - if (!(options.config && 'model' in options.config)) cfg.model = 'mock' - // Mount the bridge the way production does: as a cordis plugin (via `ctx.plugin` with the - // real `inject`), not `AcpPlugin.apply(ctx, cfg)` on the ungated root. Later JSON-RPC callbacks run - // outside apply's injection scope, matching production and exposing missing-inject failures. - harness.acpFiber = await ctx.plugin({ - name: 'acp-test', - // Use the bridge's real exported `inject` so this never drifts from the plugin's actual - // dependency list (adding a service to the bridge must not require editing the harness — a - // hardcoded list silently broke when `tools` was added). The returned fiber permits ACP-only - // disposal while root services remain live for HMR assertions. - inject: [...AcpPlugin.inject], - apply: (inner: Context) => { AcpPlugin.apply(inner, cfg) }, - }) - harness.client = new ClientSideConnection(makeClient, clientStream) - - return harness -} diff --git a/packages/ui/acp/tests/load.spec.ts b/packages/ui/acp/tests/load.spec.ts deleted file mode 100644 index e8617a2b83..0000000000 --- a/packages/ui/acp/tests/load.spec.ts +++ /dev/null @@ -1,337 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' -import type {} from '@deepseek-ai/dsh-session-title' -import { makeBridgeHarness, textResponse, toolCallResponse, type BridgeHarness, type CapturedUpdate } from './harness.ts' - -/** Concatenate the text of all agent_message_chunk updates. */ -function messageText(updates: CapturedUpdate[]): string { - return updates - .filter(u => u.sessionUpdate === 'agent_message_chunk') - .map(u => (u.content.type === 'text' ? u.content.text : '')) - .join('') -} - -describe('acp bridge — session/load replay', () => { - let storageDir: string - let live: BridgeHarness | undefined - let loader: BridgeHarness | undefined - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-load-')) }) - afterEach(async () => { - if (live) await live.dispose() - if (loader) await loader.dispose() - live = loader = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - it('replays a persisted turn from the event log as session/update on load', async () => { - // 1. Create a session and run one turn — persistence writes the event log. - live = await makeBridgeHarness({ storageDir, script: [textResponse('remembered answer')] }) - await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'remember this' }] }) - // Dispose to flush + release; the on-disk log persists. - await live.dispose() - live = undefined - - // 2. A fresh bridge loads the same session id and must replay the turn. - loader = await makeBridgeHarness({ storageDir, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const res = await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - expect(res).toBeDefined() - - // The replayed updates reconstruct the assistant text from the event log - // (assistant/chunk → agent_message_chunk), NOT from deriveMessages. - expect(messageText(loader.updates)).toBe('remembered answer') - - // And the USER side of the turn replays too (user/message → - // user_message_chunk), so the editor transcript shows both sides. - const userText = loader.updates - .filter(u => u.sessionUpdate === 'user_message_chunk') - .map(u => (u.content.type === 'text' ? u.content.text : '')) - .join('') - expect(userText).toBe('remember this') - }) - - it('streams and replays the same persisted session_info_update for a title event', async () => { - live = await makeBridgeHarness({ storageDir, script: [] }) - await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - const session = live.ctx.agents.get(SessionId(sessionId))!.session - const event = await live.ctx.sessions.appendOutOfBand(session, 'session/title', { - title: 'Durable ACP title', - messageSeqs: [1], - source: { kind: 'fallback' }, - }, { kind: 'session-title' }) - const expected = { - sessionUpdate: 'session_info_update' as const, - title: 'Durable ACP title', - updatedAt: new Date(event.time).toISOString(), - } - expect(live.updates).toContainEqual(expected) - await live.dispose() - live = undefined - - loader = await makeBridgeHarness({ storageDir, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - expect(loader.updates).toContainEqual(expected) - }) - - it('replays a persisted tool call with the TOOL-OWNED presentation (title/rawInput/console output)', async () => { - // Persist a real bash call, then replay it through a fresh bridge. A throwaway presenter pairs - // call and result in log order so replay uses the shipping tool's same cards as live streaming. - live = await makeBridgeHarness({ - storageDir, - withBash: true, - script: [toolCallResponse('c1', 'bash', { command: 'echo hello', description: 'Print a greeting' }), textResponse('done')], - }) - await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'greet' }] }) - await live.dispose() - live = undefined - - // A fresh bridge — also with the real bash tool, since the presentation is - // resolved from the live registry at replay time — loads the session. - loader = await makeBridgeHarness({ storageDir, withBash: true, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - - const call = loader.updates.find(u => u.sessionUpdate === 'tool_call') - expect(call).toMatchObject({ toolCallId: 'c1', title: 'echo hello', kind: 'execute', rawInput: 'echo hello' }) - if (call?.sessionUpdate !== 'tool_call') throw new Error('expected a tool_call') - // Capability OFF on this loader: the description renders as a content block, no terminal block. - expect(call.content).toEqual([{ type: 'content', content: { type: 'text', text: 'Print a greeting' } }]) - const update = loader.updates.find(u => u.sessionUpdate === 'tool_call_update') - expect(update?.sessionUpdate).toBe('tool_call_update') - if (update?.sessionUpdate !== 'tool_call_update') throw new Error('expected a tool_call_update') - expect(update).toMatchObject({ toolCallId: 'c1', status: 'completed' }) - const content = update.content as { content: { text: string } }[] - expect(content[0]?.content.text).toBe('```console\nhello\n```') - }) - - it('replays a persisted todo/write as a plan sessionUpdate on load', async () => { - // A persisted `todo/write` must replay as an ACP plan update so a reopened editor sees the - // current plan, not just the tool transcript. - live = await makeBridgeHarness({ - storageDir, - withTodo: true, - script: [ - toolCallResponse('c1', 'todo_write', { - todos: [ - { content: 'first step', status: 'in_progress' }, - { content: 'second step', status: 'pending' }, - ], - }), - textResponse('planned'), - ], - }) - await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'plan it' }] }) - await live.dispose() - live = undefined - - loader = await makeBridgeHarness({ storageDir, withTodo: true, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - - const plan = loader.updates.find(u => u.sessionUpdate === 'plan') - expect(plan).toEqual({ - sessionUpdate: 'plan', - entries: [ - { content: 'first step', priority: 'medium', status: 'in_progress' }, - { content: 'second step', priority: 'medium', status: 'pending' }, - ], - }) - }) - - it('replays a persisted bash call as a TERMINAL card when the loader advertises the capability', async () => { - // The presentation is resolved at replay time, so a loader that advertised - // _meta.terminal_output must reconstruct the terminal card (content + _meta) - // from the persisted log — identical to how it would have streamed live. - live = await makeBridgeHarness({ - storageDir, - withBash: true, - script: [toolCallResponse('c1', 'bash', { command: 'echo hi', description: 'Greet' }), textResponse('done')], - }) - await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'greet' }] }) - await live.dispose() - live = undefined - - loader = await makeBridgeHarness({ storageDir, withBash: true, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: { _meta: { terminal_output: true } } }) - await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - - const call = loader.updates.find(u => u.sessionUpdate === 'tool_call') - if (call?.sessionUpdate !== 'tool_call') throw new Error('expected a tool_call') - // Replay reconstructs the terminal card: description block, then terminal block. - expect(call.content).toEqual([ - { type: 'content', content: { type: 'text', text: 'Greet' } }, - { type: 'terminal', terminalId: 'c1' }, - ]) - expect((call._meta as { terminal_info?: unknown }).terminal_info).toEqual({ terminal_id: 'c1', cwd: process.cwd() }) - const update = loader.updates.find(u => u.sessionUpdate === 'tool_call_update') - if (update?.sessionUpdate !== 'tool_call_update') throw new Error('expected a tool_call_update') - // Terminal mode: content omitted, output + exit on _meta — matching live. - expect(update.content).toBeUndefined() - const meta = update._meta as { terminal_output?: { data: string }; terminal_exit?: { exit_code?: number } } - expect(meta.terminal_output?.data).toBe('hi\n') - expect(meta.terminal_exit?.exit_code).toBe(0) - }) - - it('keeps one terminal completion live and on replay when a pruning replacement is logged', async () => { - live = await makeBridgeHarness({ - storageDir, - withBash: true, - script: [toolCallResponse('c1', 'bash', { command: 'echo full', description: 'Print full output' }), textResponse('done')], - }) - await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: { _meta: { terminal_output: true } } }) - const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'run it' }] }) - - const session = live.ctx.agents.get(SessionId(sessionId))!.session - const original = session.events.find(event => event.type === 'tool/result') - if (original?.type !== 'tool/result') throw new Error('expected original tool/result') - const liveCompletions = () => live!.updates.filter(update => - update.sessionUpdate === 'tool_call_update' && update.toolCallId === 'c1') - expect(liveCompletions()).toHaveLength(1) - expect((liveCompletions()[0] as { _meta?: { terminal_output?: { data: string } } })._meta?.terminal_output?.data) - .toBe('full\n') - - session.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } }) - session.append('tool/result', { - ...original.data, - content: [{ type: 'text', text: '[... tool result middle pruned ...]' }], - }, { - surfaceOp: { op: 'replace', start: original.seq, end: original.seq }, - sourceEventSeqs: [original.seq], - }) - session.append('turn/end', { turn: 2, reason: { kind: 'completed' } }) - - // The replacement is durable but is not another live completion. - expect(session.events.filter(event => event.type === 'tool/result')).toHaveLength(2) - expect(JSON.stringify(session.deriveMessages())).toContain('tool result middle pruned') - expect(liveCompletions()).toHaveLength(1) - await live.dispose() - live = undefined - - loader = await makeBridgeHarness({ storageDir, withBash: true, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: { _meta: { terminal_output: true } } }) - await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - - const replayed = loader.updates.filter(update => - update.sessionUpdate === 'tool_call_update' && update.toolCallId === 'c1') - expect(replayed).toHaveLength(1) - expect((replayed[0] as { _meta?: { terminal_output?: { data: string } } })._meta?.terminal_output?.data) - .toBe('full\n') - }) - - it('a load whose resume finishes after a client disconnect leaks no live session', async () => { - // Stall persistence so transport closes while resume is pending. Whether the SDK rejects first - // or the bridge's post-await guard fires, no agent may survive for the dead connection. - live = await makeBridgeHarness({ storageDir, script: [textResponse('x')] }) - await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'hi' }] }) - await live.dispose() - live = undefined - - loader = await makeBridgeHarness({ storageDir, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const realLoad = loader.ctx.sessionPersistence.load.bind(loader.ctx.sessionPersistence) - let release!: () => void - const gate = new Promise<void>((r) => { release = r }) - loader.ctx.sessionPersistence.load = async (id) => { await gate; return realLoad(id) } - - const loadResult = loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - .then(() => 'resolved' as const, () => 'rejected' as const) - await loader.closeClientTransport() // teardown sets `closed` while load is gated - release() // resume() finishes AFTER teardown - expect(await loadResult).toBe('rejected') - // No live agent was installed for the closed connection. - expect(loader.ctx.agents.get(SessionId(sessionId))).toBeUndefined() - }) - - it('rejects load when the requested cwd does not match the persisted session cwd', async () => { - // Seed a session on disk whose header.cwd is a DIFFERENT absolute path than the server's - // launch dir. Resume must retain the header cwd and route bash there rather than reject the - // mismatch or substitute the server cwd. - loader = await makeBridgeHarness({ storageDir, script: [] }) - const otherCwd = '/some/other/workspace' - await loader.ctx.sessionPersistence.create({ - version: SESSION_FORMAT_VERSION, id: SessionId('elsewhere'), createdAt: 1, cwd: otherCwd, - }) - await loader.ctx.sessionPersistence.append(SessionId('elsewhere'), [ - { type: 'turn/start', seq: 0, time: 0, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }, - { type: 'turn/end', seq: 1, time: 0, data: { turn: 1, reason: { kind: 'completed' } } }, - ]) - - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(loader.client.loadSession({ sessionId: 'elsewhere', cwd: process.cwd(), mcpServers: [] })) - .rejects.toThrow(/cwd mismatch/) - expect(loader.ctx.agents.get(SessionId('elsewhere'))).toBeUndefined() - - const res = await loader.client.loadSession({ sessionId: 'elsewhere', cwd: `${otherCwd}/.`, mcpServers: [] }) - expect(res).toBeDefined() - expect(loader.ctx.agents.get(SessionId('elsewhere'))!.session.header.cwd).toBe(otherCwd) - }) - - it('rejects load for a non-absolute cwd (still required to be absolute)', async () => { - loader = await makeBridgeHarness({ storageDir, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(loader.client.loadSession({ sessionId: 's', cwd: 'rel', mcpServers: [] })) - .rejects.toThrow(/absolute/) - }) - - it('lets persistence reject a load for an unknown id after metadata lookup misses', async () => { - loader = await makeBridgeHarness({ storageDir, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(loader.client.loadSession({ sessionId: 'missing', cwd: process.cwd(), mcpServers: [] })) - .rejects.toThrow(/Internal error/) - }) - - it('rejects loading a persisted session that has NO cwd (would silently run in the launch dir)', async () => { - // A legacy/external log without `header.cwd` must be rejected; the request cwd does not override - // it, and accepting would let bash silently fall back to the server launch directory. - loader = await makeBridgeHarness({ storageDir, script: [] }) - await loader.ctx.sessionPersistence.create({ - version: SESSION_FORMAT_VERSION, id: SessionId('legacy'), createdAt: 1, // no cwd - }) - await loader.ctx.sessionPersistence.append(SessionId('legacy'), [ - { type: 'turn/start', seq: 0, time: 0, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }, - { type: 'turn/end', seq: 1, time: 0, data: { turn: 1, reason: { kind: 'completed' } } }, - ]) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(loader.client.loadSession({ sessionId: 'legacy', cwd: process.cwd(), mcpServers: [] })) - .rejects.toThrow(/no absolute persisted cwd/) - // Rejected BEFORE resume (metadata-only check) — no agent was registered, so - // the id is not wedged: a later attempt hits the same clean rejection, not a - // duplicate-registration error. - expect(loader.ctx.agents.get(SessionId('legacy'))).toBeUndefined() - await expect(loader.client.loadSession({ sessionId: 'legacy', cwd: process.cwd(), mcpServers: [] })) - .rejects.toThrow(/no absolute persisted cwd/) - }) - - it('allows loading alongside an existing session but rejects re-loading the SAME id', async () => { - // Multi-session: a load can coexist with a live session, but loading an id - // that is already live is rejected (it is already loaded). - live = await makeBridgeHarness({ storageDir, script: [textResponse('one')] }) - await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'hi' }] }) - // A different new session coexists. - const other = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(other.sessionId).not.toBe(sessionId) - // Re-loading the already-live id is rejected. - await expect(live.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] })) - .rejects.toThrow(/already loaded/) - }) -}) diff --git a/packages/ui/acp/tests/modes.spec.ts b/packages/ui/acp/tests/modes.spec.ts deleted file mode 100644 index 7680d611c4..0000000000 --- a/packages/ui/acp/tests/modes.spec.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { SessionId } from '@deepseek-ai/dsh-session' -import { makeBridgeHarness, textResponse, type BridgeHarness, type CapturedUpdate } from './harness.ts' - -/** The `current_mode_update` notifications, in order. */ -function modeUpdates(updates: CapturedUpdate[]): string[] { - return updates - .filter(update => update.sessionUpdate === 'current_mode_update') - .map(update => update.currentModeId) -} - -describe('acp bridge — plan mode projection', () => { - let storageDir: string - let harness: BridgeHarness | undefined - let loader: BridgeHarness | undefined - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-modes-')) }) - afterEach(async () => { - if (harness) await harness.dispose() - if (loader) await loader.dispose() - harness = loader = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - it('advertises no mode surface and rejects session/set_mode when plan mode is not composed', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const res = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(res.modes).toBeUndefined() - await expect(harness.client.setSessionMode({ sessionId: res.sessionId, modeId: 'plan' })) - .rejects.toMatchObject({ message: expect.stringContaining('session modes are not composed') as string }) - }) - - it('advertises availableModes/currentModeId on session/new', async () => { - harness = await makeBridgeHarness({ storageDir, withModes: true }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const res = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - expect(res.modes).toEqual({ - availableModes: [ - { id: 'default', name: 'default' }, - { id: 'plan', name: 'plan' }, - ], - currentModeId: 'default', - }) - }) - - it('session/set_mode records the pending intent and echoes one optimistic current_mode_update', async () => { - harness = await makeBridgeHarness({ storageDir, withModes: true }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await harness.client.setSessionMode({ sessionId, modeId: 'plan' }) - expect(modeUpdates(harness.updates)).toEqual(['plan']) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - expect(harness.ctx.planMode.get(agent)).toEqual({ active: false, pending: true }) - }) - - it('rejects an unknown ACP mode id at the adapter boundary', async () => { - harness = await makeBridgeHarness({ storageDir, withModes: true }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await expect(harness.client.setSessionMode({ sessionId, modeId: 'nope' })) - .rejects.toMatchObject({ message: expect.stringContaining('unknown session mode "nope"') as string }) - expect(modeUpdates(harness.updates)).toEqual([]) - }) - - it('does not re-notify when the boundary flush logs the mode the picker already showed', async () => { - harness = await makeBridgeHarness({ storageDir, withModes: true, script: [textResponse('planning')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await harness.client.setSessionMode({ sessionId, modeId: 'plan' }) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go plan' }] }) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - expect(agent.session.events.some(event => event.type === 'plan/mode')).toBe(true) - expect(modeUpdates(harness.updates)).toEqual(['plan']) - }) - - it('re-notifies on a logged flip the picker has not seen (the tool-driven exit shape)', async () => { - harness = await makeBridgeHarness({ storageDir, withModes: true, script: [textResponse('planning')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await harness.client.setSessionMode({ sessionId, modeId: 'plan' }) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go plan' }] }) - // A writer other than the picker (exit_plan_mode's execute) appends the - // flip back; the bridge must re-notify the client off the logged event. - const agent = harness.ctx.agents.get(SessionId(sessionId))! - agent.session.append('plan/mode', { active: false }) - // The notification crosses the in-memory JSON-RPC transport asynchronously. - await new Promise(resolve => setTimeout(resolve, 20)) - expect(modeUpdates(harness.updates)).toEqual(['plan', 'default']) - }) - - it('advertises the folded mode on session/load', async () => { - harness = await makeBridgeHarness({ storageDir, withModes: true, script: [textResponse('planning')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - await harness.client.setSessionMode({ sessionId, modeId: 'plan' }) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go plan' }] }) - await harness.dispose() - harness = undefined - - loader = await makeBridgeHarness({ storageDir, withModes: true, script: [] }) - await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const res = await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }) - expect(res.modes).toEqual({ - availableModes: [ - { id: 'default', name: 'default' }, - { id: 'plan', name: 'plan' }, - ], - currentModeId: 'plan', - }) - }) -}) diff --git a/packages/ui/acp/tests/multi-session.spec.ts b/packages/ui/acp/tests/multi-session.spec.ts deleted file mode 100644 index efeb00f9ad..0000000000 --- a/packages/ui/acp/tests/multi-session.spec.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { makeBridgeHarness, textResponse, type BridgeHarness, type CapturedUpdate } from './harness.ts' -import { SessionId } from '@deepseek-ai/dsh-session' - -/** Text of the agent_message_chunk updates scoped to one session id. */ -function messageTextFor(updates: { sessionId?: string; update: CapturedUpdate }[], sessionId: string): string { - return updates - .filter(u => u.sessionId === sessionId && u.update.sessionUpdate === 'agent_message_chunk') - .map(u => (u.update.sessionUpdate === 'agent_message_chunk' && u.update.content.type === 'text' ? u.update.content.text : '')) - .join('') -} - -describe('acp bridge — multi-session isolation', () => { - let storageDir: string - let harness: BridgeHarness | undefined - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-multi-')) }) - afterEach(async () => { - if (harness) await harness.dispose() - harness = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - it('two sessions stream concurrently without interleaving their updates', async () => { - // Each session's prompt answer must arrive only on its own sessionId. The - // scripted adapter answers in send order; both prompts run, and the bridge - // demuxes every chunk by session id. - harness = await makeBridgeHarness({ storageDir, script: [textResponse('answer-A'), textResponse('answer-B')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId - const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId - - const [ra, rb] = await Promise.all([ - harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'go A' }] }), - harness.client.prompt({ sessionId: b, prompt: [{ type: 'text', text: 'go B' }] }), - ]) - expect(ra.stopReason).toBe('end_turn') - expect(rb.stopReason).toBe('end_turn') - - // A's text landed only on A; B's only on B (strict id demux, no interleave). - expect(messageTextFor(harness.sessionUpdates, a)).toContain('answer-A') - expect(messageTextFor(harness.sessionUpdates, a)).not.toContain('answer-B') - expect(messageTextFor(harness.sessionUpdates, b)).toContain('answer-B') - expect(messageTextFor(harness.sessionUpdates, b)).not.toContain('answer-A') - }) - - it('cancel in one session leaves the other session untouched', async () => { - // Session A hangs; session B completes normally. Cancelling A settles ONLY - // A as cancelled and never disturbs B's stream or result. - harness = await makeBridgeHarness({ storageDir, script: ['hang', textResponse('B done')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId - const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId - - const aPromise = harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'hang A' }] }) - await new Promise(r => setTimeout(r, 30)) - await harness.client.cancel({ sessionId: a }) - expect((await aPromise).stopReason).toBe('cancelled') - - // B runs to completion, unaffected by A's cancel. - const rb = await harness.client.prompt({ sessionId: b, prompt: [{ type: 'text', text: 'go B' }] }) - expect(rb.stopReason).toBe('end_turn') - expect(messageTextFor(harness.sessionUpdates, b)).toContain('B done') - }) - - it('enforces one in-flight prompt PER session independently', async () => { - harness = await makeBridgeHarness({ storageDir, script: ['hang', 'hang'] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId - const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId - - // One in-flight prompt in EACH session is allowed (independent limits). - const aPromise = harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'one A' }] }) - const bPromise = harness.client.prompt({ sessionId: b, prompt: [{ type: 'text', text: 'one B' }] }) - await new Promise(r => setTimeout(r, 30)) - // A second prompt in A is rejected, but B's in-flight prompt is unaffected. - await expect(harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'two A' }] })) - .rejects.toThrow(/already in flight/) - - await harness.client.cancel({ sessionId: a }) - await harness.client.cancel({ sessionId: b }) - expect((await aPromise).stopReason).toBe('cancelled') - expect((await bPromise).stopReason).toBe('cancelled') - }) - - it('a cancel for a non-existent session id is a silent no-op (does not touch others)', async () => { - harness = await makeBridgeHarness({ storageDir, script: [textResponse('A done')] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId - await expect(harness.client.cancel({ sessionId: 'ghost' })).resolves.toBeUndefined() - // A still works after a cancel for an unknown id. - const ra = await harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'go A' }] }) - expect(ra.stopReason).toBe('end_turn') - }) - - it('disposing the whole bridge drains all live sessions to quiescence', async () => { - harness = await makeBridgeHarness({ storageDir, script: ['hang', 'hang'] }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId - const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId - const agentA = harness.ctx.agents.get(SessionId(a))! - const agentB = harness.ctx.agents.get(SessionId(b))! - - // Wait deterministically for BOTH agents to enter `running` (not a fixed - // sleep — agent startup latency is unbounded on a loaded worker). - const running = (agent: typeof agentA) => agent.status === 'running' - ? Promise.resolve() - : new Promise<void>((resolve) => { - const dispose = harness!.ctx.on('agent/status', (subject, status) => { - if (subject === agent && status === 'running') { dispose(); resolve() } - }) - }) - void harness.client.prompt({ sessionId: a, prompt: [{ type: 'text', text: 'go A' }] }).catch(() => {}) - void harness.client.prompt({ sessionId: b, prompt: [{ type: 'text', text: 'go B' }] }).catch(() => {}) - await Promise.all([running(agentA), running(agentB)]) - expect(agentA.status).toBe('running') - expect(agentB.status).toBe('running') - - await harness.ctx.fiber.dispose() - // BOTH agents drained (not still running) — teardown reached quiescence - // across all sessions, not just one. - expect(agentA.status).not.toBe('running') - expect(agentB.status).not.toBe('running') - }) -}) diff --git a/packages/ui/acp/tests/properties.spec.ts b/packages/ui/acp/tests/properties.spec.ts deleted file mode 100644 index af661d0eed..0000000000 --- a/packages/ui/acp/tests/properties.spec.ts +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Property-based protocol-shape tests for the ACP update stream (RFC 001 → ADR 0013 - * precedent). Fuzz arbitrary harness `SessionEvent` sequences through the pure - * `streamSessionEventUpdate` translator and assert legal update variants, call-before-result order - * per tool id, and deterministic event-to-update translation. Keeping this pure makes live and - * replay equivalence deterministic rather than a timing property. - */ - -import { describe, expect, it } from 'vitest' -import fc from 'fast-check' -import { CallId } from '@deepseek-ai/dsh-llm' -import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' -import type { SessionNotification } from '@agentclientprotocol/sdk' -import { streamSessionEventUpdate } from '../src/index.ts' - -const LEGAL_UPDATE_KINDS = new Set([ - 'agent_message_chunk', - 'agent_thought_chunk', - 'tool_call', - 'tool_call_update', -]) - -/** - * Build a WELL-FORMED harness event sequence: a list of "actions" where a tool - * result can only reference a call already opened earlier. This mirrors what - * the loop actually appends (tool/call always precedes its tool/result), so the - * ordering invariant is asserted over realistic logs, not arbitrary noise. - */ -type Action = - | { kind: 'text'; text: string } - | { kind: 'reasoning'; text: string } - | { kind: 'call'; id: string; name: string } - | { kind: 'result'; idx: number; isError: boolean } - | { kind: 'ignored' } - -function actionsArb(): fc.Arbitrary<Action[]> { - const action: fc.Arbitrary<Action> = fc.oneof( - fc.string().map((text): Action => ({ kind: 'text', text })), - fc.string().map((text): Action => ({ kind: 'reasoning', text })), - fc.record({ id: fc.string({ minLength: 1 }), name: fc.string() }).map(({ id, name }): Action => ({ kind: 'call', id, name })), - fc.record({ idx: fc.nat(), isError: fc.boolean() }).map(({ idx, isError }): Action => ({ kind: 'result', idx, isError })), - fc.constant<Action>({ kind: 'ignored' }), - ) - return fc.array(action, { maxLength: 30 }) -} - -/** Lower well-formed actions into a harness event sequence. */ -function actionsToEvents(actions: Action[]): SessionEvent[] { - const events: SessionEvent[] = [] - const openCalls: string[] = [] - for (const a of actions) { - switch (a.kind) { - case 'text': - events.push({ type: 'assistant/chunk', seq: 0, time: 0, data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: a.text } } }) - break - case 'reasoning': - events.push({ type: 'assistant/chunk', seq: 0, time: 0, data: { turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: a.text } } }) - break - case 'call': - openCalls.push(a.id) - events.push({ type: 'tool/call', seq: 0, time: 0, data: { turn: 1, step: 1, callId: CallId(a.id), name: a.name, arguments: '{}' } }) - break - case 'result': { - // Only emit a result for an already-opened call (well-formedness). - if (openCalls.length === 0) break - const id = openCalls[a.idx % openCalls.length]! - events.push({ type: 'tool/result', seq: 0, time: 0, data: { turn: 1, step: 1, callId: CallId(id), content: [], isError: a.isError } }) - break - } - case 'ignored': - events.push({ type: 'turn/end', seq: 0, time: 0, data: { turn: 1, reason: { kind: 'completed' } } }) - break - } - } - return events -} - -function runStream(events: SessionEvent[]): SessionNotification['update'][] { - const out: SessionNotification['update'][] = [] - for (const event of events) streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update)) - return out -} - -describe('ACP update-stream invariants (property-based)', () => { - it('every emitted update is a legal SessionUpdate variant', () => { - fc.assert(fc.property(actionsArb(), (actions) => { - for (const update of runStream(actionsToEvents(actions))) { - expect(LEGAL_UPDATE_KINDS.has(update.sessionUpdate)).toBe(true) - } - })) - }) - - it('never emits a tool_call_update for an id before that id\'s tool_call', () => { - fc.assert(fc.property(actionsArb(), (actions) => { - const seenCall = new Set<string>() - for (const update of runStream(actionsToEvents(actions))) { - if (update.sessionUpdate === 'tool_call') { - seenCall.add(update.toolCallId) - } else if (update.sessionUpdate === 'tool_call_update') { - expect(seenCall.has(update.toolCallId)).toBe(true) - } - } - })) - }) - - it('is a pure function of the event (replay equals live)', () => { - fc.assert(fc.property(actionsArb(), (actions) => { - const events = actionsToEvents(actions) - expect(runStream(events)).toEqual(runStream(events)) - })) - }) -}) diff --git a/packages/ui/acp/tests/session-list.spec.ts b/packages/ui/acp/tests/session-list.spec.ts deleted file mode 100644 index fe9e554e60..0000000000 --- a/packages/ui/acp/tests/session-list.spec.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { SessionId } from '@deepseek-ai/dsh-session' -import type {} from '@deepseek-ai/dsh-session-title' -import { encodeSessionReferenceUri } from '@deepseek-ai/dsh-session-reference' -import { ACP_SESSION_REFERENCE_META_KEY } from '../src/index.ts' -import { makeBridgeHarness, type BridgeHarness } from './harness.ts' - -describe('acp bridge — session/list', () => { - let storageDir: string - let harness: BridgeHarness | undefined - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-list-')) }) - afterEach(async () => { - await harness?.dispose() - harness = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - it('advertises title-aware listing and reference metadata for loadable sessions', async () => { - harness = await makeBridgeHarness({ storageDir, withSessionReferences: true }) - const initialized = await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - expect(initialized.agentCapabilities?.sessionCapabilities?.list).toEqual({}) - - const cwd = process.cwd() - const { sessionId } = await harness.client.newSession({ cwd, mcpServers: [] }) - const session = harness.ctx.agents.get(SessionId(sessionId))!.session - await harness.ctx.sessions.appendOutOfBand(session, 'session/title', { - title: 'Reference source title', - messageSeqs: [], - source: { kind: 'fallback' }, - }, { kind: 'session-title' }) - harness.ctx.sessions.create(SessionId('untitled'), { meta: { cwd: join(storageDir, 'other') } }) - harness.ctx.sessions.create(SessionId('missing-cwd')) - - const listed = await harness.client.listSessions({}) - expect(listed.nextCursor).toBeUndefined() - expect(listed.sessions.map(item => item.sessionId)).toEqual(expect.arrayContaining([sessionId, 'untitled'])) - expect(listed.sessions.map(item => item.sessionId)).not.toContain('missing-cwd') - const source = listed.sessions.find(item => item.sessionId === sessionId) - expect(source).toMatchObject({ cwd, title: 'Reference source title' }) - expect(source?._meta?.[ACP_SESSION_REFERENCE_META_KEY]).toEqual({ - uri: encodeSessionReferenceUri(SessionId(sessionId)), - }) - expect(listed.sessions.find(item => item.sessionId === 'untitled')).not.toHaveProperty('title') - }) - - it('filters by normalized cwd and omits reference metadata without the optional capability', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const firstCwd = join(storageDir, 'first') - const secondCwd = join(storageDir, 'second') - const first = await harness.client.newSession({ cwd: firstCwd, mcpServers: [] }) - await harness.client.newSession({ cwd: secondCwd, mcpServers: [] }) - - const listed = await harness.client.listSessions({ cursor: null, cwd: firstCwd }) - expect(listed.sessions).toHaveLength(1) - expect(listed.sessions[0]).toMatchObject({ sessionId: first.sessionId, cwd: firstCwd }) - expect(listed.sessions[0]?._meta).toBeUndefined() - await expect(harness.client.listSessions({ cwd: null })).resolves.toHaveProperty('sessions') - }) - - it('rejects unsupported cursors and relative cwd filters', async () => { - harness = await makeBridgeHarness({ storageDir }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(harness.client.listSessions({ cursor: 'next' })).rejects.toThrow('session/list does not paginate') - await expect(harness.client.listSessions({ cwd: 'relative' })).rejects.toThrow('session/list cwd must be absolute') - }) - - it('folds titles from persisted sessions in a fresh bridge', async () => { - harness = await makeBridgeHarness({ storageDir, withSessionReferences: true }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - const cwd = process.cwd() - const { sessionId } = await harness.client.newSession({ cwd, mcpServers: [] }) - const session = harness.ctx.agents.get(SessionId(sessionId))!.session - await harness.ctx.sessions.appendOutOfBand(session, 'session/title', { - title: 'Persisted reference title', - messageSeqs: [], - source: { kind: 'fallback' }, - }, { kind: 'session-title' }) - await harness.dispose() - - harness = await makeBridgeHarness({ storageDir, withSessionReferences: true }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await expect(harness.client.listSessions({ cwd })).resolves.toMatchObject({ - sessions: [{ sessionId, cwd, title: 'Persisted reference title' }], - }) - }) -}) diff --git a/packages/ui/acp/tests/stream-update.spec.ts b/packages/ui/acp/tests/stream-update.spec.ts deleted file mode 100644 index 2585968b7e..0000000000 --- a/packages/ui/acp/tests/stream-update.spec.ts +++ /dev/null @@ -1,966 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { join as pathJoin, resolve as pathResolve } from 'node:path' -import { Context } from 'cordis' -import { CallId } from '@deepseek-ai/dsh-llm' -import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' -import type {} from '@deepseek-ai/dsh-session-title' -import type { SessionNotification } from '@agentclientprotocol/sdk' -import type { ToolDefinition, ToolRegistry as ToolRegistryType } from '@deepseek-ai/dsh-tools' -import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import ToolRegistry from '@deepseek-ai/dsh-tools' -import FsLocal from '@deepseek-ai/dsh-fs-local' -import * as ToolFs from '@deepseek-ai/dsh-tool-fs' -import { streamSessionEventUpdate, agentOptions, todosToPlan, ToolPresenter } from '../src/index.ts' - -const UNUSED_TOOL_OUTPUT: ToolDefinition['output'] = { - schema: { type: 'null' }, - render: () => [], -} - -/** Collect the updates a single event produces (no presenter → generic fallback). */ -function updatesFor(event: SessionEvent): SessionNotification['update'][] { - const out: SessionNotification['update'][] = [] - streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update)) - return out -} - -/** Collect the updates emitted by the live prompt stream (user echo suppressed). */ -function liveUpdatesFor(event: SessionEvent): SessionNotification['update'][] { - const out: SessionNotification['update'][] = [] - streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update), undefined, undefined, { includeUserMessages: false }) - return out -} - -/** A tiny tool registry stub exposing just `get` for {@link ToolPresenter}. */ -function registryOf(...tools: ToolDefinition[]): Pick<ToolRegistryType, 'get'> { - const map = new Map(tools.map(t => [t.name, t])) - return { get: name => map.get(name) } -} - -function updatesWith(presenter: ToolPresenter, ...events: SessionEvent[]): SessionNotification['update'][] { - const out: SessionNotification['update'][] = [] - for (const event of events) streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update), presenter) - return out -} - -async function fsCtx(): Promise<Context> { - const ctx = new Context() - await ctx.plugin(SystemPrompt) - await ctx.plugin(ToolRegistry) - await ctx.plugin(FsLocal) - await ctx.plugin(ToolFs) - return ctx -} - -function evt<T extends SessionEvent['type']>(type: T, data: Extract<SessionEvent, { type: T }>['data']): SessionEvent { - return { type, seq: 0, time: 0, data } as SessionEvent -} - -/** ACP path fields are filesystem paths; expectations use the host separator. */ -function nativePath(...segments: string[]): string { - return pathJoin(...segments) -} - -/** Resolve root-relative fixtures the same way the bridge does on this host. */ -function nativeAbsolute(...segments: string[]): string { - return pathResolve(...segments) -} - -describe('streamSessionEventUpdate', () => { - it('maps a title event to session_info_update with the event timestamp', () => { - expect(updatesFor({ - type: 'session/title', - seq: 3, - time: 1_725_000_000_000, - data: { - title: 'Log-backed titles', - messageSeqs: [1], - source: { kind: 'fallback' }, - }, - })).toEqual([{ - sessionUpdate: 'session_info_update', - title: 'Log-backed titles', - updatedAt: new Date(1_725_000_000_000).toISOString(), - }]) - }) - - it('maps assistant/chunk text-delta to agent_message_chunk', () => { - expect(updatesFor(evt('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'hi' } }))) - .toEqual([{ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'hi' } }]) - }) - - it('maps assistant/chunk reasoning-delta to agent_thought_chunk', () => { - expect(updatesFor(evt('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'mm' } }))) - .toEqual([{ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: 'mm' } }]) - }) - - it('produces no update for a non-text/reasoning chunk (e.g. block-start)', () => { - expect(updatesFor(evt('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'block-start', index: 0, blockType: 'text' } }))) - .toEqual([]) - }) - - it('marks retry and terminal model failure boundaries but not ordinary turn errors', () => { - expect(updatesFor(evt('llm/retry', { - turn: 1, - step: 1, - retry: 1, - maxRetries: 2, - delayMs: 500, - failure: { message: 'backend busy', code: 'SERVER' }, - }))).toEqual([{ - sessionUpdate: 'agent_message_chunk', - content: { - type: 'text', - text: '\n\n[Previous model attempt discarded; retrying 1/2 in 500ms: backend busy]\n\n', - }, - }]) - expect(updatesFor(evt('turn/end', { - turn: 1, - reason: { kind: 'error', step: 2, failure: { message: 'still busy', code: 'SERVER' } }, - }))).toEqual([{ - sessionUpdate: 'agent_message_chunk', - content: { - type: 'text', - text: '\n\n[Model attempt failed; any partial output above is discarded: still busy]\n\n', - }, - }]) - expect(updatesFor(evt('turn/end', { - turn: 1, - reason: { kind: 'error', step: 2, message: 'post-step failed' }, - }))).toEqual([]) - }) - - it('maps tool/call to an in_progress tool_call with kind other and parsed rawInput (generic fallback, no presenter)', () => { - const updates = updatesFor(evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: '{"command":"ls"}' })) - expect(updates).toEqual([{ - sessionUpdate: 'tool_call', - toolCallId: 'c1', - title: 'bash', - // The fallback never sniffs a kind from the tool name — even a name a - // first-party tool uses (`bash`) renders `other`; kinds are tool-owned - // via presentCall. - kind: 'other', - status: 'in_progress', - rawInput: { command: 'ls' }, - }]) - }) - - it('falls back to the raw argument string when tool arguments are not JSON', () => { - const update = updatesFor(evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: 'not json' }))[0] - expect((update as { rawInput: unknown }).rawInput).toBe('not json') - }) - - it('parses EMPTY tool arguments to an empty-object rawInput (a zero-arg call, not the raw-string fallback)', () => { - // `JSON.parse('')` throws, so without the empty-string guard a zero-arg - // call would render `rawInput: ''` via the non-JSON fallback; the guard - // normalizes it to `{}`. - const update = updatesFor(evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'noop', arguments: '' }))[0] - expect((update as { rawInput: unknown }).rawInput).toEqual({}) - }) - - it('maps tool/result to completed/failed tool_call_update with text content', () => { - const ok = updatesFor(evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'out' }], isError: false })) - expect(ok).toEqual([{ - sessionUpdate: 'tool_call_update', - toolCallId: 'c1', - status: 'completed', - content: [{ type: 'content', content: { type: 'text', text: 'out' } }], - }]) - const failed = updatesFor(evt('tool/result', { turn: 1, step: 1, callId: CallId('c2'), content: [], isError: true })) - expect((failed[0] as { status: string }).status).toBe('failed') - }) - - it('emits no execution update for a tool-result surface replacement', () => { - const replacement = { - ...evt('tool/result', { - turn: 1, - step: 1, - callId: CallId('c1'), - content: [{ type: 'text', text: '[... tool result middle pruned ...]' }], - isError: false, - }), - seq: 2, - surfaceOp: { op: 'replace', start: 1, end: 1 }, - sourceEventSeqs: [1], - } as SessionEvent - expect(updatesFor(replacement)).toEqual([]) - }) - - it('drops non-text tool-result content (text-only)', () => { - const update = updatesFor(evt('tool/result', { - turn: 1, step: 1, callId: CallId('c1'), - content: [{ type: 'reasoning', text: 'private' }], - isError: false, - }))[0] - expect((update as { content: unknown[] }).content).toEqual([]) - }) - - it('maps user/message text blocks to user_message_chunk (load replays the user side)', () => { - // A text block surfaces; a non-text block (here a tool-call) is skipped, so - // only the text chunk is emitted. - expect(updatesFor(evt('user/message', { - content: [ - { type: 'text', text: 'hi' }, - { type: 'tool-call', id: CallId('c'), name: 'bash', arguments: '{}' }, - ], - source: { kind: 'user' }, - }))).toEqual([{ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'hi' } }]) - // A user/message with no text-bearing blocks produces no chunk. - expect(updatesFor(evt('user/message', { content: [], source: { kind: 'user' } }))).toEqual([]) - }) - - it('replays only the direct prompt from a prefixed user message', () => { - expect(updatesFor(evt('user/message', { - content: [ - { type: 'text', text: 'internal prefix' }, - { type: 'text', text: '\n\n## My request:\n' }, - { type: 'text', text: 'visible request' }, - ], - source: { kind: 'user' }, - envelope: { - displayContent: [{ type: 'text', text: 'visible request' }], - prefixContexts: [{ source: { kind: 'plugin', plugin: 'reference' } }], - }, - }))).toEqual([{ - sessionUpdate: 'user_message_chunk', - content: { type: 'text', text: 'visible request' }, - }]) - }) - - it('can suppress user/message chunks for live prompt turns', () => { - expect(liveUpdatesFor(evt('user/message', { - content: [{ type: 'text', text: 'hi' }], - source: { kind: 'user' }, - }))).toEqual([]) - }) - - it('produces no update for boundary/other event types', () => { - expect(updatesFor(evt('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }))).toEqual([]) - expect(updatesFor(evt('turn/end', { turn: 1, reason: { kind: 'completed' } }))).toEqual([]) - expect(updatesFor(evt('step/start', { turn: 1, step: 1 }))).toEqual([]) - }) - - it('maps todo/write to a plan sessionUpdate with priority synthesized as medium', () => { - expect(updatesFor(evt('todo/write', { - todos: [ - { content: 'plan the work', status: 'in_progress' }, - { content: 'write the code', status: 'pending' }, - { content: 'run the tests', status: 'completed' }, - ], - }))).toEqual([{ - sessionUpdate: 'plan', - entries: [ - { content: 'plan the work', priority: 'medium', status: 'in_progress' }, - { content: 'write the code', priority: 'medium', status: 'pending' }, - { content: 'run the tests', priority: 'medium', status: 'completed' }, - ], - }]) - }) - - it('maps an empty todo list to a plan with no entries', () => { - expect(updatesFor(evt('todo/write', { todos: [] }))).toEqual([{ sessionUpdate: 'plan', entries: [] }]) - }) -}) - -describe('todosToPlan', () => { - it('maps status 1:1 and stamps every entry priority medium', () => { - expect(todosToPlan([ - { content: 'a', status: 'pending' }, - { content: 'b', status: 'in_progress' }, - { content: 'c', status: 'completed' }, - ])).toEqual({ - entries: [ - { content: 'a', priority: 'medium', status: 'pending' }, - { content: 'b', priority: 'medium', status: 'in_progress' }, - { content: 'c', priority: 'medium', status: 'completed' }, - ], - }) - }) -}) - -describe('ToolPresenter (tool-owned presentation via the tool registry)', () => { - /** A tool whose presentCall/presentResult return generic-card views. */ - const bashLike: ToolDefinition = { - name: 'bash', - description: 'run a command', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - presentCall: (args: unknown) => { - const a = args as { command: string; description: string } - return { card: 'generic', title: a.description, kind: 'execute', rawInput: a.command } - }, - presentResult: (_args: unknown, result: { content: { type: string }[] }) => ({ - card: 'generic', - content: [{ type: 'text', text: `wrapped:${result.content.length}` }], - }), - } - - it('tool/call uses the tool: description→title, command→rawInput, tool kind', () => { - const presenter = new ToolPresenter(registryOf(bashLike)) - const [update] = updatesWith(presenter, evt('tool/call', { - turn: 1, step: 1, callId: CallId('c1'), name: 'bash', - arguments: JSON.stringify({ command: 'ls -la', description: 'List files' }), - })) - expect(update).toEqual({ - sessionUpdate: 'tool_call', - toolCallId: 'c1', - title: 'List files', - kind: 'execute', - status: 'in_progress', - rawInput: 'ls -la', - }) - }) - - it('tool/result uses the tool to reformat content (resolved by the remembered tool/call)', () => { - const presenter = new ToolPresenter(registryOf(bashLike)) - const updates = updatesWith( - presenter, - evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: JSON.stringify({ command: 'x', description: 'd' }) }), - evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'out' }], isError: false }), - ) - expect(updates[1]).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'c1', - status: 'completed', - content: [{ type: 'content', content: { type: 'text', text: 'wrapped:1' } }], - }) - }) - - it('a result with NO preceding call (unknown callId) falls back to the raw content', () => { - const presenter = new ToolPresenter(registryOf(bashLike)) - // No tool/call for c9 → presenter has nothing remembered → generic fallback. - const [update] = updatesWith(presenter, evt('tool/result', { - turn: 1, step: 1, callId: CallId('c9'), content: [{ type: 'text', text: 'raw' }], isError: false, - })) - expect(update).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'c9', - status: 'completed', - content: [{ type: 'content', content: { type: 'text', text: 'raw' } }], - }) - }) - - it('a tool with no presentCall/presentResult gets the generic fallback (title = name)', () => { - const plain: ToolDefinition = { name: 'plain', description: 'p', parameters: {}, output: UNUSED_TOOL_OUTPUT, execute: async () => [] } - const presenter = new ToolPresenter(registryOf(plain)) - const [update] = updatesWith(presenter, evt('tool/call', { - turn: 1, step: 1, callId: CallId('c1'), name: 'plain', arguments: '{"a":1}', - })) - expect(update).toMatchObject({ title: 'plain', kind: 'other', rawInput: { a: 1 } }) - }) - - it('a presentation that omits kind/content/rawInput uses the defaults (kind other, raw result content kept)', () => { - // A minimal tool-owned presentation: presentCall returns only a title (no - // kind → defaults to `other`, no rawInput → omitted); presentResult returns - // only a title (no content → the raw result content is kept). - const minimal: ToolDefinition = { - name: 'mini', - description: 'm', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - presentCall: () => ({ card: 'generic', title: 'Doing a thing' }), - presentResult: () => ({ card: 'generic', title: 'Did the thing' }), - } - const presenter = new ToolPresenter(registryOf(minimal)) - const updates = updatesWith( - presenter, - evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'mini', arguments: '{}' }), - evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'kept' }], isError: false }), - ) - // No kind → 'other'; no rawInput key at all. - expect(updates[0]).toEqual({ sessionUpdate: 'tool_call', toolCallId: 'c1', title: 'Doing a thing', kind: 'other', status: 'in_progress' }) - // Title replaced; content falls back to the raw result content. - expect(updates[1]).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'c1', - status: 'completed', - content: [{ type: 'content', content: { type: 'text', text: 'kept' } }], - title: 'Did the thing', - }) - }) - - it('holds ONLY in-flight calls: the callId entry is removed once its result is presented', () => { - const presenter = new ToolPresenter(registryOf(bashLike)) - updatesWith( - presenter, - evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: JSON.stringify({ command: 'x', description: 'd' }) }), - evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'o' }], isError: false }), - ) - // A SECOND result for the same callId now finds nothing remembered, so it - // falls back to raw content (proving the first result consumed the entry — - // the map does not retain finished calls). - const [late] = updatesWith(presenter, evt('tool/result', { - turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'late' }], isError: false, - })) - expect(late).toMatchObject({ content: [{ type: 'content', content: { type: 'text', text: 'late' } }] }) - }) - - it('a THROWING presentCall/presentResult is contained: generic fallback + onError, never propagates', () => { - // A buggy tool whose display callbacks throw must not fail a live turn or a session/load - // replay (docs/defensive-patterns.md "contain callback exceptions at the boundary"). The - // presenter reports the error and falls back to generic rendering. - const boom: ToolDefinition = { - name: 'boom', - description: 'b', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - presentCall: () => { throw new Error('call boom') }, - presentResult: () => { throw new Error('result boom') }, - } - const errors: string[] = [] - const presenter = new ToolPresenter(registryOf(boom), msg => errors.push(msg)) - const updates = updatesWith( - presenter, - evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'boom', arguments: '{"a":1}' }), - evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'raw' }], isError: false }), - ) - // tool/call fell back to title=name, raw args as rawInput. - expect(updates[0]).toMatchObject({ sessionUpdate: 'tool_call', title: 'boom', kind: 'other', rawInput: { a: 1 } }) - // tool/result fell back to the raw content. - expect(updates[1]).toMatchObject({ sessionUpdate: 'tool_call_update', content: [{ type: 'content', content: { type: 'text', text: 'raw' } }] }) - // Both throws were reported, not propagated. - expect(errors).toHaveLength(2) - expect(errors[0]).toContain('presentCall threw') - expect(errors[1]).toContain('presentResult threw') - }) - - it('contains a throwing presenter even with the DEFAULT (no-op) onError sink', () => { - // Constructed without an onError sink (the default `() => {}`): a throwing - // presenter is still swallowed and falls back generically — the absence of a - // logger must not turn a display bug into a propagated exception. - const boom: ToolDefinition = { - name: 'boom', - description: 'b', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - presentCall: () => { throw new Error('call boom') }, - presentResult: () => { throw new Error('result boom') }, - } - const presenter = new ToolPresenter(registryOf(boom)) - const updates = updatesWith( - presenter, - evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'boom', arguments: '{}' }), - evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'raw' }], isError: false }), - ) - expect(updates[0]).toMatchObject({ sessionUpdate: 'tool_call', title: 'boom' }) - expect(updates[1]).toMatchObject({ sessionUpdate: 'tool_call_update', content: [{ type: 'content', content: { type: 'text', text: 'raw' } }] }) - }) - - it('an unknown render-intent card throws via the exhaustiveness guard (closed union)', () => { - // The bridge switches on `view.card` and ends with assertNever: a rogue card - // (only reachable by a cast — the union is closed) must throw, so adding a - // real variant later fails to compile at the switch instead of silently - // dropping the card. - const rogue: ToolDefinition = { - name: 'rogue', - description: 'r', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - // A card value outside the union — forced with a cast (no valid input reaches this). - presentCall: () => ({ card: 'chart', title: 'nope' }) as unknown as ReturnType<NonNullable<ToolDefinition['presentCall']>>, - } - const presenter = new ToolPresenter(registryOf(rogue)) - expect(() => updatesWith(presenter, evt('tool/call', { - turn: 1, step: 1, callId: CallId('c1'), name: 'rogue', arguments: '{}', - }))).toThrow('unreachable variant') - }) - - it('an unknown render-intent RESULT card throws via the exhaustiveness guard (closed union)', () => { - // The result-side renderer is also an exhaustive switch + assertNever: a rogue - // result card (only reachable by a cast) must throw, so adding a real result - // variant later fails to compile at the switch. - const rogue: ToolDefinition = { - name: 'rogue', - description: 'r', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - presentCall: () => ({ card: 'generic', title: 'r' }), - presentResult: () => ({ card: 'chart' }) as unknown as ReturnType<NonNullable<ToolDefinition['presentResult']>>, - } - const presenter = new ToolPresenter(registryOf(rogue)) - expect(() => updatesWith( - presenter, - evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'rogue', arguments: '{}' }), - evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'x' }], isError: false }), - )).toThrow('unreachable variant') - }) - - it('forwards fs-tool render intents onto the wire (REAL read → generic locations, edit → diff content)', async () => { - // Use the SHIPPING fs tools (not a stand-in), booted through their real - // plugins, so the wire tool_call carries the actual presentCall output — - // read's follow-along `locations` and edit's `diff` content block. (docs/testing.md - // "prefer the real implementation over a mock".) - const ctx = new Context() - await ctx.plugin(SystemPrompt) - await ctx.plugin(ToolRegistry) - await ctx.plugin(FsLocal) - await ctx.plugin(ToolFs) - const presenter = new ToolPresenter(ctx.tools) - - const [readCall] = updatesWith(presenter, evt('tool/call', { - turn: 1, step: 1, callId: CallId('r1'), name: 'read', - arguments: JSON.stringify({ file_path: 'src/a.ts', offset: 12 }), - })) - // A generic card: the read window is in the title, the offset drives the - // follow-along location line. No rawInput (the window lives in the title). - expect(readCall).toMatchObject({ - sessionUpdate: 'tool_call', toolCallId: 'r1', title: 'Read src/a.ts (from line 12)', kind: 'read', - locations: [{ path: 'src/a.ts', line: 12 }], - }) - expect((readCall as { rawInput?: unknown }).rawInput).toBeUndefined() - - const [editCall] = updatesWith(presenter, evt('tool/call', { - turn: 1, step: 1, callId: CallId('e1'), name: 'edit', - arguments: JSON.stringify({ file_path: 'src/b.ts', old_string: 'x', new_string: 'y' }), - })) - // A diff card: `edit` kind, a `{ type: 'diff' }` content block carrying the - // literal old→new replacement, plus the follow-along location. - expect(editCall).toMatchObject({ - sessionUpdate: 'tool_call', toolCallId: 'e1', title: 'Edit src/b.ts', kind: 'edit', - locations: [{ path: 'src/b.ts' }], - content: [{ type: 'diff', path: 'src/b.ts', oldText: 'x', newText: 'y' }], - }) - await ctx.fiber.dispose() - }) -}) - -describe('terminal-card mapping (capability-gated)', () => { - // A tool that renders as a terminal — a stand-in for tool-bash's shape, letting - // us drive the bridge's terminal mapping without the real executor. `callCard` - // selects a terminal call view (optionally with a cwd) or a generic one (for the - // orphan-guard test); `resultTerminal` is the terminal result view's output/exit. - type CallCard = { card: 'terminal'; cwd?: string } | { card: 'generic' } - type ResultTerm = { title?: string; output?: string; exitCode?: number; signal?: string } - const termTool = (callCard: CallCard, resultTerminal: ResultTerm): ToolDefinition => ({ - name: 'bash', - description: 'run a command', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - presentCall: (args: unknown) => { - const command = (args as { command: string }).command - const description = (args as { description: string }).description - if (callCard.card === 'terminal') { - return { card: 'terminal', title: command, description, ...callCard.cwd !== undefined ? { cwd: callCard.cwd } : {} } - } - return { card: 'generic', title: command, kind: 'execute', rawInput: command, content: [{ type: 'text', text: description }] } - }, - presentResult: () => ({ card: 'terminal', ...resultTerminal }), - }) - - const callEvent = evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: JSON.stringify({ command: 'echo hi', description: 'Greet' }) }) - const resultEvent = evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'hi\n' }], isError: false }) - const prunedResultEvent = { - ...resultEvent, - seq: 2, - data: { - ...resultEvent.data, - content: [{ type: 'text', text: '[... tool result middle pruned ...]' }], - }, - surfaceOp: { op: 'replace', start: 1, end: 1 }, - sourceEventSeqs: [1], - } as SessionEvent - - function termUpdates(tool: ToolDefinition, enabled: boolean, cwd: string | undefined, ...events: SessionEvent[]): SessionNotification['update'][] { - const presenter = new ToolPresenter(registryOf(tool)) - const out: SessionNotification['update'][] = [] - for (const event of events) streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update), presenter, { enabled, cwd }) - return out - } - - it('capability ON: description content THEN terminal block; cwd from the session header when the tool gives none', () => { - const [call, update] = termUpdates(termTool({ card: 'terminal' }, { output: 'hi\n', exitCode: 0 }), true, '/work/proj', callEvent, resultEvent) - expect(call).toMatchObject({ - sessionUpdate: 'tool_call', - content: [ - { type: 'content', content: { type: 'text', text: 'Greet' } }, - { type: 'terminal', terminalId: 'c1' }, - ], - _meta: { terminal_info: { terminal_id: 'c1', cwd: '/work/proj' } }, - }) - // The update OMITS content (it would clobber the terminal block) and carries output + exit. - expect(update).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'c1', - status: 'completed', - _meta: { terminal_output: { terminal_id: 'c1', data: 'hi\n' }, terminal_exit: { terminal_id: 'c1', exit_code: 0 } }, - }) - }) - - it('live/replay translation preserves the original terminal completion across a pruning rewrite', () => { - const updates = termUpdates( - termTool({ card: 'terminal' }, { output: 'hi\n', exitCode: 0 }), - true, - '/work/proj', - callEvent, - resultEvent, - prunedResultEvent, - ) - expect(updates).toHaveLength(2) - expect(updates[1]).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'c1', - status: 'completed', - _meta: { - terminal_output: { terminal_id: 'c1', data: 'hi\n' }, - terminal_exit: { terminal_id: 'c1', exit_code: 0 }, - }, - }) - }) - - it('capability ON: an ABSOLUTE tool cwd wins; a RELATIVE one resolves against the session cwd', () => { - const [absCall] = termUpdates(termTool({ card: 'terminal', cwd: '/explicit/abs' }, { output: 'x' }), true, '/work/proj', callEvent) - expect((absCall as unknown as { _meta: { terminal_info: { cwd: string } } })._meta.terminal_info.cwd).toBe('/explicit/abs') - const [relCall] = termUpdates(termTool({ card: 'terminal', cwd: nativePath('sub', 'dir') }, { output: 'x' }), true, nativeAbsolute('/work/proj'), callEvent) - // Relative workdir resolved against the session cwd — the card header matches - // where execution actually ran (tool-bash resolves the same way). - expect((relCall as unknown as { _meta: { terminal_info: { cwd: string } } })._meta.terminal_info.cwd).toBe(nativeAbsolute('/work/proj', 'sub', 'dir')) - // No session cwd to resolve against → the relative tool cwd is passed through as-is. - const [noSessionCwd] = termUpdates(termTool({ card: 'terminal', cwd: 'rel/only' }, { output: 'x' }), true, undefined, callEvent) - expect((noSessionCwd as unknown as { _meta: { terminal_info: { cwd: string } } })._meta.terminal_info.cwd).toBe('rel/only') - }) - - it('capability ON: a signal kill maps to terminal_exit.signal', () => { - const [, update] = termUpdates(termTool({ card: 'terminal' }, { output: 'gone', signal: 'SIGKILL' }), true, '/w', callEvent, resultEvent) - expect((update as unknown as { _meta: { terminal_exit: unknown } })._meta.terminal_exit).toEqual({ terminal_id: 'c1', signal: 'SIGKILL' }) - }) - - it('capability ON: a terminal result with output but NO exit/signal emits terminal_output and NO exit pill', () => { - // A terminal-rendering tool that reports no structured exit (neither exitCode - // nor signal) — the card shows output but no exit pill. - const [, update] = termUpdates(termTool({ card: 'terminal' }, { output: 'partial' }), true, '/w', callEvent, resultEvent) - const meta = (update as unknown as { _meta: { terminal_output?: unknown; terminal_exit?: unknown } })._meta - expect(meta.terminal_output).toEqual({ terminal_id: 'c1', data: 'partial' }) - expect(meta.terminal_exit).toBeUndefined() - }) - - it('capability OFF: no terminal block or _meta; the description content and the bridge-derived fenced result render', () => { - const [call, update] = termUpdates(termTool({ card: 'terminal' }, { output: 'hi\n' }), false, '/work/proj', callEvent, resultEvent) - expect(call).toEqual({ - sessionUpdate: 'tool_call', - toolCallId: 'c1', - title: 'echo hi', - kind: 'execute', - status: 'in_progress', - rawInput: 'echo hi', - content: [{ type: 'content', content: { type: 'text', text: 'Greet' } }], - }) - // The bridge derives the fenced ```console fallback from the terminal output. - expect(update).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'c1', - status: 'completed', - content: [{ type: 'content', content: { type: 'text', text: '```console\nhi\n```' } }], - }) - }) - - it('orphan guard: a result-side terminal with a GENERIC call is dropped (no orphan terminal_output)', () => { - // presentCall is a generic card, but presentResult returns a terminal view — - // the bridge must not emit _meta.terminal_output for a terminal Zed never made. - const [call, update] = termUpdates(termTool({ card: 'generic' }, { output: 'hi\n', exitCode: 0 }), true, '/w', callEvent, resultEvent) - // The call was generic → ordinary tool_call (description content, no _meta). - expect((call as { _meta?: unknown })._meta).toBeUndefined() - expect((call as { content: unknown }).content).toEqual([{ type: 'content', content: { type: 'text', text: 'Greet' } }]) - // The result falls back to the RAW result content (the tool/result event's text); NO terminal _meta. - expect((update as { _meta?: unknown })._meta).toBeUndefined() - expect((update as { content: unknown }).content).toEqual([{ type: 'content', content: { type: 'text', text: 'hi\n' } }]) - }) - - it('capability ON: a terminal result title replaces the completed-card title; missing output emits empty data', () => { - // A terminal result MAY carry a replacement title and MAY omit output (a run - // that produced nothing) — the _meta carries empty data, not a dropped key. - const [, update] = termUpdates(termTool({ card: 'terminal' }, { title: 'Ran echo', exitCode: 0 }), true, '/w', callEvent, resultEvent) - expect(update).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'c1', - status: 'completed', - title: 'Ran echo', - _meta: { terminal_output: { terminal_id: 'c1', data: '' }, terminal_exit: { terminal_id: 'c1', exit_code: 0 } }, - }) - }) - - it('capability OFF: a terminal result title rides on the fenced fallback update', () => { - const [, update] = termUpdates(termTool({ card: 'terminal' }, { title: 'Ran echo', output: 'hi\n' }), false, '/w', callEvent, resultEvent) - expect(update).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'c1', - status: 'completed', - content: [{ type: 'content', content: { type: 'text', text: '```console\nhi\n```' } }], - title: 'Ran echo', - }) - }) - - it('a terminal call with NO description and NO capability is a bare execute card (no content key)', () => { - // A terminal view whose presentCall omits `description`, with the capability - // OFF: no description block and no terminal block → the card carries no content. - const noDesc: ToolDefinition = { - name: 'bash', - description: 'run a command', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - presentCall: (args: unknown) => ({ card: 'terminal', title: (args as { command: string }).command }), - } - const [call] = termUpdates(noDesc, false, undefined, callEvent) - expect(call).toEqual({ - sessionUpdate: 'tool_call', - toolCallId: 'c1', - title: 'echo hi', - kind: 'execute', - status: 'in_progress', - rawInput: 'echo hi', - }) - }) -}) - -describe('diff-card mapping', () => { - // A stand-in diff tool, letting us drive the bridge's diff arm across shapes - // the shipping fs tools don't emit (no locations, empty diffs). - const diffTool = (view: unknown): ToolDefinition => ({ - name: 'writer', - description: 'writes a file', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - presentCall: () => view as ReturnType<NonNullable<ToolDefinition['presentCall']>>, - }) - function callUpdate(tool: ToolDefinition, cwd: string | undefined): SessionNotification['update'] { - const presenter = new ToolPresenter(registryOf(tool)) - const out: SessionNotification['update'][] = [] - streamSessionEventUpdate( - SessionId('s1'), - evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'writer', arguments: '{}' }), - n => out.push(n.update), - presenter, - { enabled: false, cwd }, - ) - return out[0]! - } - - it('a diff with NO locations relativizes the title off the first diff path; omits the locations key', () => { - const update = callUpdate(diffTool({ card: 'diff', title: 'Write /work/proj/a.txt', diffs: [{ path: '/work/proj/a.txt', oldText: null, newText: 'x' }] }), '/work/proj') - expect(update).toEqual({ - sessionUpdate: 'tool_call', - toolCallId: 'c1', - title: 'Write a.txt', - kind: 'edit', - status: 'in_progress', - content: [{ type: 'diff', path: '/work/proj/a.txt', oldText: null, newText: 'x' }], - }) - }) - - it('a diff with an EMPTY diffs array omits the content key (no diff blocks to send)', () => { - const update = callUpdate(diffTool({ card: 'diff', title: 'Write nothing', diffs: [] }), undefined) - expect(update).toEqual({ - sessionUpdate: 'tool_call', - toolCallId: 'c1', - title: 'Write nothing', - kind: 'edit', - status: 'in_progress', - }) - }) -}) - -describe('result-time diff card (REAL fs edit tool → tool_call_update diff blocks)', () => { - // Drive the SHIPPING fs edit tool through the bridge: the pending tool/call installs the - // call-time snippet, then the tool/result carries the tool's computed applied-hunk `meta`, - // which presentResult narrows into a `diff` result card the bridge forwards as `{ type: - // 'diff' }` content blocks. The real tool is required because its result metadata is the contract. - it('live/replay translation keeps the applied diff when a pruning rewrite follows', async () => { - const ctx = await fsCtx() - const presenter = new ToolPresenter(ctx.tools) - const args = JSON.stringify({ file_path: 'src/b.ts', old_string: 'OLD', new_string: 'NEW' }) - // The applied hunk the tool would compute and persist on the result meta. - const meta = { diffs: [{ path: 'src/b.ts', oldText: 'a\nOLD\nb', newText: 'a\nNEW\nb' }] } - const originalResult = evt('tool/result', { - turn: 1, - step: 1, - callId: CallId('e1'), - content: [{ type: 'text', text: 'ok' }], - isError: false, - meta, - }) - const replacement = { - ...originalResult, - seq: 3, - data: { - ...originalResult.data, - content: [{ type: 'text', text: '[... tool result middle pruned ...]' }], - }, - surfaceOp: { op: 'replace', start: 2, end: 2 }, - sourceEventSeqs: [2], - } as SessionEvent - const updates = updatesWith( - presenter, - evt('tool/call', { turn: 1, step: 1, callId: CallId('e1'), name: 'edit', arguments: args }), - originalResult, - replacement, - ) - expect(updates).toHaveLength(2) - const resultUpdate = updates[1] - expect(resultUpdate).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'e1', - status: 'completed', - title: 'Edit src/b.ts', - content: [{ type: 'diff', path: 'src/b.ts', oldText: 'a\nOLD\nb', newText: 'a\nNEW\nb' }], - }) - await ctx.fiber.dispose() - }) - - it('an error result carries NO diff card (falls back to raw content)', async () => { - const ctx = await fsCtx() - const presenter = new ToolPresenter(ctx.tools) - const args = JSON.stringify({ file_path: 'src/b.ts', old_string: 'OLD', new_string: 'NEW' }) - const [, resultUpdate] = updatesWith( - presenter, - evt('tool/call', { turn: 1, step: 1, callId: CallId('e1'), name: 'edit', arguments: args }), - evt('tool/result', { turn: 1, step: 1, callId: CallId('e1'), content: [{ type: 'text', text: 'Error: boom' }], isError: true }), - ) - expect(resultUpdate).toMatchObject({ sessionUpdate: 'tool_call_update', status: 'failed' }) - expect(resultUpdate).not.toHaveProperty('content', expect.arrayContaining([expect.objectContaining({ type: 'diff' })])) - await ctx.fiber.dispose() - }) - - it('the completed diff TITLE relativizes against the session cwd (the result title replaces the card header)', async () => { - // A `tool_call_update.title` replaces the card header, so the result-side diff must - // relativize its title exactly as the pending card did — otherwise a completed - // absolute-path edit flips `Edit src/b.ts` back to the raw absolute path. Diff and location - // paths remain absolute so the editor can open the real file. - const ctx = await fsCtx() - const presenter = new ToolPresenter(ctx.tools) - const workspace = nativeAbsolute('/work/proj') - const file = nativeAbsolute('/work/proj', 'src', 'b.ts') - const args = JSON.stringify({ file_path: file, old_string: 'OLD', new_string: 'NEW' }) - const meta = { diffs: [{ path: file, oldText: 'a\nOLD\nb', newText: 'a\nNEW\nb' }] } - const out: SessionNotification['update'][] = [] - const rendering = { enabled: false, cwd: workspace } - for (const event of [ - evt('tool/call', { turn: 1, step: 1, callId: CallId('e1'), name: 'edit', arguments: args }), - evt('tool/result', { turn: 1, step: 1, callId: CallId('e1'), content: [{ type: 'text', text: 'ok' }], isError: false, meta }), - ]) streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update), presenter, rendering) - expect(out[1]).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'e1', - status: 'completed', - title: `Edit ${nativePath('src', 'b.ts')}`, - content: [{ type: 'diff', path: file, oldText: 'a\nOLD\nb', newText: 'a\nNEW\nb' }], - }) - await ctx.fiber.dispose() - }) - - it('a diff result with an EMPTY diffs array and no title omits both keys (nothing to send)', () => { - // Shipping edit always has a hunk and write falls back to a whole-file diff, so a synthetic - // tool is required to cover both absent-title and empty-content result branches. - const emptyDiffTool: ToolDefinition = { - name: 'writer', - description: 'writes a file', - parameters: {}, - output: UNUSED_TOOL_OUTPUT, - execute: async () => [], - presentCall: () => ({ card: 'diff', title: 'Write x', diffs: [{ path: 'x', oldText: null, newText: 'y' }] }), - presentResult: () => ({ card: 'diff', diffs: [] }), - } - const presenter = new ToolPresenter(registryOf(emptyDiffTool)) - const [, resultUpdate] = updatesWith( - presenter, - evt('tool/call', { turn: 1, step: 1, callId: CallId('w1'), name: 'writer', arguments: '{}' }), - evt('tool/result', { turn: 1, step: 1, callId: CallId('w1'), content: [{ type: 'text', text: 'ok' }], isError: false }), - ) - expect(resultUpdate).toEqual({ - sessionUpdate: 'tool_call_update', - toolCallId: 'w1', - status: 'completed', - }) - expect(resultUpdate).not.toHaveProperty('content') - expect(resultUpdate).not.toHaveProperty('title') - }) -}) - -describe('relative-path display titles (bridge relativizes the title against the session cwd)', () => { - // The bridge relativizes a file card's TITLE against the session workspace cwd (mirroring the - // reference adapter's `toDisplayPath`), while leaving location/diff paths raw. Use real fs tools - // and the absolute paths an editor supplies; presentation itself is args-only and lacks cwd. - function callUpdate(ctx: Context, sessionCwd: string | undefined, name: string, args: unknown): SessionNotification['update'] { - const presenter = new ToolPresenter(ctx.tools) - const out: SessionNotification['update'][] = [] - streamSessionEventUpdate( - SessionId('s1'), - evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name, arguments: JSON.stringify(args) }), - n => out.push(n.update), - presenter, - { enabled: false, cwd: sessionCwd }, - ) - return out[0]! - } - - it('read: an absolute path inside the workspace relativizes the TITLE; the location path stays absolute', async () => { - const ctx = await fsCtx() - const workspace = nativeAbsolute('/work/proj') - const file = nativeAbsolute('/work/proj', 'src', 'a.ts') - const update = callUpdate(ctx, workspace, 'read', { file_path: file, offset: 5 }) - expect(update).toMatchObject({ - title: `Read ${nativePath('src', 'a.ts')} (from line 5)`, - locations: [{ path: file, line: 5 }], - }) - await ctx.fiber.dispose() - }) - - it('edit: the diff TITLE relativizes; the diff/location paths stay absolute (the editor opens the real path)', async () => { - const ctx = await fsCtx() - const workspace = nativeAbsolute('/work/proj') - const file = nativeAbsolute('/work/proj', 'src', 'b.ts') - const update = callUpdate(ctx, workspace, 'edit', { file_path: file, old_string: 'x', new_string: 'y' }) - expect(update).toMatchObject({ - title: `Edit ${nativePath('src', 'b.ts')}`, - locations: [{ path: file }], - content: [{ type: 'diff', path: file, oldText: 'x', newText: 'y' }], - }) - await ctx.fiber.dispose() - }) - - it('a path OUTSIDE the workspace is left as-is (no `..` title)', async () => { - const ctx = await fsCtx() - const update = callUpdate(ctx, '/work/proj', 'read', { file_path: '/etc/passwd' }) - expect((update as { title: string }).title).toBe('Read /etc/passwd') - await ctx.fiber.dispose() - }) - - it('an in-workspace file whose relative form starts with `..` chars (a sibling name) still relativizes', async () => { - // `/work/proj/..cache/x` is inside the workspace — its relative form `..cache/x` begins - // with the chars `..` but is not a parent segment. Segment-aware guarding must relativize it, - // matching targets under `cwd + sep` in the reference adapter. - const ctx = await fsCtx() - const update = callUpdate(ctx, nativeAbsolute('/work/proj'), 'read', { file_path: nativeAbsolute('/work/proj', '..cache', 'x.ts') }) - expect((update as { title: string }).title).toBe(`Read ${nativePath('..cache', 'x.ts')}`) - await ctx.fiber.dispose() - }) - - it('no session cwd → the absolute title is left unchanged', async () => { - const ctx = await fsCtx() - const update = callUpdate(ctx, undefined, 'read', { file_path: '/work/proj/src/a.ts' }) - expect((update as { title: string }).title).toBe('Read /work/proj/src/a.ts') - await ctx.fiber.dispose() - }) - - it('a relative path is passed through unchanged (already display-friendly)', async () => { - const ctx = await fsCtx() - const update = callUpdate(ctx, nativeAbsolute('/work/proj'), 'read', { file_path: nativePath('src', 'a.ts') }) - expect((update as { title: string }).title).toBe(`Read ${nativePath('src', 'a.ts')}`) - await ctx.fiber.dispose() - }) -}) - -describe('agentOptions', () => { - it('includes only the fields present in config', () => { - expect(agentOptions({})).toEqual({}) - expect(agentOptions({ model: 'm' })).toEqual({ model: 'm' }) - expect(agentOptions({ provider: 'p', model: 'm' })).toEqual({ provider: 'p', model: 'm' }) - }) -}) diff --git a/packages/ui/acp/tests/turns.spec.ts b/packages/ui/acp/tests/turns.spec.ts deleted file mode 100644 index b3dcc22a55..0000000000 --- a/packages/ui/acp/tests/turns.spec.ts +++ /dev/null @@ -1,406 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' -import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' -import { - errorResponse, - makeBridgeHarness, - maxTokensResponse, - textResponse, - toolCallResponse, - type BridgeHarness, -} from './harness.ts' -import { SessionId } from '@deepseek-ai/dsh-session' - -/** Boilerplate: initialize + create one session, returning its id. */ -async function newSession(h: BridgeHarness, clientCapabilities: Record<string, unknown> = {}): Promise<string> { - await h.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities }) - const { sessionId } = await h.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - return sessionId -} - -describe('acp bridge — turn outcomes', () => { - let storageDir: string - let harness: BridgeHarness | undefined - - beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-test-')) }) - afterEach(async () => { - if (harness) await harness.dispose() - harness = undefined - await rm(storageDir, { recursive: true, force: true }) - }) - - it('maps a max-tokens turn to stopReason max_tokens', async () => { - harness = await makeBridgeHarness({ storageDir, script: [maxTokensResponse('cut off')] }) - const sessionId = await newSession(harness) - const res = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - expect(res.stopReason).toBe('max_tokens') - }) - - it('rejects the prompt RPC when a turn fails (no misleading end_turn)', async () => { - // ACP has no "error" stop reason; a failed turn must surface as a rejected - // session/prompt, not a normal end_turn that hides the failure from the - // client. The bridge rejects via the turn/end{error} log record. - harness = await makeBridgeHarness({ storageDir, script: [errorResponse('provider boom')] }) - const sessionId = await newSession(harness) - await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })) - .rejects.toThrow(/turn failed: provider boom/) - }) - - it('rejects an ordinary plugin turn failure through the same ACP boundary', async () => { - harness = await makeBridgeHarness({ storageDir, script: [textResponse('must not run')] }) - harness.ctx.on('agent/pre-step', () => { throw new Error('plugin pre-step failed') }) - const sessionId = await newSession(harness) - - await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })) - .rejects.toThrow(/turn failed: plugin pre-step failed/) - }) - - it('streams a tool call as tool_call then tool_call_update', async () => { - harness = await makeBridgeHarness({ - storageDir, - script: [toolCallResponse('c1', 'bash', { command: 'echo hi' }), textResponse('done')], - }) - harness.ctx.tools.register(defineContentToolFixture({ - name: 'bash', - description: 'run a command', - parameters: { command: { type: 'string' } }, - async execute() { return [{ type: 'text', text: 'hi\n' }] }, - })) - const sessionId = await newSession(harness) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'run it' }] }) - - const toolCalls = harness.updates.filter(u => u.sessionUpdate === 'tool_call') - const toolUpdates = harness.updates.filter(u => u.sessionUpdate === 'tool_call_update') - expect(toolCalls).toHaveLength(1) - // The inline stand-in declares no presentCall, so the generic fallback - // renders kind `other` (kinds are tool-owned; the bridge never sniffs the - // name — the REAL dsh-tool-bash test below covers the execute card). - expect(toolCalls[0]).toMatchObject({ toolCallId: 'c1', title: 'bash', kind: 'other', status: 'in_progress' }) - expect(toolUpdates).toHaveLength(1) - expect(toolUpdates[0]).toMatchObject({ toolCallId: 'c1', status: 'completed' }) - - // Ordering invariant: the tool_call precedes its tool_call_update. - const callIdx = harness.updates.findIndex(u => u.sessionUpdate === 'tool_call') - const updIdx = harness.updates.findIndex(u => u.sessionUpdate === 'tool_call_update') - expect(callIdx).toBeLessThan(updIdx) - }) - - it('the REAL bash tool drives the tool-call UI end-to-end: command title + description block + console output', async () => { - // Use the SHIPPING tool (dsh-tool-bash + dsh-bash-local), not an inline - // stand-in, so this verifies the actual presentCall/presentResult the editor - // sees (docs/testing.md "prefer the real implementation over a mock"). - // The mock MODEL still scripts the tool call (no real LLM needed), but the - // tool and executor are real: a real `echo` runs and its real output flows - // back through the bridge. - harness = await makeBridgeHarness({ - storageDir, - withBash: true, - script: [ - toolCallResponse('c1', 'bash', { command: 'echo hello', description: 'Print a greeting' }), - textResponse('done'), - ], - }) - const sessionId = await newSession(harness) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'greet' }] }) - - // presentCall: execute kind, title IS the command (an execute card hides - // rawInput, so the command is the title), the description rides as a content - // text block, the command is also rawInput for non-terminal UIs. - const call = harness.updates.find(u => u.sessionUpdate === 'tool_call') - expect(call).toMatchObject({ - toolCallId: 'c1', - title: 'echo hello', - kind: 'execute', - rawInput: 'echo hello', - status: 'in_progress', - }) - if (call?.sessionUpdate !== 'tool_call') throw new Error('expected a tool_call') - // Capability OFF: the description renders as the only content block (no terminal block). - expect(call.content).toEqual([{ type: 'content', content: { type: 'text', text: 'Print a greeting' } }]) - // presentResult: the REAL command output, wrapped in a fenced console block. - const update = harness.updates.find(u => u.sessionUpdate === 'tool_call_update') - expect(update?.sessionUpdate).toBe('tool_call_update') - if (update?.sessionUpdate !== 'tool_call_update') throw new Error('expected a tool_call_update') - expect(update).toMatchObject({ toolCallId: 'c1', status: 'completed' }) - const content = update.content as { content: { type: string; text: string } }[] - expect(content[0]?.content.text).toBe('```console\nhello\n```') - // Capability OFF (the default newSession): NO terminal _meta on either update. - expect((call as { _meta?: unknown })._meta).toBeUndefined() - expect((update as { _meta?: unknown })._meta).toBeUndefined() - }) - - it('with the terminal_output capability ON, a real bash call renders as a TERMINAL card (content + _meta + exit)', async () => { - // With terminal output advertised, a real bash call emits description then terminal content - // plus cwd metadata; its result uses terminal output/exit metadata and omits text that would - // clobber the card. - harness = await makeBridgeHarness({ - storageDir, - withBash: true, - script: [toolCallResponse('c1', 'bash', { command: 'echo hi', description: 'Greet' }), textResponse('done')], - }) - // Capability lives under clientCapabilities._meta.terminal_output. - const sessionId = await newSession(harness, { _meta: { terminal_output: true } }) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'greet' }] }) - - const call = harness.updates.find(u => u.sessionUpdate === 'tool_call') - if (call?.sessionUpdate !== 'tool_call') throw new Error('expected a tool_call') - // The description content block FIRST (renders above the card), then a - // terminal content block keyed by the callId; terminal_info carries the - // session cwd (the bridge fills it from the session header). - expect(call.content).toEqual([ - { type: 'content', content: { type: 'text', text: 'Greet' } }, - { type: 'terminal', terminalId: 'c1' }, - ]) - expect((call._meta as { terminal_info?: unknown }).terminal_info).toEqual({ terminal_id: 'c1', cwd: process.cwd() }) - - const update = harness.updates.find(u => u.sessionUpdate === 'tool_call_update') - if (update?.sessionUpdate !== 'tool_call_update') throw new Error('expected a tool_call_update') - // In terminal mode the text content is OMITTED (a tool_call_update.content - // REPLACES the call's content — it would clobber the terminal block). - expect(update.content).toBeUndefined() - // Output rides on _meta.terminal_output; the parsed exit on _meta.terminal_exit. - const meta = update._meta as { - terminal_output?: { terminal_id: string; data: string } - terminal_exit?: { terminal_id: string; exit_code?: number; signal?: string } - } - expect(meta.terminal_output).toEqual({ terminal_id: 'c1', data: 'hi\n' }) - expect(meta.terminal_exit).toEqual({ terminal_id: 'c1', exit_code: 0 }) - }) - - it('the terminal capability is snapshotted per-session: a later initialize cannot desync a call/result', async () => { - // Create the session with terminal support, then disable it connection-wide. The session's - // snapshot must keep call and result rendering consistent instead of re-reading changed state. - harness = await makeBridgeHarness({ - storageDir, - withBash: true, - script: [toolCallResponse('c1', 'bash', { command: 'echo hi', description: 'Greet' }), textResponse('done')], - }) - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: { _meta: { terminal_output: true } } }) - const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) - // A re-initialize that DROPS the capability after the session exists. - await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'greet' }] }) - - const call = harness.updates.find(u => u.sessionUpdate === 'tool_call') - if (call?.sessionUpdate !== 'tool_call') throw new Error('expected a tool_call') - // Still a terminal card (the session's snapshot, not the mutated connection cap). - expect((call._meta as { terminal_info?: unknown }).terminal_info).toBeDefined() - const update = harness.updates.find(u => u.sessionUpdate === 'tool_call_update') - if (update?.sessionUpdate !== 'tool_call_update') throw new Error('expected a tool_call_update') - // The result AGREES with the call: terminal output present, content omitted. - expect(update.content).toBeUndefined() - expect((update._meta as { terminal_output?: unknown }).terminal_output).toBeDefined() - }) - - it('a throwing tool presenter does not break the turn: the bridge falls back generically', async () => { - // A buggy tool whose presentCall throws must not fail the live turn — the - // bridge's presenter contains the throw (logging via its onError sink) and - // falls back to the generic title=name presentation. Exercises the real - // bridge wiring of the per-session presenter's error sink. - harness = await makeBridgeHarness({ - storageDir, - script: [toolCallResponse('c1', 'kaboom', { x: 1 }), textResponse('done')], - }) - harness.ctx.tools.register(defineContentToolFixture({ - name: 'kaboom', - description: 'explodes when presented', - parameters: { x: { type: 'number' } }, - async execute() { return [{ type: 'text', text: 'ok' }] }, - presentCall: () => { throw new Error('present boom') }, - })) - const sessionId = await newSession(harness) - const res = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - expect(res.stopReason).toBe('end_turn') // the turn completed despite the throw - - const call = harness.updates.find(u => u.sessionUpdate === 'tool_call') - // Generic fallback: title is the tool name, raw args as rawInput. - expect(call).toMatchObject({ toolCallId: 'c1', title: 'kaboom', kind: 'other', rawInput: { x: 1 } }) - const update = harness.updates.find(u => u.sessionUpdate === 'tool_call_update') - expect(update).toMatchObject({ toolCallId: 'c1', status: 'completed' }) - }) - - it('a failing tool yields a failed tool_call_update', async () => { - harness = await makeBridgeHarness({ - storageDir, - script: [toolCallResponse('c1', 'bash', { command: 'boom' }), textResponse('ok')], - }) - harness.ctx.tools.register(defineContentToolFixture({ - name: 'bash', - description: 'run a command', - parameters: { command: { type: 'string' } }, - async execute() { throw new Error('command failed') }, - })) - const sessionId = await newSession(harness) - await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'run it' }] }) - const failed = harness.updates.filter(u => u.sessionUpdate === 'tool_call_update' && u.status === 'failed') - expect(failed).toHaveLength(1) - }) - - it('settles successfully when an earlier turn/end observer throws', async () => { - // Session contains each post-commit observer failure, so a prepended peer - // cannot starve the bridge's live turn/end delivery. - harness = await makeBridgeHarness({ storageDir, script: [textResponse('answer')] }) - harness.ctx.on('session/event', (_s, event) => { - if (event.type === 'turn/end') throw new Error('peer listener boom') - }, { prepend: true }) - const sessionId = await newSession(harness) - const res = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - expect(res.stopReason).toBe('end_turn') - }) - - it('still rejects a failed turn when an earlier turn/end observer throws', async () => { - harness = await makeBridgeHarness({ storageDir, script: [errorResponse('starved boom')] }) - harness.ctx.on('session/event', (_s, event) => { - if (event.type === 'turn/end') throw new Error('peer listener boom') - }, { prepend: true }) - const sessionId = await newSession(harness) - await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })) - .rejects.toThrow(/turn failed: starved boom/) - }) - - it('captures and settles the owning turn when an earlier turn-start observer throws', async () => { - // Turn correlation still reaches the bridge after the throwing peer and - // captures inflight.turn via the live stream. A throwing turn/start listener - // Session contains post-commit callbacks independently. - // The model request and normal turn outcome therefore still occur. - harness = await makeBridgeHarness({ storageDir, script: [textResponse('answer')] }) - harness.ctx.on('session/event', (_s, event) => { - if (event.type === 'turn/start') throw new Error('peer listener boom on start') - }, { prepend: true }) - const sessionId = await newSession(harness) - const result = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - expect(result.stopReason).toBe('end_turn') - }) - - it('a between-turn injection does not settle the prompt early (message-trigger correlation)', async () => { - // A plugin injects context (a one-shot injection-triggered turn) right after - // the prompt is queued but before the prompt's own message turn runs. The - // bridge must NOT mistake the injection turn's turn/end for the prompt's — - // it correlates only to message-triggered turns. The prompt settles on its - // OWN turn with the real model answer. - harness = await makeBridgeHarness({ storageDir, script: [textResponse('real answer')] }) - const sessionId = await newSession(harness) - const agent = harness.ctx.agents.get(SessionId(sessionId))! - // On the queued prompt, synchronously inject a one-shot context turn (idle - // inject writes turn/start{injection} → user/message → turn/end). Fire - // once so it lands between install and the prompt turn. - let injected = false - harness.ctx.on('agent/inbox/enqueue', (subject) => { - if (subject === agent && !injected) { - injected = true - agent.inject([{ type: 'text', text: 'ctx note' }], { source: { kind: 'plugin', plugin: 'test' } }) - } - }) - const res = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - expect(res.stopReason).toBe('end_turn') - const text = harness.updates - .filter(u => u.sessionUpdate === 'agent_message_chunk') - .map(u => (u.content.type === 'text' ? u.content.text : '')) - .join('') - expect(text).toContain('real answer') - }) - - it('rejects a second prompt while one is in flight', async () => { - harness = await makeBridgeHarness({ storageDir, script: ['hang'] }) - const sessionId = await newSession(harness) - // Start the first prompt but do NOT await — it hangs in the model stream. - const first = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'one' }] }) - // Give the loop a tick to install the settle + start running. - await new Promise(r => setTimeout(r, 30)) - await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'two' }] })) - .rejects.toThrow(/already in flight/) - // Cancel to settle the first so the harness disposes cleanly. - await harness.client.cancel({ sessionId }) - await first - }) - - it('session/cancel aborts a running turn and settles the prompt as cancelled', async () => { - harness = await makeBridgeHarness({ storageDir, script: ['hang'] }) - const sessionId = await newSession(harness) - const promptDone = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - await new Promise(r => setTimeout(r, 30)) - await harness.client.cancel({ sessionId }) - const res = await promptDone - expect(res.stopReason).toBe('cancelled') - const agent = harness.ctx.agents.get(SessionId(sessionId))! - await agent.whenIdle() - const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end') - expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' }) - }) - - it('cancel right after prompt settles cancelled and leaves the agent idle, no leaked turn', async () => { - // JSON-RPC timing normally makes this a running mid-step cancellation; pre-step dropping is - // covered in agent-loop. Here the prompt must settle cancelled, return idle, and clear queued - // work so the scripted second response cannot leak into another turn. - harness = await makeBridgeHarness({ storageDir, script: [textResponse('answer'), textResponse('leaked')] }) - const sessionId = await newSession(harness) - const promptDone = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - await harness.client.cancel({ sessionId }) - const res = await promptDone - expect(res.stopReason).toBe('cancelled') - const agent = harness.ctx.agents.get(SessionId(sessionId))! - await agent.whenIdle() - const turnStarts = agent.session.events.filter(e => e.type === 'turn/start').length - expect(turnStarts).toBeLessThanOrEqual(1) - }) - - it('idle session/cancel then session/prompt runs the prompt (no intervening whenIdle)', async () => { - // The bridge settles cancel synchronously, so exercise the production cancel→prompt race with - // no `whenIdle()`. An idle cancel must not mark or drop the following prompt. - harness = await makeBridgeHarness({ storageDir, script: [textResponse('real answer')] }) - const sessionId = await newSession(harness) - // Cancel while idle (no prompt in flight) — a no-op. - await harness.client.cancel({ sessionId }) - // Immediately prompt, no whenIdle() between. - const res = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }) - expect(res.stopReason).toBe('end_turn') - const text = harness.updates - .filter(u => u.sessionUpdate === 'agent_message_chunk') - .map(u => (u.content.type === 'text' ? u.content.text : '')) - .join('') - expect(text).toContain('real answer') - }) - - it('mid-stream cancel then an IMMEDIATE next prompt runs (no intervening whenIdle)', async () => { - // Cancel a running turn and immediately send another prompt without awaiting quiescence. The - // cancellation marker belongs only to the first turn and must not drop the next request. - harness = await makeBridgeHarness({ storageDir, script: ['hang', textResponse('next answer')] }) - const sessionId = await newSession(harness) - const a = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'A' }] }) - await new Promise(r => setTimeout(r, 30)) - await harness.client.cancel({ sessionId }) - expect((await a).stopReason).toBe('cancelled') - // Immediately — no whenIdle() — send the next prompt. - const b = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'B' }] }) - expect(b.stopReason).toBe('end_turn') - const text = harness.updates - .filter(u => u.sessionUpdate === 'agent_message_chunk') - .map(u => (u.content.type === 'text' ? u.content.text : '')) - .join('') - expect(text).toContain('next answer') - }) - - it('a cancelled turn\'s late turn/end does not settle the NEXT prompt', async () => { - // Cancellation frees A's slot before its aborted turn/end is appended. Send B in that window; - // correlation by turn number must prevent A's late closer from settling B as cancelled. - harness = await makeBridgeHarness({ storageDir, script: ['hang', textResponse('B answer')] }) - const sessionId = await newSession(harness) - - const a = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'A' }] }) - await new Promise(r => setTimeout(r, 30)) // let A start running (turn 1) - await harness.client.cancel({ sessionId }) - expect((await a).stopReason).toBe('cancelled') - - // B owns the later turn and must complete on its own turn/end. - const b = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'B' }] }) - expect(b.stopReason).toBe('end_turn') - const text = harness.updates - .filter(u => u.sessionUpdate === 'agent_message_chunk') - .map(u => (u.content.type === 'text' ? u.content.text : '')) - .join('') - expect(text).toContain('B answer') - }) -}) diff --git a/packages/ui/acp/tsconfig.json b/packages/ui/acp/tsconfig.json deleted file mode 100644 index 409928f136..0000000000 --- a/packages/ui/acp/tsconfig.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], - "references": [ - { - "path": "../../../vendor/cosmokit" - }, - { - "path": "../../../vendor/cordis" - }, - { - "path": "../../../vendor/schemastery" - }, - { - "path": "../../llm/llm" - }, - { - "path": "../../llm/llm-retry" - }, - { - "path": "../../core/session" - }, - { - "path": "../../context/session-reference" - }, - { - "path": "../../session-query/session-query" - }, - { - "path": "../../session-title/session-title" - }, - { - "path": "../../core/agent" - }, - { - "path": "../../core/tools" - }, - { - "path": "../commands" - }, - { - "path": "../user-interaction" - }, - { - "path": "../../plan/plan-mode" - }, - { - "path": "../../session-persistence/session-persistence" - }, - { - "path": "../user-approval" - }, - { - "path": "../permission" - }, - { - "path": "../../sandbox/sandbox" - }, - { - "path": "../../bash/bash" - }, - { - "path": "../../support/invariants" - } - ] -} diff --git a/packages/ui/commands/README.md b/packages/ui/commands/README.md index 0c9eb04267..e32513a563 100644 --- a/packages/ui/commands/README.md +++ b/packages/ui/commands/README.md @@ -1,10 +1,10 @@ # @deepseek-ai/dsh-commands -Plugin-owned human-command registry shared by the TUI and ACP adapters. The [plugin command registration Agent Note](../../../.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md) owns the boundary and protocol mapping. +Plugin-owned human-command registry consumed by interactive UI adapters. The [plugin command registration Agent Note](../../../.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md) owns the boundary and dispatch contract. ## Service contract -`ctx.commands.register(definition)` registers one lowercase command name, description, optional ACP-compatible unstructured-input hint, and abortable handler. A registered command is available to every composed command adapter; a plugin that is incompatible with a deployment does not register there. A plain-context registration is global. A command-producing plugin mounted beneath `agent.ctx` declares its own `commands` injection and creates an exact agent-scoped definition; it shadows a global definition with the same name. This child-injection shape preserves the agent scope without making the core agent loop depend on a UI service. Duplicate names within one layer fail during registration. Every disposer is the exact Cordis effect disposer, and registration or removal notifies every `commands/change` observer so live adapters can refresh discovery; observer failures are logged and cannot veto the registry mutation or starve later observers. +`ctx.commands.register(definition)` registers one lowercase command name, description, optional unstructured-input hint, and abortable handler. A registered command is available to every composed command adapter; a plugin that is incompatible with a deployment does not register there. A plain-context registration is global. A command-producing plugin mounted beneath `agent.ctx` declares its own `commands` injection and creates an exact agent-scoped definition; it shadows a global definition with the same name. This child-injection shape preserves the agent scope without making the core agent loop depend on a UI service. Duplicate names within one layer fail during registration. Every disposer is the exact Cordis effect disposer, and registration or removal notifies every `commands/change` observer so live adapters can refresh discovery; observer failures are logged and cannot veto the registry mutation or starve later observers. `list(agent)` returns immutable, name-sorted descriptors after scoped shadowing. `find(agent, name)` returns the corresponding definition. `execute(agent, line, signal)` uses `parseCommand()` and runs only a known command, returning `undefined` for invalid syntax or unknown names. @@ -14,7 +14,7 @@ Handlers return `success` or `error` plus optional UI text. Results are rendered ## Composition -The terminal and ACP app bundles mount this service with their consuming front door; the UI-less agent spine does not. Custom compositions that use `dsh-tui`, `dsh-acp`, or a command producer mount `@deepseek-ai/dsh-commands` explicitly. +The terminal app bundle mounts this service with `dsh-tui`; the UI-less agent spine and ACP automation app do not. Custom interactive compositions and command producers mount `@deepseek-ai/dsh-commands` explicitly. ## Model Experience @@ -34,6 +34,6 @@ Registry metadata, command input, and direct output never enter a model request ## Known Limitations and Deferred Work -- **Only unstructured text input** — the descriptor intentionally matches ACP's current unstructured command input; forms, completion schemas, and typed arguments remain command-owned parsing concerns. +- **Only unstructured text input** — forms, completion schemas, and typed arguments remain command-owned parsing concerns. - **No persisted command output** — adapters display results live, but the generic registry does not add them to the session log or reconstruct them after reconnect. - **Cooperative side-effect cancellation** — dispatch stops awaiting on abort; handlers must honor the signal to stop work that has already escaped into external systems. diff --git a/packages/ui/commands/src/index.ts b/packages/ui/commands/src/index.ts index 56f88a9f20..ba8a519e4e 100644 --- a/packages/ui/commands/src/index.ts +++ b/packages/ui/commands/src/index.ts @@ -12,7 +12,7 @@ export const name = 'commands' const COMMAND_NAME = /^[a-z][a-z0-9_-]*$/u -/** Immutable command input metadata compatible with ACP unstructured input. */ +/** Immutable metadata for a command's optional unstructured input. */ export interface CommandInputDescriptor { /** Placeholder shown before the user supplies free-form input. */ readonly hint: string diff --git a/packages/ui/permission/README.md b/packages/ui/permission/README.md index 12196d89a0..cdf6e0f435 100644 --- a/packages/ui/permission/README.md +++ b/packages/ui/permission/README.md @@ -1,10 +1,10 @@ # @deepseek-ai/dsh-permission -User-facing permission presets through `ctx.permission` ([`PermissionService`](src/index.ts)). Each configured name bundles `sandbox/mode` with `approval/policy`; the defaults are `workspace-write` (`workspace-write` + `ask`) and `danger-full-access` (`danger-full-access` + `never`). The ACP bridge exposes them as one `Permissions` select, while sandbox execution and approval continue to consume their own knobs. +User-facing permission presets through `ctx.permission` ([`PermissionService`](src/index.ts)). Each configured name bundles `sandbox/mode` with `approval/policy`; the defaults are `workspace-write` (`workspace-write` + `ask`) and `danger-full-access` (`danger-full-access` + `never`). UI adapters may expose the table as one selector, while sandbox execution and approval continue to consume their own knobs. `set(session, name)` records a changed selection in a log-only `permission/preset` event, then calls each knob's setter only when its effective value changes. The selection event precedes the knob events and preserves user intent when presets share a bundle; a net-zero selection appends nothing. `current(events)` prefers a still-matching recorded selection, then the first matching table entry, and otherwise returns `custom`. Clients may display `custom` as the current value, but cannot select it. -The service requires a confining `ctx.bash` executor and `ctx.approval`. A table entry named `custom` throws at load; composition defaults outside the table instead make a zero-event session derive `custom`. See the [acp-agent composition](../../../examples/acp-agent/) and [sandbox switching design](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md). +The service requires a confining `ctx.bash` executor and `ctx.approval`. A table entry named `custom` throws at load; composition defaults outside the table instead make a zero-event session derive `custom`. See the [sandbox switching design](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md). ## Model Experience @@ -16,6 +16,7 @@ No direct invalidation; the named consumer owns any request-prefix changes. ## Known Limitations and Deferred Work +- **No shipped composition currently mounts the service** — the ACP bridge was its only selector before [ACP became automation-only](../../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md); the preset table is kept for the interactive front door that next exposes a runtime policy switch. - **Only two mechanism knobs are bundled** — presets select sandbox mode and approval policy; an agent/profile choice is not part of `PresetSpec` yet. - **`custom` is derived-only** — callers can switch away from an unmatched knob combination but cannot target or persist a named custom preset through this service. - **The preset table is process-level** — configuration is fixed for the plugin lifetime; changing available presets requires reloading the plugin. diff --git a/packages/ui/permission/src/index.ts b/packages/ui/permission/src/index.ts index a92f3bc221..d44dff3df4 100644 --- a/packages/ui/permission/src/index.ts +++ b/packages/ui/permission/src/index.ts @@ -51,7 +51,7 @@ export interface PresetSpec { /** The select-option shape a presentation layer advertises for one preset (or for the derived `custom` state). */ export interface PresetOption { - /** The machine value (`session/set_config_option` vocabulary): the table key, or `custom`. */ + /** Stable option value: the table key, or `custom`. */ value: string /** The display label. */ name: string diff --git a/packages/ui/tui/tests/tui.spec.ts b/packages/ui/tui/tests/tui.spec.ts index 2c4fd21650..0fea8b2750 100644 --- a/packages/ui/tui/tests/tui.spec.ts +++ b/packages/ui/tui/tests/tui.spec.ts @@ -1877,7 +1877,7 @@ describe('pi-tui chat lifecycle and transcript', () => { await mkdir(join(cwd, 'docs'), { recursive: true }) await writeFile(join(cwd, 'src', 'source-file.ts'), 'export const source = true\n') await writeFile(join(cwd, 'docs', 'design notes.md'), '# Design\n') - await writeFile(join(cwd, 'unsafe\nfile.ts'), 'unsafe name\n') + await writeFile(join(cwd, 'unsafe\u007ffile.ts'), 'unsafe name\n') const result = await setup({ cwd, tools: { diff --git a/packages/ui/user-approval/README.md b/packages/ui/user-approval/README.md index 77b368fac3..f61e56b535 100644 --- a/packages/ui/user-approval/README.md +++ b/packages/ui/user-approval/README.md @@ -4,11 +4,11 @@ Channel-neutral one-shot approval seam. `ctx.approval.request(req)` returns `all Each request must belong to an open agent turn. The service appends a paired `approval/asked` and `approval/decided` audit record, while the model sees only the resulting logged tool outcome. An aborted request resolves `cancelled`; an audit append that fails before commit rejects rather than returning an unlogged decision. -Answerers are `approval/request` waterfall listeners. Return an outcome to answer for an owned agent or call `next()` to delegate. Agent-scoped listeners receive only that agent's requests; compose one terminal answerer per deployment because sibling listener order is not a policy priority mechanism. The ACP bridge is the shipped human answerer. +Answerers are `approval/request` waterfall listeners. Return an outcome to answer for an owned agent or call `next()` to delegate. Agent-scoped listeners receive only that agent's requests; compose one terminal answerer per deployment because sibling listener order is not a policy priority mechanism. The ACP automation bridge supplies one-shot machine decisions for sessions it owns. `ApprovalPolicy` is `'ask'` or `'never'`. The effective value is the last `approval/policy` event, falling back to config; `setApprovalPolicy()` is the write path. `'never'` rejects before interactive dispatch and is the only policy stated in the prompt. Switches produce at most one coalesced notice, attributed to the user when the override follows the last `request/header` and to operator/config otherwise. -The tools pipeline routes `ask` decisions through this seam and fails closed when it is absent; the sandboxed bash tool also uses it for escalated retries. The ACP bridge is the shipped human answerer for calls it owns. Audit events remain log-only, so the model sees only the asking consumer's result. See the [approval-seam Agent Note](../../../.agents/notes/implemented/feature/2026-07-06-approval-seam.md) and [sandbox Agent Note](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md). +The tools pipeline routes `ask` decisions through this seam and fails closed when it is absent; the sandboxed bash tool also uses it for escalated retries. The ACP automation bridge answers calls for its own agents through the client's machine policy. Audit events remain log-only, so the model sees only the asking consumer's result. See the [approval-seam Agent Note](../../../.agents/notes/implemented/feature/2026-07-06-approval-seam.md) and [sandbox Agent Note](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md). ## Model Experience @@ -57,5 +57,5 @@ Append-only; newly visible content follows the reusable request prefix and does - **Requests are valid only inside an open turn** — an idle or between-turn caller throws before auditing; a durable out-of-turn approval workflow is deferred. - **Only one-shot grants exist** — the outcome vocabulary has `allowed-once` but no `allow-always`, remembered rule, revocation, or grant store; session policy is only `ask` / `never`. -- **The request carries no tool arguments** — a UI must correlate `callId` with an already rendered tool call, and a call-less request cannot be presented by the shipped ACP answerer. +- **The request carries no tool arguments** — an answerer sees the tool name, reason, and optional call id; the ACP machine channel requires a call id and delegates requests without one. - **No built-in answerer** — headless or incompletely composed deployments resolve `unavailable` and fail closed; the service itself never prompts a human. diff --git a/packages/ui/user-interaction/README.md b/packages/ui/user-interaction/README.md index f0e14b81bd..6e74d743c2 100644 --- a/packages/ui/user-interaction/README.md +++ b/packages/ui/user-interaction/README.md @@ -21,7 +21,7 @@ When an answer includes `custom`, `selected` is empty; custom text is an overrid ## Role -This is the interface package. Model-facing consumers such as `@deepseek-ai/dsh-tool-ask-user` depend on this seam; the interactive `dsh-tui` and structured `dsh-acp` front doors provide the provider. The loop stays unchanged: a tool call awaits a promise, and the tool result resumes the normal agent loop. +This is the interface package. Model-facing consumers such as `@deepseek-ai/dsh-tool-ask-user` depend on this seam; `dsh-tui` and the host runtime provide interactive implementations. The loop stays unchanged: a tool call awaits a promise, and the tool result resumes the normal agent loop. ## Model Experience diff --git a/packages/workspace/README.md b/packages/workspace/README.md new file mode 100644 index 0000000000..4658080be9 --- /dev/null +++ b/packages/workspace/README.md @@ -0,0 +1,9 @@ +# workspace/ — the workspace entity + +The workspace family owns the persistent workspace concept: a directory the user works in, with a title and the ordered list of sessions that belong to it. Design record: [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md). + +| Package | Role | ctx key | +|---|---|---| +| `workspace/` | `WorkspaceRegistry` service over the storage domain form: realpath-unique paths, session-ownership accounting, entity cache | `ctx.workspace` | + +Ownership truth lives in the workspace record's `sessionIds` (ordered), never derived from session cwd; `attachSession` verifies the session header's cwd resolves to the workspace path, so one session structurally belongs to at most one workspace. Deletion (workspace and session cascade) is deliberately absent this phase and ships with the session-side primitives. diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md new file mode 100644 index 0000000000..a32528517f --- /dev/null +++ b/packages/workspace/workspace/README.md @@ -0,0 +1,37 @@ +# @deepseek-ai/dsh-workspace + +Workspace entity registry (`ctx.workspace`) for the DeepSeek Harness: durable workspace records — a stable `WorkspaceId`, a canonical directory path, a display title, and the ordered account of owned sessions — stored through the domain data form (`workspaceDomainSpec`, table `workspaces`). Consumers see the `Workspace` interface only; the entity implementation stays package-private. + +Design rationale, the path/uniqueness canon, and the consistency rules live in the [Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md). + +## Shape + +- `ctx.workspace.create(path, title?)` — canonicalizes `path` via `fs.realpath` (trailing slashes, `..`, symlinks), rejects a nonexistent path (the original `ENOENT`), a path resolving to anything but a directory, and a canonical path another workspace already owns. Title defaults to `basename(path)`. +- `ctx.workspace.get(id)` / `list()` / `resolveByPath(path)` — cache-served lookups; `resolveByPath` is async because it runs the same `realpath` canon first. +- `Workspace.attachSession(id)` — idempotent; validates that the session's stored header `cwd`, canonicalized the same way, equals the workspace path. A missing persistence service, unknown session, absent or unresolvable `cwd`, or mismatch rejects without writing (what cannot be validated is not recorded). `detachSession` removes from the account only, never touching the session's own log. +- `Workspace.sessionIds` — the ordered ownership account (array order is display order). Accounted ids whose session no longer exists are filtered from the projection and pruned durably on the next mutation. A medium accounting one session under two workspaces, or claiming one canonical path from two records, rejects at startup (external edit — the write side makes both unreachable). Attach/detach idempotence is decided on the domain write chain, so unawaited concurrent calls settle in call order. +- `Workspace.status()` — uncached directory check, `'ok' | 'missing-dir'`; a missing directory never mutates the record. + +Session persistence is an optional peer resolved with `ctx.get`: absent, attach rejects and projections serve the account unfiltered. + +## Model Experience + +### Workspace records and session accounts + +#### What the model sees + +Nothing. `ctx.workspace` serves workspace records to host-side consumers only: the package registers no tools, injects no prompts, and writes no session events, so no request field ever carries this package's data. + +#### Token effect + +Zero direct tokens on every request. + +#### KV Cache effect + +Independent of live requests: the package never touches a request prefix, so it cannot invalidate provider cache reuse. + +## Known Limitations and Deferred Work + +- No delete entry point in this phase — workspace deletion ships as one complete semantic together with the session-delete primitive and cascade orchestration (future-work section of the Agent Note); a half "drop the record, keep the sessions" operation is deliberately not exposed. +- No RPC surface or GUI wiring yet; the record schema is the direct source of the next phase's wire projection. +- The known-session view refreshes at startup and on attach validation; a session deleted by an external process during this one is filtered only after the next refresh. diff --git a/packages/workspace/workspace/package.json b/packages/workspace/workspace/package.json new file mode 100644 index 0000000000..6bfab64773 --- /dev/null +++ b/packages/workspace/workspace/package.json @@ -0,0 +1,50 @@ +{ + "name": "@deepseek-ai/dsh-workspace", + "description": "Workspace entity registry (ctx.workspace): durable workspace records with validated session attachment over the domain data form for the DeepSeek Harness", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-brand": "^0.0.1", + "@deepseek-ai/dsh-storage-domain": "^0.0.1", + "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-session": "^0.0.1", + "@deepseek-ai/dsh-session-persistence": "^0.0.1", + "@deepseek-ai/dsh-storage": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "dependencies": { + "zod": "^4.4.3" + }, + "devDependencies": { + "@deepseek-ai/dsh-brand": "workspace:^", + "@deepseek-ai/dsh-storage-domain": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-storage": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/workspace/workspace/src/entity.ts b/packages/workspace/workspace/src/entity.ts new file mode 100644 index 0000000000..6ce2c01a00 --- /dev/null +++ b/packages/workspace/workspace/src/entity.ts @@ -0,0 +1,169 @@ +/** + * Package-private workspace entity: the single {@link Workspace} + * implementation. Holds a record snapshot that is swapped in place after each + * durable mutation; every write funnels through the private `mutate` so + * `updatedAt` stamping and dead-account pruning happen exactly once. + * Not re-exported from the package entrypoint — consumers see only the + * `Workspace` interface. + * @module @deepseek-ai/dsh-workspace/src/entity + */ + +import { stat } from 'node:fs/promises' +import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import type { KvTable } from '@deepseek-ai/dsh-storage-domain' +import type { WorkspaceRecord } from './spec.ts' +import type { Workspace, WorkspaceId } from './types.ts' +import { realpathNormalize } from './paths.ts' + +/** + * The registry-owned machinery an entity mutates through. Entities never see + * the registry itself — only the open table, the known-session view backing + * the `sessionIds` projection, and header reads for attach validation. + */ +export interface WorkspaceEntityHost { + /** + * Resolve the open `workspaces` table. + * @returns the table; throws while the registry has not started yet. + */ + table(): KvTable<WorkspaceId, WorkspaceRecord> + + /** + * Synchronous view of the session ids known to exist in session + * persistence. + * @returns the id set, or `undefined` when persistence has been absent so + * far (membership cannot be verified, so projections serve the account + * unfiltered). + */ + knownSessionIds(): ReadonlySet<string> | undefined + + /** + * Read one stored session header for attach validation. + * @param id - The session whose header to read. + * @returns the header; rejects when session persistence is absent or holds + * no session with this id. + */ + readSessionHeader(id: SessionId): Promise<SessionHeader> +} + +/** Chain-slot abort sentinel thrown by the update fn when the record needs no change; only `mutate` observes it. */ +const unchangedSentinel = new Error('workspace record unchanged (internal sentinel)') + +/** The single {@link Workspace} implementation; constructed only by the registry. */ +export class WorkspaceEntity implements Workspace { + private record: WorkspaceRecord + + /** + * @param host - Registry-owned table, known-session view, and header reads. + * @param id - The record's stable id. + * @param record - The validated record snapshot loaded or just written. + */ + constructor( + private readonly host: WorkspaceEntityHost, + readonly id: WorkspaceId, + record: WorkspaceRecord, + ) { + this.record = record + } + + get path(): string { + return this.record.path + } + + get title(): string { + return this.record.title + } + + get sessionIds(): readonly SessionId[] { + const known = this.host.knownSessionIds() + if (known === undefined) return this.record.sessionIds + return this.record.sessionIds.filter(id => known.has(id)) + } + + async setTitle(title: string): Promise<void> { + await this.mutate(record => ({ ...record, title })) + } + + async attachSession(sessionId: SessionId): Promise<void> { + // Validation is skipped when the settled snapshot already accounts the + // id: the cwd fact was checked when it first attached and both inputs + // (stored header cwd, workspace path) are immutable. Membership itself is + // decided on the write chain inside `mutate`, never on this snapshot. + if (!this.record.sessionIds.includes(sessionId)) { + const header = await this.host.readSessionHeader(sessionId) + if (header.cwd === undefined) { + throw new Error( + `cannot attach session '${sessionId}' to workspace '${this.record.path}': ` + + 'its stored header carries no cwd to validate against', + ) + } + let cwd: string + try { + cwd = await realpathNormalize(header.cwd) + } catch (error) { + throw new Error( + `cannot attach session '${sessionId}' to workspace '${this.record.path}': ` + + `its cwd '${header.cwd}' does not resolve, so it cannot be validated`, + { cause: error }, + ) + } + if (cwd !== this.record.path) { + throw new Error( + `cannot attach session '${sessionId}' to workspace '${this.record.path}': ` + + `its cwd resolves to '${cwd}'`, + ) + } + } + await this.mutate(record => record.sessionIds.includes(sessionId) + ? record + : { ...record, sessionIds: [...record.sessionIds, sessionId] }) + } + + async detachSession(sessionId: SessionId): Promise<void> { + await this.mutate(record => record.sessionIds.includes(sessionId) + ? { ...record, sessionIds: record.sessionIds.filter(id => id !== sessionId) } + : record) + } + + async status(): Promise<'ok' | 'missing-dir'> { + try { + return (await stat(this.record.path)).isDirectory() ? 'ok' : 'missing-dir' + } catch { + // Any stat failure (ENOENT, dangling parent, permission loss) means the + // directory is not usable right now; the record itself never mutates. + return 'missing-dir' + } + } + + /** + * The single write path: run `fn` on the domain write chain via + * `table.update`, stamping `updatedAt` and pruning accounted ids whose + * session no longer exists (consistency rule: dead ids are dropped on the + * next mutation, whatever that mutation is), then swap the snapshot. + * + * `fn` sees the value current at its chain slot, so membership decisions + * (attach/detach idempotence) are race-free against queued writes; a fn + * signalling no change by returning `current` verbatim aborts the slot + * through the sentinel when pruning also finds nothing, so a no-op neither + * rewrites the medium nor emits a change event. + */ + private async mutate(fn: (record: WorkspaceRecord) => WorkspaceRecord): Promise<void> { + const known = this.host.knownSessionIds() + let next: WorkspaceRecord + try { + next = await this.host.table().update(this.id, (current) => { + const changed = fn(current) + const sessionIds = known === undefined + ? changed.sessionIds + : changed.sessionIds.filter(id => known.has(id)) + if (changed === current && sessionIds.length === current.sessionIds.length) { + throw unchangedSentinel + } + return { ...changed, sessionIds, updatedAt: new Date().toISOString() } + }) + } catch (error) { + if (error === unchangedSentinel) return + throw error + } + this.record = next + } +} diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts new file mode 100644 index 0000000000..3754a9917a --- /dev/null +++ b/packages/workspace/workspace/src/index.ts @@ -0,0 +1,231 @@ +/** + * Workspace entity registry (`ctx.workspace`): durable workspace records over + * the domain data form, with session attachment validated against stored + * session headers. This package owns the `WorkspaceId` brand and the + * `workspace` domain; consumers see the {@link Workspace} interface only. + * @module @deepseek-ai/dsh-workspace + */ + +import { randomUUID } from 'node:crypto' +import { stat } from 'node:fs/promises' +import { basename } from 'node:path' +import { Context, Service } from 'cordis' +import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +// Type-only: merges `sessionPersistence` into the Context service map for the +// optional `ctx.get` lookups below. +import type {} from '@deepseek-ai/dsh-session-persistence' +import type { KvTable } from '@deepseek-ai/dsh-storage-domain' +import { workspaceDomainSpec } from './spec.ts' +import type { WorkspaceRecord } from './spec.ts' +import { WorkspaceEntity } from './entity.ts' +import type { WorkspaceEntityHost } from './entity.ts' +import { realpathNormalize } from './paths.ts' +import type { Workspace, WorkspaceId as WorkspaceIdBrand } from './types.ts' + +export type { Workspace } from './types.ts' +export { workspaceRecord, workspaceDomainSpec } from './spec.ts' +export type { WorkspaceRecord } from './spec.ts' +export { realpathNormalize } from './paths.ts' + +/** Identifies one workspace record (see `src/types.ts` for the brand rationale). */ +export type WorkspaceId = WorkspaceIdBrand + +/** + * Brand a string as a {@link WorkspaceId}. + * @param id - the raw workspace id string. + * @returns the same string, branded (a compile-time cast — no runtime cost). + */ +export function WorkspaceId(id: string): WorkspaceId { + return id as WorkspaceId +} + +declare module 'cordis' { + interface Context { + workspace: WorkspaceRegistry + } +} + +/** + * The workspace registry service. Opens the `workspace` domain at startup, + * rebuilds one entity per stored record, and serves entities from an + * in-memory cache keyed by id. Session persistence is an OPTIONAL peer + * (resolved via `ctx.get`, never injected): while it is absent, session + * attachment rejects (what cannot be validated is not recorded) and + * `sessionIds` projections serve the account unfiltered. + * + * There is deliberately no delete entry point in this phase: workspace + * deletion ships as one complete semantic together with the session-cascade + * primitives (future work in the owning Agent Note). + */ +export class WorkspaceRegistry extends Service { + static inject = ['storage'] + + private table?: KvTable<WorkspaceId, WorkspaceRecord> + private readonly entities = new Map<WorkspaceId, WorkspaceEntity>() + /** + * Session ids known to exist in session persistence; `undefined` until the + * first successful listing. Refreshed at startup and on every attach + * validation — within one process sessions are only ever added (this phase + * has no delete primitive), so the set can only lag by missing very recent + * sessions, never by holding dead ones from this process's lifetime. + */ + private known?: Set<string> + + private readonly host: WorkspaceEntityHost = { + table: () => this.requireTable(), + knownSessionIds: () => this.known, + readSessionHeader: id => this.readSessionHeader(id), + } + + constructor(ctx: Context) { + super(ctx, 'workspace') + } + + /** Open the domain and rebuild the entity cache before the service is published as active. */ + protected async [Service.init](): Promise<void> { + const domain = await this.ctx.storage.domain.open(workspaceDomainSpec) + // This registry owns the domain handle it opened: closing on fiber + // disposal frees the domain name, so a re-plugged registry can reopen it. + this.ctx.effect(() => () => domain.close(), 'workspace.domainClose') + this.table = domain.table('workspaces') + const persistence = this.ctx.get('sessionPersistence') + if (persistence !== undefined) { + this.known = new Set<string>((await persistence.list()).map(header => header.id)) + } + // Rebuild entities, rejecting states the write side makes structurally + // impossible (an external medium edit is the only way in, and hiding it + // would silently pick a winner): one session accounted under two + // workspaces, or two records claiming one canonical path (plain string + // equality — stored paths are already canonical, so no realpath here). + const accounted = new Map<string, WorkspaceId>() + const paths = new Map<string, WorkspaceId>() + for (const [id, record] of this.table.entries()) { + const pathHolder = paths.get(record.path) + if (pathHolder !== undefined) { + throw new Error( + `workspace domain is inconsistent: path '${record.path}' is claimed ` + + `by both workspace '${pathHolder}' and workspace '${id}'`, + ) + } + paths.set(record.path, id) + for (const sessionId of record.sessionIds) { + const holder = accounted.get(sessionId) + if (holder !== undefined) { + throw new Error( + `workspace domain is inconsistent: session '${sessionId}' is accounted ` + + `by both workspace '${holder}' and workspace '${id}'`, + ) + } + accounted.set(sessionId, id) + } + this.entities.set(id, new WorkspaceEntity(this.host, id, record)) + } + } + + /** + * Create a workspace over an existing directory. The path is canonicalized + * through `fs.realpath` first — a nonexistent path rejects with the + * original `ENOENT`, a path resolving to anything but a directory rejects, + * and a canonical path already owned by another workspace (including a + * symlink resolving to it) rejects. + * @param path - Directory the workspace points at; canonicalized before storing. + * @param title - Display title; defaults to `basename` of the canonical path. + * @returns the created workspace after durability. + */ + async create(path: string, title?: string): Promise<Workspace> { + const table = this.requireTable() + const canonical = await realpathNormalize(path) + if (!(await stat(canonical)).isDirectory()) { + throw new Error(`cannot create a workspace at '${canonical}': path is not a directory`) + } + for (const entity of this.entities.values()) { + if (entity.path === canonical) { + throw new Error(`a workspace for '${canonical}' already exists ('${entity.id}')`) + } + } + const id = WorkspaceId(randomUUID()) + const now = new Date().toISOString() + const record: WorkspaceRecord = { + path: canonical, + title: title ?? basename(canonical), + sessionIds: [], + createdAt: now, + updatedAt: now, + } + const entity = new WorkspaceEntity(this.host, id, record) + // Cache before the durable put: a concurrent same-path create fails the + // scan above, and the entity already exists when `domain/changed` fires. + this.entities.set(id, entity) + try { + await table.put(id, record) + } catch (error) { + this.entities.delete(id) + throw error + } + return entity + } + + /** + * Look up a workspace by id. + * @param id - The workspace id. + * @returns the workspace, or `undefined` when unknown. + */ + get(id: WorkspaceId): Workspace | undefined { + return this.entities.get(id) + } + + /** + * Snapshot of all workspaces, in load-then-creation order. + * @returns a fresh array of the cached entities. + */ + list(): Workspace[] { + return [...this.entities.values()] + } + + /** + * Resolve a workspace by directory path, through the same `fs.realpath` + * canon as {@link create} (hence async). A path that does not exist rejects + * with the original error — a missing directory has no canonical form to + * compare (a workspace whose recorded directory vanished is only reachable + * by id; see `Workspace.status`). + * @param path - Directory path in any spelling (symlinks, `..`, trailing slash). + * @returns the owning workspace, or `undefined` when none matches. + */ + async resolveByPath(path: string): Promise<Workspace | undefined> { + const canonical = await realpathNormalize(path) + for (const entity of this.entities.values()) { + if (entity.path === canonical) return entity + } + return undefined + } + + private requireTable(): KvTable<WorkspaceId, WorkspaceRecord> { + if (this.table === undefined) { + throw new Error('workspace registry is not started yet') + } + return this.table + } + + /** + * Read one stored session header for attach validation, refreshing the + * known-session view from the same listing. Rejects when session + * persistence is absent or holds no session with this id. + */ + private async readSessionHeader(id: SessionId): Promise<SessionHeader> { + const persistence = this.ctx.get('sessionPersistence') + if (persistence === undefined) { + throw new Error( + `cannot validate session '${id}': no session persistence service is available`, + ) + } + const headers = await persistence.list() + this.known = new Set<string>(headers.map(header => header.id)) + const header = headers.find(candidate => candidate.id === id) + if (header === undefined) { + throw new Error(`cannot validate session '${id}': session persistence holds no such session`) + } + return header + } +} + +export default WorkspaceRegistry diff --git a/packages/workspace/workspace/src/invariant.ts b/packages/workspace/workspace/src/invariant.ts new file mode 100644 index 0000000000..70c9ea4b48 --- /dev/null +++ b/packages/workspace/workspace/src/invariant.ts @@ -0,0 +1,53 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-workspace`. + * @module @deepseek-ai/dsh-workspace/invariant + */ + +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' +import type { DomainChanged } from '@deepseek-ai/dsh-storage-domain' +import { WorkspaceId } from '@deepseek-ai/dsh-workspace' + +const PACKAGE_NAME = '@deepseek-ai/dsh-workspace' + +/** Cordis companion plugin name. */ +export const name = 'workspace-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * Owned relationship: the registry's entity cache mirrors the workspace + * domain's durable table. Every `domain/changed` for the `workspaces` table + * must name a record the cache already holds an entity for (the registry + * caches before the durable put and mutates only through cached entities), + * and no `deleted` operation may appear at all — this phase ships no delete + * entry point, so a deletion proves a write path outside the registry. + */ +const install: InvariantInstaller = Object.assign( + (ctx: Context, fail: (message: string) => never) => { + ctx.on('domain/changed', (change: DomainChanged) => { + if (change.domain !== 'workspace' || change.table !== 'workspaces') return + if (change.operation === 'deleted') { + fail( + `workspace record '${change.key}' emitted a deleted change, but the registry ` + + 'exposes no delete entry point — some write path bypassed ctx.workspace', + ) + } + if (ctx.workspace.get(WorkspaceId(change.key)) === undefined) { + fail( + `workspace record '${change.key}' landed durably but the registry cache holds ` + + 'no entity for it — the cache and the domain table have diverged', + ) + } + }) + }, + { inject: ['workspace'] }, +) + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) diff --git a/packages/workspace/workspace/src/paths.ts b/packages/workspace/workspace/src/paths.ts new file mode 100644 index 0000000000..610ded0e06 --- /dev/null +++ b/packages/workspace/workspace/src/paths.ts @@ -0,0 +1,22 @@ +/** + * Path canonicalization for workspace identity. + * @module @deepseek-ai/dsh-workspace/src/paths + */ + +import { realpath } from 'node:fs/promises' + +/** + * Canonicalize a directory path via `fs.realpath`: trailing slashes, `..` + * segments, and symlinks are all resolved. This is the ONE uniqueness canon of + * the package — workspace paths are stored canonicalized, uniqueness is + * string equality of canonicalized paths (a symlink to an existing + * workspace's directory collides), and attach-time session `cwd` checks go + * through the same canon. A path that does not exist rejects with the + * original `ENOENT` — this is `create`'s reject path (a workspace must point + * at an existing directory). + * @param path - The path to canonicalize. + * @returns the canonical absolute path. + */ +export async function realpathNormalize(path: string): Promise<string> { + return await realpath(path) +} diff --git a/packages/workspace/workspace/src/spec.ts b/packages/workspace/workspace/src/spec.ts new file mode 100644 index 0000000000..7ef1487bd7 --- /dev/null +++ b/packages/workspace/workspace/src/spec.ts @@ -0,0 +1,39 @@ +/** + * The workspace domain declaration: record schema and the `defineDomain` spec + * the registry opens. The zod schema is the durable-boundary validator today + * and the direct source of the RPC wire projection in a later phase. + * @module @deepseek-ai/dsh-workspace/src/spec + */ + +import { z } from 'zod' +import { SessionId } from '@deepseek-ai/dsh-session' +import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain' +import type { WorkspaceId } from './types.ts' + +/** + * Durable shape of one workspace record. `path` is the `fs.realpath` canon + * stamped at create; `sessionIds` is the ordered ownership account (array + * order is display order); timestamps are ISO-8601 strings. + */ +export const workspaceRecord = z.object({ + path: z.string(), + title: z.string(), + sessionIds: z.array(z.string().transform(SessionId)), + createdAt: z.string(), + updatedAt: z.string(), +}) + +/** One stored workspace record, inferred from {@link workspaceRecord}. */ +export type WorkspaceRecord = z.infer<typeof workspaceRecord> + +/** + * The workspace domain spec: one `workspaces` table keyed by + * {@link WorkspaceId}, no global singleton. The registry opens this through + * `ctx.storage.domain`; the spec object is the single source of the domain's + * identity, version, and record schema. + */ +export const workspaceDomainSpec = defineDomain({ + name: 'workspace', + version: 1, + tables: { workspaces: domainTable<WorkspaceId, WorkspaceRecord>(workspaceRecord) }, +}) diff --git a/packages/workspace/workspace/src/types.ts b/packages/workspace/workspace/src/types.ts new file mode 100644 index 0000000000..cc5d75653d --- /dev/null +++ b/packages/workspace/workspace/src/types.ts @@ -0,0 +1,86 @@ +/** + * Public type vocabulary of the workspace entity: the `WorkspaceId` brand and + * the `Workspace` consumer interface. Types only — the `WorkspaceId` factory + * lives in `index.ts` (this file carries no runtime code). + * @module @deepseek-ai/dsh-workspace/src/types + */ + +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { SessionId } from '@deepseek-ai/dsh-session' + +/** + * Identifies one workspace record. A generated uuid, never the path: path + * normalization rewrites paths, and a reference anchor must stay stable. + */ +export type WorkspaceId = Branded<'WorkspaceId'> + +/** + * One workspace: a stable id over an existing directory, a display title, and + * the ordered account of sessions that belong to it. The account is the sole + * source of ownership — sessions are never inferred from cwd. Consumers only + * see this interface; the entity implementation stays package-private. + */ +export interface Workspace { + /** Stable record id (generated uuid). */ + readonly id: WorkspaceId + + /** + * Canonical directory path: the `fs.realpath` of the path given at create + * time (trailing slashes, `..`, and symlinks all resolved). Never rewritten + * afterwards, even when the directory disappears (see {@link status}). + */ + readonly path: string + + /** Display title. Defaults to `basename(path)` at create; duplicates are allowed. */ + readonly title: string + + /** + * Sessions recorded under this workspace, in attach order (the array order + * is the display order). A projection: accounted ids whose session no + * longer exists in session persistence are filtered out here (and dropped + * from the durable account on the next mutation); when session persistence + * is absent the account is served unfiltered because membership cannot be + * verified. + */ + readonly sessionIds: readonly SessionId[] + + /** + * Replace the display title durably. + * @param title - New title; any string, duplicates across workspaces allowed. + * @returns resolution after durability. + */ + setTitle(title: string): Promise<void> + + /** + * Record a session under this workspace. Idempotent: a session already on + * the account resolves without writing (membership is decided on the + * domain write chain, so unawaited concurrent attach/detach calls settle + * in call order). For a session not yet on the account, its stored header + * is read from session persistence and its `cwd`, normalized through the + * same `fs.realpath` canon as workspace paths, must equal this workspace's + * {@link path} — a missing persistence service, an unknown session id, a + * header without `cwd`, a `cwd` that no longer resolves, or a mismatched + * `cwd` all reject without touching the account (what cannot be validated + * is not recorded). + * @param sessionId - The session to record. + * @returns resolution after durability. + */ + attachSession(sessionId: SessionId): Promise<void> + + /** + * Remove a session from this workspace's account. Idempotent: an id not on + * the account resolves without writing (decided on the domain write chain, + * like attach). Never touches the session's own stored log. + * @param sessionId - The session to remove. + * @returns resolution after durability. + */ + detachSession(sessionId: SessionId): Promise<void> + + /** + * Live directory check, uncached: whether {@link path} currently exists and + * is a directory. A missing directory never mutates the record — the + * directory may only be temporarily moved. + * @returns `'ok'` when the directory exists, `'missing-dir'` otherwise. + */ + status(): Promise<'ok' | 'missing-dir'> +} diff --git a/packages/workspace/workspace/tests/invariant.spec.ts b/packages/workspace/workspace/tests/invariant.spec.ts new file mode 100644 index 0000000000..583c516937 --- /dev/null +++ b/packages/workspace/workspace/tests/invariant.spec.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import InvariantService from '@deepseek-ai/dsh-invariants' +import type { DomainChanged } from '@deepseek-ai/dsh-storage-domain' +import * as WorkspaceInvariant from '../src/invariant.ts' +import { WorkspaceId } from '../src/index.ts' + +/** Boot the invariant service plus the companion over a stubbed registry knowing exactly `ids`. */ +async function setup(ids: string[]): Promise<Context> { + const ctx = new Context() + await ctx.plugin(InvariantService) + ctx.provide('workspace', { + get: (id: WorkspaceId) => (ids.includes(id) ? { id } : undefined), + }) + await ctx.plugin(WorkspaceInvariant) + return ctx +} + +type ChangeLocation = Partial<Pick<DomainChanged, 'domain' | 'table' | 'key'>> + +const put = (overrides?: ChangeLocation): DomainChanged => ({ + domain: 'workspace', + table: 'workspaces', + key: 'w1', + operation: 'put', + value: {}, + ...overrides, +}) + +const deleted = (): DomainChanged => ({ + domain: 'workspace', + table: 'workspaces', + key: 'w1', + operation: 'deleted', +}) + +describe('workspace cache/table invariant', () => { + it('accepts a put whose record has a cached entity and ignores foreign events', async () => { + const ctx = await setup(['w1']) + expect(() => { ctx.emit('domain/changed', put()) }).not.toThrow() + // Other domains and other tables are out of scope, whatever their shape. + expect(() => { ctx.emit('domain/changed', put({ domain: 'other', key: 'missing' })) }).not.toThrow() + expect(() => { ctx.emit('domain/changed', put({ table: 'other', key: 'missing' })) }).not.toThrow() + }) + + it('fails a deleted operation — this phase exposes no delete entry point', async () => { + const ctx = await setup(['w1']) + expect(() => { ctx.emit('domain/changed', deleted()) }) + .toThrow(/no delete entry point/) + }) + + it('fails a put whose record the registry cache does not hold', async () => { + const ctx = await setup([]) + expect(() => { ctx.emit('domain/changed', put()) }).toThrow(/diverged/) + }) +}) diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts new file mode 100644 index 0000000000..9d2c71c5cc --- /dev/null +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -0,0 +1,381 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import { Context } from 'cordis' +import Storage from '@deepseek-ai/dsh-storage' +import type { StorageBackend } from '@deepseek-ai/dsh-storage' +import { DomainFacility } from '@deepseek-ai/dsh-storage-domain' +import type { DomainChanged } from '@deepseek-ai/dsh-storage-domain' +import { SessionId } from '@deepseek-ai/dsh-session' +import type { SessionHeader } from '@deepseek-ai/dsh-session' +import { MemoryMediaPool, MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts' +import WorkspaceRegistry, { WorkspaceId } from '../src/index.ts' +import type { WorkspaceRecord } from '../src/index.ts' + +const header = (id: string, cwd?: string): SessionHeader => + ({ version: 0, id: SessionId(id), createdAt: 0, ...(cwd === undefined ? {} : { cwd }) }) + +/** + * Boot storage hub + memory backend + domain form + the workspace registry. + * `sessions: 'absent'` boots without a sessionPersistence service; otherwise + * a stub serving exactly the given headers from `list()` is provided, and + * `setSessions` swaps what it serves next. + */ +async function harness(options?: { + pool?: MemoryMediaPool + sessions?: SessionHeader[] | 'absent' + backend?: StorageBackend +}) { + const ctx = new Context() + await ctx.plugin(Storage) + ctx.storage.backend.register('memory', options?.backend ?? new MemoryStorageBackend(options?.pool)) + ctx.storage.mount('domain', new DomainFacility(ctx, { backend: 'memory', routes: {} })) + let listed = options?.sessions === 'absent' ? undefined : options?.sessions ?? [] + if (listed !== undefined) { + ctx.provide('sessionPersistence', { list: async () => listed ?? [] }) + } + const changes: DomainChanged[] = [] + ctx.on('domain/changed', (change) => { changes.push(change) }) + await ctx.plugin(WorkspaceRegistry) + return { + ctx, + registry: ctx.workspace, + changes, + setSessions: (headers: SessionHeader[]) => { listed = headers }, + } +} + +/** A memory backend whose next `putRecord` throws once when armed, for write-failure paths. */ +function failingBackend(): { backend: StorageBackend; arm: () => void } { + const inner = new MemoryStorageBackend() + let failNext = false + return { + arm: () => { failNext = true }, + backend: { + kv: { + open: async (descriptor) => { + const unit = await inner.kv.open(descriptor) + return { + loadAll: () => unit.loadAll(), + putRecord: async (table, key, value) => { + if (failNext) { + failNext = false + throw new Error('medium write failed (injected)') + } + return unit.putRecord(table, key, value) + }, + deleteRecord: (table, key) => unit.deleteRecord(table, key), + setGlobal: value => unit.setGlobal(value), + close: () => unit.close(), + } + }, + }, + close: () => inner.close(), + }, + } +} + +/** A pool pre-stamped with one stored workspace record, simulating a prior run. */ +function pooledRecord(id: string, record: WorkspaceRecord): MemoryMediaPool { + const pool = new MemoryMediaPool() + pool.versions.set('workspace', 1) + pool.media.set('workspace', { + tables: new Map([['workspaces', new Map<string, unknown>([[id, record]])]]), + global: null, + }) + return pool +} + +const record = (path: string, sessionIds: string[]): WorkspaceRecord => ({ + path, + title: basename(path), + sessionIds: sessionIds.map(SessionId), + createdAt: '2026-07-24T00:00:00.000Z', + updatedAt: '2026-07-24T00:00:00.000Z', +}) + +/** Stored record as the memory medium currently holds it. */ +function storedRecord(pool: MemoryMediaPool, id: string): WorkspaceRecord { + return pool.media.get('workspace')!.tables.get('workspaces')!.get(id) as WorkspaceRecord +} + +let base: string +const tempDirs: string[] = [] + +/** A fresh real directory under a canonicalized temp base. */ +async function makeDir(name: string): Promise<string> { + base ??= await realpath(await mkdtemp(join(tmpdir(), 'dsh-workspace-'))) + if (tempDirs.length === 0) tempDirs.push(base) + const dir = join(base, name) + await mkdir(dir, { recursive: true }) + return dir +} + +afterEach(async () => { + for (const dir of tempDirs.splice(0)) await rm(dir, { recursive: true, force: true }) + base = undefined as never +}) + +describe('WorkspaceRegistry.create', () => { + it('stores the canonical path, defaults the title to basename, and lists the entity', async () => { + const dir = await makeDir('proj') + const { registry } = await harness() + const workspace = await registry.create(dir + '/') + expect(workspace.path).toBe(dir) + expect(workspace.title).toBe('proj') + expect(workspace.sessionIds).toEqual([]) + expect(registry.list()).toEqual([workspace]) + expect(registry.get(workspace.id)).toBe(workspace) + const titled = await registry.create(await makeDir('other'), 'Custom') + expect(titled.title).toBe('Custom') + }) + + it('rejects a nonexistent directory with the original ENOENT', async () => { + const dir = await makeDir('exists') + const { registry } = await harness() + await expect(registry.create(join(dir, 'nope'))).rejects.toMatchObject({ code: 'ENOENT' }) + expect(registry.list()).toEqual([]) + }) + + it('rejects a path resolving to a plain file', async () => { + const dir = await makeDir('has-file') + const file = join(dir, 'plain.txt') + await writeFile(file, 'not a directory') + const { registry } = await harness() + await expect(registry.create(file)).rejects.toThrow(/not a directory/) + expect(registry.list()).toEqual([]) + }) + + it('rejects a duplicate path, including a symlink resolving to an existing workspace', async () => { + const dir = await makeDir('real') + const link = join(base, 'link') + await symlink(dir, link) + const { registry } = await harness() + await registry.create(dir) + await expect(registry.create(link)).rejects.toThrow(/already exists/) + expect(registry.list()).toHaveLength(1) + }) + + it('resolves by path through the same canon', async () => { + const dir = await makeDir('canon') + const link = join(base, 'canon-link') + await symlink(dir, link) + const { registry } = await harness() + const workspace = await registry.create(dir) + expect(await registry.resolveByPath(link)).toBe(workspace) + expect(await registry.resolveByPath(await makeDir('unowned'))).toBeUndefined() + }) + + it('rolls the entity cache back when the durable write fails, leaving the path free to retry', async () => { + const dir = await makeDir('rollback') + const { backend, arm } = failingBackend() + const { registry } = await harness({ backend }) + arm() + await expect(registry.create(dir)).rejects.toThrow(/injected/) + expect(registry.list()).toEqual([]) + const retried = await registry.create(dir) + expect(retried.path).toBe(dir) + }) + + it('rejects any table access before the registry has started', async () => { + const dir = await makeDir('unstarted') + const ctx = new Context() + // Constructed directly, Service.init never ran: no domain, no table. + const registry = new WorkspaceRegistry(ctx) + await expect(registry.create(dir)).rejects.toThrow(/not started/) + }) + + it('closes its domain on fiber disposal so a re-plugged registry reopens it', async () => { + const dir = await makeDir('replug') + const ctx = new Context() + await ctx.plugin(Storage) + ctx.storage.backend.register('memory', new MemoryStorageBackend()) + ctx.storage.mount('domain', new DomainFacility(ctx, { backend: 'memory', routes: {} })) + const fiber = ctx.plugin(WorkspaceRegistry) + await fiber + const first = await ctx.workspace.create(dir) + await fiber.dispose() + // The registry's effect closed the domain, freeing the name: a second + // plugin of the same registry must reopen it (not already-open) and see + // the durable record. + await ctx.plugin(WorkspaceRegistry) + const reloaded = await ctx.workspace.resolveByPath(dir) + expect(reloaded?.id).toBe(first.id) + }) +}) + +describe('Workspace.attachSession', () => { + it('attaches when the session cwd resolves to the workspace path, keeping attach order', async () => { + const dir = await makeDir('attach') + const link = join(base, 'attach-link') + await symlink(dir, link) + // s2's cwd is spelled through the symlink: same canon, must attach. + const { registry } = await harness({ + sessions: [header('s1', dir), header('s2', link), header('s3', dir)], + }) + const workspace = await registry.create(dir) + await workspace.attachSession(SessionId('s1')) + await workspace.attachSession(SessionId('s2')) + await workspace.attachSession(SessionId('s3')) + expect(workspace.sessionIds).toEqual(['s1', 's2', 's3']) + await workspace.detachSession(SessionId('s2')) + expect(workspace.sessionIds).toEqual(['s1', 's3']) + }) + + it('rejects a cwd resolving elsewhere, a missing cwd, and an unknown session', async () => { + const dir = await makeDir('strict') + const elsewhere = await makeDir('elsewhere') + const { registry } = await harness({ + sessions: [header('other-dir', elsewhere), header('no-cwd', undefined)], + }) + const workspace = await registry.create(dir) + await expect(workspace.attachSession(SessionId('other-dir'))).rejects.toThrow(/resolves to/) + await expect(workspace.attachSession(SessionId('no-cwd'))).rejects.toThrow(/no cwd/) + await expect(workspace.attachSession(SessionId('unknown'))).rejects.toThrow(/no such session/) + expect(workspace.sessionIds).toEqual([]) + }) + + it('rejects a cwd that no longer resolves', async () => { + const dir = await makeDir('target') + const gone = await makeDir('gone') + const { registry } = await harness({ sessions: [header('s1', gone)] }) + const workspace = await registry.create(dir) + await rm(gone, { recursive: true }) + await expect(workspace.attachSession(SessionId('s1'))).rejects.toThrow(/does not resolve/) + }) + + it('rejects every attach while session persistence is absent', async () => { + const dir = await makeDir('no-persistence') + const { registry } = await harness({ sessions: 'absent' }) + const workspace = await registry.create(dir) + await expect(workspace.attachSession(SessionId('s1'))).rejects.toThrow(/no session persistence/) + }) + + it('is idempotent on both attach and detach — a no-op never writes', async () => { + const dir = await makeDir('idem') + const { registry, changes, setSessions } = await harness({ sessions: [header('s1', dir)] }) + const workspace = await registry.create(dir) + await workspace.attachSession(SessionId('s1')) + const written = changes.length + // Re-attaching skips validation entirely: even with the session gone from + // the listing, the id already being on the account resolves without IO. + setSessions([]) + await workspace.attachSession(SessionId('s1')) + await workspace.detachSession(SessionId('absent')) + expect(changes.length).toBe(written) + }) + + it('decides membership at the write-chain slot: unawaited detach then attach re-attaches', async () => { + const dir = await makeDir('race') + const { registry } = await harness({ sessions: [header('s1', dir)] }) + const workspace = await registry.create(dir) + await workspace.attachSession(SessionId('s1')) + // Both fire before either lands. Snapshot-based idempotence would see + // 's1' still on the account and turn the attach into a no-op, losing it; + // chain-slot decisions replay detach → attach in order. (The attach skips + // re-validation off the same stale snapshot — the cwd fact is immutable — + // and enqueues immediately, keeping the chain order deterministic here.) + const detached = workspace.detachSession(SessionId('s1')) + const attached = workspace.attachSession(SessionId('s1')) + await Promise.all([detached, attached]) + expect(workspace.sessionIds).toEqual(['s1']) + }) +}) + +describe('consistency projections', () => { + it('filters accounted ids with no stored session and prunes them on the next mutation', async () => { + const dir = await makeDir('stale') + const id = WorkspaceId('00000000-0000-4000-8000-000000000001') + const pool = pooledRecord(id, record(dir, ['live', 'ghost'])) + const { registry } = await harness({ pool, sessions: [header('live', dir)] }) + const workspace = registry.get(id)! + // Rule 1: the projection hides the dead id; the durable account still holds it. + expect(workspace.sessionIds).toEqual(['live']) + expect(storedRecord(pool, id).sessionIds).toEqual(['live', 'ghost']) + // Any mutation prunes it durably. + await workspace.setTitle('renamed') + expect(storedRecord(pool, id).sessionIds).toEqual(['live']) + expect(workspace.title).toBe('renamed') + }) + + it('serves the account unfiltered while session persistence is absent', async () => { + const dir = await makeDir('unverifiable') + const id = WorkspaceId('00000000-0000-4000-8000-000000000002') + const pool = pooledRecord(id, record(dir, ['maybe'])) + const { registry } = await harness({ pool, sessions: 'absent' }) + const workspace = registry.get(id)! + expect(workspace.sessionIds).toEqual(['maybe']) + // Mutations must not prune either: unverifiable membership is kept as-is. + await workspace.setTitle('still-unverified') + expect(storedRecord(pool, id).sessionIds).toEqual(['maybe']) + }) + + it('prunes dead ids even when the triggering mutation is itself a no-op', async () => { + const dir = await makeDir('prune-on-noop') + const id = WorkspaceId('00000000-0000-4000-8000-000000000007') + const pool = pooledRecord(id, record(dir, ['ghost'])) + const { registry, changes } = await harness({ pool, sessions: [] }) + const workspace = registry.get(id)! + // Detaching an id that was never on the account changes nothing by + // itself, but the mutation slot still prunes the dead 'ghost' durably. + await workspace.detachSession(SessionId('never-there')) + expect(storedRecord(pool, id).sessionIds).toEqual([]) + expect(changes).toHaveLength(1) + }) + + it('rejects startup over a medium accounting one session twice', async () => { + const dirA = await makeDir('double-a') + const dirB = await makeDir('double-b') + const pool = pooledRecord('00000000-0000-4000-8000-000000000003', record(dirA, ['dup'])) + pool.media.get('workspace')!.tables.get('workspaces')! + .set('00000000-0000-4000-8000-000000000004', record(dirB, ['dup'])) + const ctx = new Context() + await ctx.plugin(Storage) + ctx.storage.backend.register('memory', new MemoryStorageBackend(pool)) + ctx.storage.mount('domain', new DomainFacility(ctx, { backend: 'memory', routes: {} })) + await expect(Promise.resolve(ctx.plugin(WorkspaceRegistry))).rejects.toThrow(/accounted/) + }) + + it('rejects startup over a medium where two records claim one path', async () => { + const dirA = await makeDir('claimed') + const pool = pooledRecord('00000000-0000-4000-8000-000000000005', record(dirA, [])) + pool.media.get('workspace')!.tables.get('workspaces')! + .set('00000000-0000-4000-8000-000000000006', record(dirA, [])) + const ctx = new Context() + await ctx.plugin(Storage) + ctx.storage.backend.register('memory', new MemoryStorageBackend(pool)) + ctx.storage.mount('domain', new DomainFacility(ctx, { backend: 'memory', routes: {} })) + await expect(Promise.resolve(ctx.plugin(WorkspaceRegistry))).rejects.toThrow(/claimed/) + }) +}) + +describe('Workspace mutation failures', () => { + it('propagates a medium write failure from a mutation and keeps the old snapshot', async () => { + const dir = await makeDir('write-fail') + const { backend, arm } = failingBackend() + const { registry } = await harness({ backend }) + const workspace = await registry.create(dir) + arm() + await expect(workspace.setTitle('lost')).rejects.toThrow(/injected/) + expect(workspace.title).toBe('write-fail') + await workspace.setTitle('kept') + expect(workspace.title).toBe('kept') + }) +}) + +describe('Workspace.status', () => { + it('reports ok while the directory exists and missing-dir once it is gone, without mutating the record', async () => { + const dir = await makeDir('vanishing') + const { registry } = await harness() + const workspace = await registry.create(dir) + expect(await workspace.status()).toBe('ok') + await rm(dir, { recursive: true }) + expect(await workspace.status()).toBe('missing-dir') + expect(workspace.path).toBe(dir) + expect(registry.get(workspace.id)).toBe(workspace) + // The path re-materializing as a non-directory is still missing-dir. + await writeFile(dir, 'now a file') + expect(await workspace.status()).toBe('missing-dir') + }) +}) diff --git a/packages/workspace/workspace/tsconfig.json b/packages/workspace/workspace/tsconfig.json new file mode 100644 index 0000000000..0bddf4672c --- /dev/null +++ b/packages/workspace/workspace/tsconfig.json @@ -0,0 +1,39 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../storage/storage" + }, + { + "path": "../../storage/storage-domain" + }, + { + "path": "../../core/session" + }, + { + "path": "../../session-persistence/session-persistence" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9ff32a5140..400ae6df7e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -98,9 +98,27 @@ importers: apps/cli: dependencies: + '@cordisjs/plugin-include': + specifier: workspace:* + version: link:../../vendor/include + '@cordisjs/plugin-loader': + specifier: workspace:* + version: link:../../vendor/loader + '@cordisjs/plugin-timer': + specifier: workspace:* + version: link:../../vendor/timer + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../packages/core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:^ + version: link:../../packages/core/agent-loop '@deepseek-ai/dsh-app-boot': specifier: workspace:^ version: link:../../packages/ui/app-boot + '@deepseek-ai/dsh-bash-local': + specifier: workspace:^ + version: link:../../packages/bash/bash-local '@deepseek-ai/dsh-client-connection': specifier: workspace:^ version: link:../../packages/client/connection @@ -110,6 +128,9 @@ importers: '@deepseek-ai/dsh-client-i18n': specifier: workspace:^ version: link:../../packages/client/i18n + '@deepseek-ai/dsh-client-modules': + specifier: workspace:^ + version: link:../../packages/client/modules '@deepseek-ai/dsh-client-runtime': specifier: workspace:^ version: link:../../packages/client/runtime @@ -131,9 +152,18 @@ importers: '@deepseek-ai/dsh-client-ui-trajectory': specifier: workspace:^ version: link:../../packages/client/ui-trajectory + '@deepseek-ai/dsh-compact-basic': + specifier: workspace:^ + version: link:../../packages/compact/compact-basic '@deepseek-ai/dsh-frontend': specifier: workspace:^ version: link:../web + '@deepseek-ai/dsh-fs-local': + specifier: workspace:^ + version: link:../../packages/fs/fs-local + '@deepseek-ai/dsh-fs-policy': + specifier: workspace:^ + version: link:../../packages/fs/fs-policy '@deepseek-ai/dsh-host-apiproxy': specifier: workspace:^ version: link:../../packages/host/apiproxy @@ -143,18 +173,109 @@ importers: '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ version: link:../../packages/host/webserver + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../packages/llm/llm + '@deepseek-ai/dsh-llm-deepseek': + specifier: workspace:^ + version: link:../../packages/llm/llm-deepseek '@deepseek-ai/dsh-paths': specifier: workspace:^ version: link:../../packages/util/paths '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../packages/core/session + '@deepseek-ai/dsh-session-persistence-jsonl': + specifier: workspace:^ + version: link:../../packages/session-persistence/session-persistence-jsonl + '@deepseek-ai/dsh-session-title': + specifier: workspace:^ + version: link:../../packages/session-title/session-title + '@deepseek-ai/dsh-session-title-first-message-llm': + specifier: workspace:^ + version: link:../../packages/session-title/session-title-first-message-llm + '@deepseek-ai/dsh-skill': + specifier: workspace:^ + version: link:../../packages/skill/skill + '@deepseek-ai/dsh-skill-local': + specifier: workspace:^ + version: link:../../packages/skill/skill-local + '@deepseek-ai/dsh-spill-local': + specifier: workspace:^ + version: link:../../packages/spill/spill-local + '@deepseek-ai/dsh-spill-policy': + specifier: workspace:^ + version: link:../../packages/spill/spill-policy + '@deepseek-ai/dsh-subagent': + specifier: workspace:^ + version: link:../../packages/subagent/subagent + '@deepseek-ai/dsh-subagent-fork': + specifier: workspace:^ + version: link:../../packages/subagent/subagent-fork + '@deepseek-ai/dsh-subagent-spawn': + specifier: workspace:^ + version: link:../../packages/subagent/subagent-spawn + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:^ + version: link:../../packages/core/system-prompt + '@deepseek-ai/dsh-tasks': + specifier: workspace:^ + version: link:../../packages/tasks/tasks + '@deepseek-ai/dsh-timeout-policy': + specifier: workspace:^ + version: link:../../packages/timeout/timeout-policy + '@deepseek-ai/dsh-token-meter': + specifier: workspace:^ + version: link:../../packages/llm/token-meter + '@deepseek-ai/dsh-tool-bash': + specifier: workspace:^ + version: link:../../packages/bash/tool-bash + '@deepseek-ai/dsh-tool-fs': + specifier: workspace:^ + version: link:../../packages/fs/tool-fs + '@deepseek-ai/dsh-tool-fs-search': + specifier: workspace:^ + version: link:../../packages/fs/tool-fs-search + '@deepseek-ai/dsh-tool-skill': + specifier: workspace:^ + version: link:../../packages/skill/tool-skill + '@deepseek-ai/dsh-tool-subagent': + specifier: workspace:^ + version: link:../../packages/subagent/tool-subagent + '@deepseek-ai/dsh-tool-tasks': + specifier: workspace:^ + version: link:../../packages/tasks/tool-tasks + '@deepseek-ai/dsh-tool-todo': + specifier: workspace:^ + version: link:../../packages/todo/tool-todo + '@deepseek-ai/dsh-tool-workflow': + specifier: workspace:^ + version: link:../../packages/workflow/tool-workflow + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../packages/core/tools '@deepseek-ai/dsh-tui': specifier: workspace:^ version: link:../../packages/ui/tui + '@deepseek-ai/dsh-user-interaction': + specifier: workspace:^ + version: link:../../packages/ui/user-interaction + '@deepseek-ai/dsh-workflow-workerthread': + specifier: workspace:^ + version: link:../../packages/workflow/workflow-workerthread + '@deepseek-ai/dsh-workspace-context': + specifier: workspace:^ + version: link:../../packages/context/workspace-context cordis: specifier: ^4.0.0-rc.7 - version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + version: 4.0.0-rc.7(@cordisjs/plugin-include@vendor+include)(@cordisjs/plugin-loader@vendor+loader) + js-yaml: + specifier: ^4.2.0 + version: 4.2.0 + devDependencies: + '@types/js-yaml': + specifier: ^4.0.9 + version: 4.0.9 apps/web: dependencies: @@ -180,9 +301,6 @@ importers: '@deepseek-ai/dsh-client-web-react': specifier: workspace:^ version: link:../../packages/client/web-react - '@deepseek-ai/dsh-host-webserver': - specifier: workspace:^ - version: link:../../packages/host/webserver '@types/node': specifier: ^22.0.0 version: 22.20.0 @@ -407,6 +525,43 @@ importers: specifier: 1.1.0 version: 1.1.0 + packages/acp/acp: + dependencies: + '@agentclientprotocol/sdk': + specifier: 0.25.1 + version: 0.25.1(zod@4.4.3) + schemastery: + specifier: ^3.17.0 + version: 3.18.0 + devDependencies: + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:^ + version: link:../../core/agent-loop + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../support/agent-loop-testkit + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-session': + specifier: workspace:^ + version: link:../../core/session + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../core/tools + '@deepseek-ai/dsh-user-approval': + specifier: workspace:^ + version: link:../../ui/user-approval + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/bash/bash: devDependencies: '@deepseek-ai/dsh-invariants': @@ -544,6 +699,9 @@ importers: specifier: workspace:^ version: link:../../core/tools devDependencies: + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:^ + version: link:../../host/webserver '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants @@ -552,6 +710,10 @@ importers: version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) packages/client/hmr: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 devDependencies: '@cordisjs/plugin-loader': specifier: workspace:^ @@ -559,6 +721,9 @@ importers: '@deepseek-ai/dsh-client-modules': specifier: workspace:^ version: link:../modules + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:^ + version: link:../../host/webserver '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants @@ -581,12 +746,18 @@ importers: packages/client/modules: devDependencies: + '@cordisjs/plugin-loader': + specifier: workspace:^ + version: link:../../../vendor/loader + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:^ + version: link:../../host/webserver '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants cordis: specifier: ^4.0.0-rc.7 - version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@vendor+loader) packages/client/runtime: dependencies: @@ -1323,7 +1494,7 @@ importers: version: link:../../../vendor/loader '@deepseek-ai/dsh-acp': specifier: workspace:^ - version: link:../../ui/acp + version: link:../../acp/acp '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent @@ -1333,12 +1504,6 @@ importers: '@deepseek-ai/dsh-app-boot': specifier: workspace:^ version: link:../../ui/app-boot - '@deepseek-ai/dsh-command-goal': - specifier: workspace:^ - version: link:../../goal/command-goal - '@deepseek-ai/dsh-commands': - specifier: workspace:^ - version: link:../../ui/commands '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants @@ -1354,18 +1519,12 @@ importers: '@deepseek-ai/dsh-session-query-sqlite': specifier: workspace:^ version: link:../../session-query/session-query-sqlite - '@deepseek-ai/dsh-session-reference': - specifier: workspace:^ - version: link:../../context/session-reference '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools - '@deepseek-ai/dsh-user-interaction': - specifier: workspace:^ - version: link:../../ui/user-interaction '@deepseek-ai/dsh-workspace-context': specifier: workspace:^ version: link:../../context/workspace-context @@ -2054,6 +2213,9 @@ importers: packages/host/apiproxy: dependencies: + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../core/agent '@deepseek-ai/dsh-brand': specifier: workspace:^ version: link:../../util/brand @@ -2063,6 +2225,12 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:^ + version: link:../../session-persistence/session-persistence + '@deepseek-ai/dsh-session-title': + specifier: workspace:^ + version: link:../../session-title/session-title '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools @@ -2072,6 +2240,9 @@ importers: '@deepseek-ai/dsh-user-interaction': specifier: workspace:^ version: link:../../ui/user-interaction + schemastery: + specifier: ^3.18.0 + version: 3.18.0 zod: specifier: ^4.4.3 version: 4.4.3 @@ -2121,9 +2292,6 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session - '@deepseek-ai/dsh-session-persistence': - specifier: workspace:^ - version: link:../../session-persistence/session-persistence '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:^ version: link:../../session-persistence/session-persistence-jsonl @@ -2217,6 +2385,10 @@ importers: version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@vendor+loader) packages/host/webserver: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 devDependencies: '@deepseek-ai/dsh-invariants': specifier: workspace:^ @@ -3225,6 +3397,66 @@ importers: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/storage/storage: + devDependencies: + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + + packages/storage/storage-domain: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 + zod: + specifier: ^4.4.3 + version: 4.4.3 + devDependencies: + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@deepseek-ai/dsh-storage': + specifier: workspace:^ + version: link:../storage + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + + packages/storage/storage-json: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 + devDependencies: + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@deepseek-ai/dsh-storage': + specifier: workspace:^ + version: link:../storage + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + + packages/storage/storage-sqlite: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 + devDependencies: + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@deepseek-ai/dsh-storage': + specifier: workspace:^ + version: link:../storage + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/subagent/subagent: devDependencies: '@deepseek-ai/dsh-agent': @@ -3644,106 +3876,6 @@ importers: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) - packages/ui/acp: - dependencies: - '@agentclientprotocol/sdk': - specifier: 0.25.1 - version: 0.25.1(zod@4.4.3) - schemastery: - specifier: ^3.17.0 - version: 3.18.0 - zod: - specifier: ^4.0.0 - version: 4.4.3 - devDependencies: - '@deepseek-ai/dsh-agent': - specifier: workspace:^ - version: link:../../core/agent - '@deepseek-ai/dsh-agent-loop': - specifier: workspace:^ - version: link:../../core/agent-loop - '@deepseek-ai/dsh-agent-loop-testkit': - specifier: workspace:^ - version: link:../../support/agent-loop-testkit - '@deepseek-ai/dsh-bash': - specifier: workspace:^ - version: link:../../bash/bash - '@deepseek-ai/dsh-bash-local': - specifier: workspace:^ - version: link:../../bash/bash-local - '@deepseek-ai/dsh-commands': - specifier: workspace:^ - version: link:../commands - '@deepseek-ai/dsh-fs-local': - specifier: workspace:^ - version: link:../../fs/fs-local - '@deepseek-ai/dsh-fs-policy': - specifier: workspace:^ - version: link:../../fs/fs-policy - '@deepseek-ai/dsh-invariants': - specifier: workspace:^ - version: link:../../support/invariants - '@deepseek-ai/dsh-llm': - specifier: workspace:^ - version: link:../../llm/llm - '@deepseek-ai/dsh-llm-retry': - specifier: workspace:^ - version: link:../../llm/llm-retry - '@deepseek-ai/dsh-permission': - specifier: workspace:^ - version: link:../permission - '@deepseek-ai/dsh-plan-mode': - specifier: workspace:^ - version: link:../../plan/plan-mode - '@deepseek-ai/dsh-sandbox': - specifier: workspace:^ - version: link:../../sandbox/sandbox - '@deepseek-ai/dsh-session': - specifier: workspace:^ - version: link:../../core/session - '@deepseek-ai/dsh-session-persistence': - specifier: workspace:^ - version: link:../../session-persistence/session-persistence - '@deepseek-ai/dsh-session-persistence-jsonl': - specifier: workspace:^ - version: link:../../session-persistence/session-persistence-jsonl - '@deepseek-ai/dsh-session-query': - specifier: workspace:^ - version: link:../../session-query/session-query - '@deepseek-ai/dsh-session-reference': - specifier: workspace:^ - version: link:../../context/session-reference - '@deepseek-ai/dsh-session-title': - specifier: workspace:^ - version: link:../../session-title/session-title - '@deepseek-ai/dsh-system-prompt': - specifier: workspace:^ - version: link:../../core/system-prompt - '@deepseek-ai/dsh-tool-ask-user': - specifier: workspace:^ - version: link:../tool-ask-user - '@deepseek-ai/dsh-tool-bash': - specifier: workspace:^ - version: link:../../bash/tool-bash - '@deepseek-ai/dsh-tool-fs': - specifier: workspace:^ - version: link:../../fs/tool-fs - '@deepseek-ai/dsh-tool-todo': - specifier: workspace:^ - version: link:../../todo/tool-todo - '@deepseek-ai/dsh-tools': - specifier: workspace:^ - version: link:../../core/tools - '@deepseek-ai/dsh-user-approval': - specifier: workspace:^ - version: link:../user-approval - '@deepseek-ai/dsh-user-interaction': - specifier: workspace:^ - version: link:../user-interaction - cordis: - specifier: ^4.0.0-rc.7 - version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) - packages/ui/app-boot: dependencies: js-yaml: @@ -4331,6 +4463,34 @@ importers: specifier: ^4.19.2 version: 4.22.4 + packages/workspace/workspace: + dependencies: + zod: + specifier: ^4.4.3 + version: 4.4.3 + devDependencies: + '@deepseek-ai/dsh-brand': + specifier: workspace:^ + version: link:../../util/brand + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@deepseek-ai/dsh-session': + specifier: workspace:^ + version: link:../../core/session + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:^ + version: link:../../session-persistence/session-persistence + '@deepseek-ai/dsh-storage': + specifier: workspace:^ + version: link:../../storage/storage + '@deepseek-ai/dsh-storage-domain': + specifier: workspace:^ + version: link:../../storage/storage-domain + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + python/sdk-runtime: dependencies: '@cordisjs/plugin-include': @@ -4344,7 +4504,7 @@ importers: version: link:../../vendor/timer '@deepseek-ai/dsh-acp': specifier: workspace:^ - version: link:../../packages/ui/acp + version: link:../../packages/acp/acp '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../packages/core/agent diff --git a/scripts/cordis-config-files.spec.ts b/scripts/cordis-config-files.spec.ts new file mode 100644 index 0000000000..ae5c4b1580 --- /dev/null +++ b/scripts/cordis-config-files.spec.ts @@ -0,0 +1,36 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { cordisConfigFiles } from './cordis-config-files.ts' + +const roots: string[] = [] + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +describe('cordisConfigFiles', () => { + it('finds Loader YAML without treating translation records as configs', () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-cordis-config-files-')) + roots.push(root) + for (const directory of ['.claude', 'docs', 'examples', 'node_modules/pkg', 'vendor/pkg']) { + mkdirSync(join(root, directory), { recursive: true }) + } + for (const file of [ + '.claude/hidden.cordis.yml', + 'docs/cordis-primer.i18n.yaml', + 'examples/agent.cordis.yaml', + 'examples/headless.cordis.yml', + 'node_modules/pkg/hidden.cordis.yml', + 'vendor/pkg/hidden.cordis.yml', + ]) { + writeFileSync(join(root, file), '[]\n') + } + + expect(cordisConfigFiles(root)).toEqual([ + join('examples', 'agent.cordis.yaml'), + join('examples', 'headless.cordis.yml'), + ]) + }) +}) diff --git a/scripts/cordis-config-files.ts b/scripts/cordis-config-files.ts new file mode 100644 index 0000000000..9473779efe --- /dev/null +++ b/scripts/cordis-config-files.ts @@ -0,0 +1,18 @@ +/** Cordis Loader configuration file discovery. */ + +import { globSync } from 'node:fs' + +/** + * Return repository-relative Cordis Loader YAML paths under `root`. + * + * Translation consistency records are YAML sidecars, never Loader inputs. + * + * @param root Repository root to scan. + * @returns Sorted repository-relative Loader configuration paths. + */ +export function cordisConfigFiles(root: string): string[] { + return globSync(['**/*cordis*.yml', '**/*cordis*.yaml'], { + cwd: root, + exclude: ['.claude/**', 'node_modules/**', 'vendor/**', '**/*.i18n.yaml'], + }).sort() +} diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index 7e4d154174..45c7e74414 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -7,5 +7,5 @@ "docs/testing.md": 1020, "examples/AGENTS.md": 310, "packages/AGENTS.md": 660, - "packages/README.md": 760 + "packages/README.md": 790 } diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 6e5f95f809..13df129998 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -211,8 +211,15 @@ const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = { BashEnvVariableInfo: 'service-local metadata type is owned by packages/bash/tool-bash/src/index.ts', CompactAgentContext: 'compaction service input is owned by packages/compact/compact/src/index.ts', CreateAgentOptions: 'agent creation contract is owned by packages/core/agent/README.md', + DomainChanged: 'event-local snapshot is owned by packages/storage/storage-domain/src/events.ts', + DomainFacility: 'domain form facility is owned by packages/storage/storage-domain/README.md', + DomainSpec: 'domain declaration contract is owned by packages/storage/storage-domain/README.md', + StorageBackend: 'backend contract is owned by packages/storage/storage/src/backend.ts', + StorageForms: 'merge-extensible form map is owned by packages/storage/storage/src/index.ts', InvariantInstaller: 'service-local contribution contract is owned by packages/support/invariants/README.md', LocaleDict: 'service-local dictionary shape is owned by packages/client/i18n/src/index.ts', + WebBootGraph: 'web boot graph wire shape is owned by packages/client/modules/src/client/index.ts', + WebRoute: 'route registration contract is owned by packages/host/webserver/src/index.ts', ThemeTokens: 'service-local token dictionary is owned by packages/client/ui-theme/src/index.ts', Translate: 'service-local bound translator is owned by packages/client/i18n/src/index.ts', TuiOverlayRequest: 'service-local extension contract is owned by packages/ui/tui/README.md', @@ -228,6 +235,8 @@ const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = { WorkflowAgentEndInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts', WorkflowAgentInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts', WorkflowResultInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts', + Workspace: 'workspace entity contract is owned by packages/workspace/workspace/README.md', + WorkspaceId: 'branded id is owned by packages/workspace/workspace/README.md', } /** Collect named references from parameter, generic-constraint/default, and return types. */ diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 50d679a4e5..7c087fd2e4 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -77,7 +77,10 @@ const GROUP_ORDER = [ 'session-persistence', 'session-query', 'session-title', + 'storage', + 'workspace', 'support', + 'acp', 'ui', ] @@ -129,9 +132,26 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Durable session persistence seam', mode: 'seam', implementations: ['session-persistence-jsonl', 'session-persistence-sqlite'], - consumers: ['agent-loop', 'tool-bash', 'hooks-claude', 'hooks-codex', 'acp', 'session-query', 'session-query-sqlite'], + consumers: ['agent-loop', 'tool-bash', 'hooks-claude', 'hooks-codex', 'session-query', 'session-query-sqlite'], note: 'Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time.', }, + { + key: 'storage', + pkg: 'storage', + title: 'Non-session storage hub', + mode: 'seam', + implementations: ['storage-json', 'storage-sqlite'], + consumers: ['storage-domain', 'workspace'], + note: 'Backends register side by side under names; data forms (domain first) mount on the hub and translate typed operations into opaque KV-unit primitives.', + }, + { + key: 'workspace', + pkg: 'workspace', + title: 'Workspace entity registry', + mode: 'core', + consumers: [], + note: 'Owns WorkspaceId-branded records over the domain form; sessionIds is the single source of ownership truth. RPC and GUI consumers arrive next phase.', + }, { key: 'sessionQuery', pkg: 'session-query', @@ -146,7 +166,7 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'session-reference', title: 'Cross-session snapshot preparation', mode: 'core', - consumers: ['tui', 'acp'], + consumers: ['tui'], note: 'Projects bounded current-surface conversation snapshots into durable untrusted message context; host adapters own mention syntax.', }, { @@ -170,7 +190,7 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'tools', title: 'Tool registry and guarded execution pipeline', mode: 'core', - consumers: ['agent-loop', 'tool-ask-user', 'tool-bash', 'tool-cordis', 'tool-fs', 'tool-pty', 'tool-skill', 'tool-subagent', 'tool-todo', 'tool-web', 'acp'], + consumers: ['agent-loop', 'tool-ask-user', 'tool-bash', 'tool-cordis', 'tool-fs', 'tool-pty', 'tool-skill', 'tool-subagent', 'tool-todo', 'tool-web'], note: 'Registers capabilities, owns Code Mode transport, and routes calls through pre-policy, monotonic guards, around dispatch, post-policy, and final-result observation.', }, { @@ -178,8 +198,8 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'user-interaction', title: 'Human question/answer seam', mode: 'seam', - implementations: ['tui', 'acp'], - consumers: ['tool-ask-user', 'tui', 'acp'], + implementations: ['tui'], + consumers: ['tool-ask-user', 'tui'], note: 'UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise.', }, { @@ -187,7 +207,6 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'plan-mode', title: 'Plan collaboration state', mode: 'core', - consumers: ['acp'], note: 'Folds logged plan/mode state, flushes user selections at turn boundaries, renders deployment-owned guidance, registers /plan, and keeps the plan-exit schema stable across transitions.', }, { @@ -195,8 +214,8 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'commands', title: 'Human command registry', mode: 'core', - consumers: ['tui', 'acp'], - note: 'Plugins register direct human commands; TUI and ACP consume the same effective per-agent catalog without sending invocations to the model.', + consumers: ['tui'], + note: 'Plugins register direct human commands; TUI consumes the effective per-agent catalog without sending invocations to the model.', }, { key: 'tui', @@ -295,7 +314,6 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Permission presets', mode: 'core', implementations: [], - consumers: ['acp'], note: 'User-facing preset table (`workspace-write`/`danger-full-access`) bundling the sandbox-mode and approval-policy knobs; a switch writes one `permission/preset` event through to both knob events.', }, { @@ -361,6 +379,22 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['spill-policy'], note: 'The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill.', }, + { + key: 'httpServer', + pkg: 'webserver', + title: 'HTTP route registration', + mode: 'core', + consumers: ['connection', 'modules', 'hmr'], + note: 'Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes.', + }, + { + key: 'clientModuleHost', + pkg: 'modules', + title: 'Client plugin graph host', + mode: 'core', + consumers: ['hmr'], + note: 'Composes the __DSH_BOOT__ entry graph from an incremental dshClient scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers.', + }, { key: 'workflows', pkg: 'workflow', @@ -531,10 +565,10 @@ const APP_EXAMPLES = [ { id: 'acp', rel: 'examples/acp-agent/composition.md', - title: 'ACP Agent App Composition', + title: 'ACP Automation App Composition', label: 'examples/acp-agent', config: 'examples/acp-agent/cordis.yml', - summary: 'The ACP demo exposes the same agent spine over JSON-RPC stdio, with no stdout logger and no pre-created agent; clients create sessions through the ACP bridge.', + summary: 'The ACP demo exposes fresh baseline-prompt agent sessions to programmatic clients over JSON-RPC stdio, with no stdout logger, human UI, or pre-created agent.', }, ] @@ -550,7 +584,7 @@ function renderAppExpansion(lines: string[], appNode: string, pluginName: string } else if (pluginName === '@deepseek-ai/dsh-cli-demo') { lines.push(` ${appNode} --> ${nodeId('frontdoor', 'cli')}["one-shot driver<br/>format-pure stdout<br/>fresh top-level agent"]`) } else if (pluginName === '@deepseek-ai/dsh-acp-demo') { - lines.push(` ${appNode} --> ${nodeId('frontdoor', 'acp')}["@deepseek-ai/dsh-acp<br/>JSON-RPC stdio bridge<br/>sessions created by client"]`) + lines.push(` ${appNode} --> ${nodeId('frontdoor', 'acp')}["@deepseek-ai/dsh-acp<br/>automation-only JSON-RPC stdio<br/>fresh sessions created by client"]`) } lines.push( ` ${agentCore} --> ${nodeId('spine', 'llm')}["ctx.llm"]`, @@ -1039,35 +1073,6 @@ function renderToolPipeline(): string { ].join('\n') } -function renderSnapshotReplay(): string { - const maintenance = 'curated Mermaid sequence based on the snapshot test harness' - return [ - ...generatedHeader('ACP Snapshot Replay'), - 'This graph explains what a snapshot scenario proves: recorded real-model session logs are replayed keylessly, ACP stdout is normalized and diffed, and scenario workspaces preserve tool side effects that the UI stream alone cannot prove.', - '', - '```mermaid', - 'sequenceDiagram', - ' participant Recorder as Real API recording', - ' participant Fixture as snapshot fixture', - ' participant Workspace', - ' participant Replay as llm-replay adapter', - ' participant ACP as acp-agent subprocess', - ' participant Expected as stdout expected output', - ' Recorder->>Fixture: session.jsonl + workspace inputs', - ' Fixture->>Workspace: seed files and hook configs', - ' Fixture->>Replay: recorded StreamChunk script', - ` Replay->>ACP: deterministic ${mermaidCode('llm/stream')} chunks`, - ' ACP->>Workspace: bash, fs, and hook side effects', - ' ACP->>Expected: normalized sessionUpdate stream', - ' Expected-->>ACP: diff must be empty', - '```', - '', - 'The fs and hook snapshot matrix is valuable because it proves world state, hook decisions, and failed tool-card rendering, not just that replay returns text.', - '', - ...maintenanceFooter(maintenance), - ].join('\n') -} - function renderDocs(): GraphDoc[] { const pkgs = collectPackageGraph(root, GROUP_ORDER, 'gen-doc-graphs') const docs: GraphDoc[] = [ @@ -1076,7 +1081,6 @@ function renderDocs(): GraphDoc[] { { rel: 'docs/event-producer-consumer.md', content: renderEventRelations(pkgs) }, { rel: 'docs/agent-lifecycle.md', content: renderLifecycle() }, { rel: 'docs/tool-execution-pipeline.md', content: renderToolPipeline() }, - { rel: 'packages/ui/acp/snapshot-replay.md', content: renderSnapshotReplay() }, ] docs.unshift({ rel: 'docs/graph-atlas.md', content: renderIndex(docs) }) return docs @@ -1092,7 +1096,6 @@ function renderIndex(docs: GraphDoc[]): string { 'docs/event-producer-consumer.md': 'event producer/consumer matrix', 'docs/agent-lifecycle.md': 'agent turn and step lifecycle', 'docs/tool-execution-pipeline.md': 'tool execution pipeline', - 'packages/ui/acp/snapshot-replay.md': 'ACP snapshot replay', } const modes: Record<string, string> = { 'docs/capability-seams.md': 'hybrid generated', @@ -1103,7 +1106,6 @@ function renderIndex(docs: GraphDoc[]): string { 'docs/event-producer-consumer.md': 'hybrid generated', 'docs/agent-lifecycle.md': 'curated', 'docs/tool-execution-pipeline.md': 'curated', - 'packages/ui/acp/snapshot-replay.md': 'curated', } const rows = [ '| [module dependency graph](module-graph.md) | `generated` |', diff --git a/scripts/gen-module-graph.ts b/scripts/gen-module-graph.ts index f2d7514d23..0d1b16588f 100644 --- a/scripts/gen-module-graph.ts +++ b/scripts/gen-module-graph.ts @@ -38,6 +38,7 @@ const GROUP_ORDER = [ 'session-query', 'session-title', 'support', + 'acp', 'ui', ] diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index c2c619aa5d..6c81aee2c6 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -371,7 +371,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ await ctx.plugin(ToolTodo) }, note: - 'todo_write is session-owned state; UIs render the latest todo/write event as a checklist or ACP plan.', + 'todo_write is session-owned state; UIs render the latest todo/write event as a checklist.', }, { pkg: '@deepseek-ai/dsh-tool-workflow', diff --git a/scripts/project-doc-site.spec.ts b/scripts/project-doc-site.spec.ts index 7d1c3c1550..e6cc11ae6e 100644 --- a/scripts/project-doc-site.spec.ts +++ b/scripts/project-doc-site.spec.ts @@ -172,13 +172,13 @@ describe('rewriteMarkdown', () => { }) describe('docsPages locale routes', () => { - it('publishes every route in both locales and selects paired user sources', () => { + it('publishes every route in both locales and selects paired sources', () => { const byRoute = new Map(docsPages.map(page => [page.route, page])) for (const page of docsPages.filter(page => page.locale === 'root')) { const counterpart = byRoute.get(`en/${page.route}`) expect(counterpart, page.route).toBeDefined() expect(counterpart?.locale).toBe('en') - if (page.source.startsWith('docs/user/')) { + if (page.contentLocale === 'zh-CN') { expect(page.source).toMatch(/\.zh\.md$/) expect(page.contentLocale).toBe('zh-CN') expect(counterpart?.source).toBe(page.source.replace(/\.zh\.md$/, '.md')) @@ -190,6 +190,22 @@ describe('docsPages locale routes', () => { } }) + it('projects translated core-data pages while retaining explicit English fallbacks', () => { + const rootPages = docsPages.filter(page => ( + page.locale === 'root' && page.route.startsWith('reference/core-data-structures/') + )) + const translated = rootPages.filter(page => page.contentLocale === 'zh-CN') + const fallbacks = rootPages.filter(page => page.contentLocale === 'en-US') + + expect(translated).toHaveLength(18) + expect(translated.every(page => page.source.endsWith('.zh.md'))).toBe(true) + expect(fallbacks.map(page => page.source).sort()).toEqual([ + 'docs/core-data-structures/commands.md', + 'docs/core-data-structures/goal.md', + 'docs/core-data-structures/pty.md', + ]) + }) + it('publishes the Cordis core API under matching locale structures', () => { const files = ['context.md', 'events.md', 'fiber.md', 'registry.md', 'service.md'] for (const file of files) { diff --git a/scripts/snapshots/translation-prompt-v4/request-response.expected.json b/scripts/snapshots/translation-prompt-v4/request-response.expected.json index b0a3a3d526..fd9e0bec36 100644 --- a/scripts/snapshots/translation-prompt-v4/request-response.expected.json +++ b/scripts/snapshots/translation-prompt-v4/request-response.expected.json @@ -4,7 +4,7 @@ "messages": [ { "role": "system", - "content": "# Translation Prompt\n\nYou are a senior technical translator specializing in LLM and agent development documentation. Your task is to translate the given source document from English to Chinese, producing natural, professional technical prose.\n\n## Quality Requirements\n\n### Structure and Format Preservation\n- Output a complete translated document that maintains exactly the same structure as the source: heading hierarchy, list shape, table columns, link targets, and code blocks.\n- Fenced code blocks must be byte-identical to the source, including ALL comments inside them. Do NOT translate comments inside code blocks. This is a hard rule with no exceptions.\n- Inline code spans (commands, flags, paths, API names, version numbers) must be kept verbatim. Never translate or reformat them.\n- Every relative link must point to the same target as in the source. Link text is translated; link targets are not.\n- Language switcher line: when translating into Chinese, write `[English](source-filename.md) | 中文`. When translating into English, write `English | [中文](source-filename.zh.md)`. Do NOT copy the switcher line from the source file unchanged — you must flip the link direction.\n- After a closing bold marker `**`, insert a space before the next character when that character is a Latin letter, digit, or CJK ideograph. Never insert a space before any punctuation (full-width or half-width).\n\n### Tone and Style\n- The translation must read as if originally written in the target language by a native speaker. If an expression sounds like a word-for-word rendering from the source language, rephrase it.\n- Write in a professional, formal tone appropriate for developer documentation. Never use colloquial or casual expressions.\n- Use polite imperative forms where the text instructs the reader to do something.\n- Keep the author's register: concise stays concise, detailed stays detailed.\n\n### Sentence Structure\n- Break long sentences with commas or semicolons. Avoid run-on sentences.\n- Prefer active voice. Convert passive constructions to active if it reads more naturally.\n- Translate meaning, not words. Restructure sentences where the target language grammar requires it.\n- Do not invent words or expressions that do not exist in natural technical writing of the target language.\n\n### Word Choice\n- Prefer precise, formal vocabulary over casual or colloquial alternatives.\n- When multiple synonyms exist, choose the one most commonly used in professional technical documentation of the target language.\n- Avoid slang, internal jargon, or overly literal translations that would not be recognized by the general developer audience.\n- Do not use the same word to translate two different source-language terms that carry distinct meanings.\n- Avoid repeating the same verb in close proximity; vary word choice for readability.\n\n#### When translating into Chinese\n- When a number modifies a noun, always include a Chinese classifier or measure word (量词). For example: \"three-package seam\" → \"由三个包构成的 seam\", not \"三包 seam\".\n\n### Punctuation\n\n#### When translating into Chinese\n- Use full-width Chinese punctuation in prose: `,。:;?!()「」`.\n- Strongly prefer replacing all em-dashes (——) with colons, periods, commas, or parentheses. Keep an em-dash only if no other punctuation works at all.\n- Use enumeration commas (、) between parallel items, not regular commas.\n- List item endings: use semicolons or no punctuation. Do not end list items with commas.\n- Put one half-width space between Chinese text and Latin words/numbers.\n- For RFC 2119 keywords (MUST, MUST NOT, SHOULD, MAY), translate to the corresponding Chinese term (必须、禁止、应当、可以) and keep the SOURCE emphasis marker: plain source stays plain (必须), italic source stays italic (*必须*), and bold source stays bold (**必须**).\n\n#### When translating into English\n(To be added.)\n\n## Terminology\n\nA terminology table is provided below. Follow it strictly:\n- Render every listed term exactly as specified.\n- When the target language is Chinese, use the \"中文\" column. On first occurrence, write the \"首次出现\" value with its parenthetical gloss; on subsequent occurrences, write only the part before the parentheses.\n- When the target language is English, use the \"English\" column without a Chinese gloss; do not copy the \"中文\" or \"首次出现\" value into English prose.\n- If a term has already been glossed as part of a compound term, do not gloss it again when it appears alone later.\n- NEVER use translations listed in the \"不要译作\" column.\n- For technical terms not in the table, follow the target language: for a Chinese target, use an established Chinese rendering from a major Chinese-language OSS or vendor source, or keep the source term and flag it as pending when no such precedent exists; for an English target, use the established English technical term, or preserve an ambiguous source term with a short English gloss and flag it as pending. Do not invent a translation. This rule applies to terminology only; for general prose, freely restructure and paraphrase for natural expression.\n\n# Terminology\n\n本表约定本仓库的中英术语统一译法。\n\n**通用规则:**\n- \"中文\"列为中文译文的正文默认用词。若该列为英文,则中文译文的正文中保留英文不翻译。\n- 首次出现按\"首次出现\"列书写(带括号注释);后续出现只写括号前的部分(可能为中文,也可能为英文),不出现括号内的注释。\n- \"不要译作\"列为严格禁止的译法。\n- 如果某术语已经作为另一个术语的组成部分被括注过(如 `agent loop(智能体循环)` 中已包含 `agent` 的括注),则该术语后续单独出现时无需再次括注。\n\n## 缩写类(中英文文本中均使用缩写)\n\n| English | 中文 | 首次出现 | 不要译作 | 备注 |\n|---|---|---|---|---|\n| ACP | ACP | ACP(Agent Client Protocol) | | |\n| AI | AI | AI(人工智能) | | |\n| API | API | | | |\n| CI | CI | | | |\n| CLI | CLI | CLI(命令行界面) | | |\n| e2e | e2e | | | |\n| HMR | HMR | HMR(热模块替换) | | |\n| JSON Schema | JSON Schema | | | |\n| JSONL | JSONL | | | |\n| LLM | LLM | LLM(大语言模型) | | |\n| MCP | MCP | | | |\n| PR | PR | PR(Pull Request) | | |\n| RAG | RAG | RAG(检索增强生成) | | |\n| SDK | SDK | | | |\n| SSE | SSE | SSE(Server-Sent Events) | | |\n\n## 英文类(中英文文本中均使用英文)\n\n| English | 中文 | 首次出现 | 不要译作 | 备注 |\n|---|---|---|---|---|\n| agent | agent | agent(智能体) | | |\n| Agent Note | Agent Note | Agent Note(agent 决策记录) | 智能体注记、智能体笔记 | 本仓库中由 agent 撰写的提案与决策记录 |\n| agent harness | agent harness | agent harness(智能体框架) | | agent 组合词(agent harness/workflow/loop/skill 等)整体保留英文;未括注过 agent 时首现按对应组合词或 agent 行处理 |\n| agent loop | agent loop | agent loop(智能体循环) | | |\n| backlog | backlog | backlog(待翻清单) | | 仅在双语翻译语境里括注`待翻清单` |\n| blob hash | blob hash | | | `git hash-object` 的结果 |\n| Cordis | Cordis | | | |\n| dispose | dispose | dispose(资源释放) | | |\n| doc-sync | doc-sync | doc-sync(文档同步门禁) | | |\n| fiber | fiber | | | |\n| fixture | fixture | fixture(测试前置数据) | | |\n| fork | fork | | | |\n| Function Calling | Function Calling | Function Calling(函数调用) | | |\n| harness | harness | | | |\n| harness engineering | harness engineering | | | |\n| lint | lint | | | |\n| mock | mock | | | 保留英文;指测试替身 |\n| loader | loader | | | |\n| manifest | manifest | manifest(元数据清单) | | |\n| monorepo | monorepo | | | |\n| schema | schema | | | |\n| schema DSL | schema DSL | | | |\n| seam | seam | | | 与 `extension point` 是不同概念;根据具体语境,可译为`服务边界`或`可替换点` |\n| skill | skill | skill(技能) | | |\n| spawn | spawn | | | |\n| steering | steering | steering(中途引导) | | |\n| task id | task id | | 任务 id | 保留英文 |\n| subagent | subagent | | | |\n| thinking | thinking | | | API 字段保留英文;描述模型模式时译为`思考` |\n| transcript | transcript | transcript(文本记录) | | 指会话渲染给用户或编辑器的完整文本,区别于事件日志 |\n| waterfall | waterfall | waterfall(瀑布式事件) | | |\n| wheel | wheel 包 | | | Python 打包格式 |\n| worktree | worktree | | | git 工作区概念 |\n| Zstandard | Zstandard | | | RFC 8878 compression format; `zstd` remains a code value. |\n\n## 双语类(中英文文本各自使用中英文)\n\n| English | 中文 | 首次出现 | 不要译作 | 备注 |\n|---|---|---|---|---|\n| adapter | 适配器 | | | |\n| adapter contract | 适配器契约 | 适配器契约(adapter contract) | | |\n| append-only | 仅追加 | | | |\n| artifact | 产物 | | | |\n| backend | 后端 | | | |\n| background task | 后台任务 | | | |\n| block | 块 | | | |\n| build target | 构建目标 | | | |\n| cancel | 取消 | | | |\n| feature | 功能 | | 能力 | SDK 产品与工程模型中的可管理产品单元 |\n| feature option | 功能选项 | | variant | 一项 SDK 功能内有限、可选择的实现或配置 |\n| checkpoint | 检查点 | | | |\n| chunk | 分片 | | | |\n| compaction | 压缩 | 压缩(compaction) | | |\n| companion tool | 配套工具 | | | |\n| Cordis plugin config | Cordis 插件配置 | | | Cordis 插件公开的 `Config` 对象或配置结构 |\n| config key | 配置键 | | | Cordis 插件配置中的单个字段 |\n| consumer | 消费方 | | | |\n| content block | 内容块 | | | |\n| Cookbook | 实操手册 | | | 文档标题用语 |\n| context | 上下文 | | | |\n| counterpart | 对侧文件 | | 对应物、配对物 | 双语配对语境;泛指\"另一侧\"时可写「另一侧」 |\n| context compaction | 上下文压缩 | 上下文压缩(context compaction) | | |\n| contract | 契约 | | | 如:`pairing contract` →`配对契约` |\n| Cordis config entry | Cordis 配置项 | | | 指 `cordis.yml` 插件列表中的一项;插件实现本身写`Cordis 插件` |\n| Cordis plugin | Cordis 插件 | | | Cordis 加载的插件实现,不指 `cordis.yml` 中的一项配置 |\n| coverage | 覆盖率 | | | |\n| crash recovery | 崩溃恢复 | | | |\n| deploy root | 部署根目录 | | | |\n| durability | 持久性 | | | |\n| feature requirement | 功能依赖 | | | 功能或功能选项通过 `requires` 声明的关系 |\n| enforcement frontier | 执行红线 | | 强制边界 | i18n 配对机制用语:manifest `required` 清单所划的门禁生效范围;与金标样例(style-samples ⑦)一致 |\n| event | 事件 | | | |\n| event log | 事件日志 | | | |\n| event stream | 事件流 | | | |\n| event-sourced | 事件溯源 | | | 沿用 DDD 社区通行译法 |\n| executor | 执行器 | | | |\n| expected output | 预期输出 | | 金标 | 指 snapshot 比较产物;翻译语料的人工校准样例不在此列 |\n| extension | 扩展 | | | |\n| extension point | 扩展点 | | | 注意与 `seam` 区分 |\n| fail-fast | 快速失败 | | | |\n| fenced code block | 围栏代码块 | | | 沿用 MDN 中文翻译 |\n| fingerprint | 指纹 | | | 通用内容指纹;双语配对机制使用 sidecar record 记录两侧 blob hash |\n| finish reason | 结束原因 | | | |\n| foreground run | 前台运行 | | | |\n| freshness | 新鲜度 | | | 沿用 MDN 中文翻译;在本项目中指译文相对源文的同步状态 |\n| hook | 钩子 | | | |\n| implementation | 实现 | | | |\n| inference | 推理 | 推理(inference) | | 需要和 `reasoning` 区分时保留英文括注 |\n| info string | 信息字符串 | | | 沿用 CommonMark 中文翻译;指代码围栏 ``` 之后的语言标注 |\n| injection | 注入 | | | |\n| integration | 集成 | | | |\n| interface | 接口 | | | |\n| language switcher | 语言切换行 | | | i18n 配对机制用语:双语配对文件顶部的互链行 |\n| memory | 记忆 / 内存 | | | 与 `agent` 搭配时译为`记忆`(如 `agent memory` →`智能体记忆`);指系统资源时译为`内存` |\n| merge | 合并 | | | |\n| message | 消息 | | | |\n| mod | 模组 | | | |\n| model provider | 模型提供方 | | | |\n| module | 模块 | | | |\n| npm dependency | NPM 依赖 | | | `package.json` 中的包关系;`dependencies`、`devDependencies` 等字段保持原样 |\n| orphan | 遗留 | | 孤儿、孤立 | 指英文源已不存在的 `.zh.md`(如「遗留译文」);进程语境按 OS 惯用语译「孤儿进程」 |\n| orphan branch | 孤立分支 | | 孤儿分支 | 沿用 git 官方中文翻译 |\n| package | 包 | 包(package) | | 指 npm 包(`@deepseek-ai/dsh-*`);`package.json` 等代码标识保持原样 |\n| pairing | 配对 | | | |\n| peer dependency | 对等依赖 | 对等依赖(peer dependency) | | |\n| permission | 权限 | | | |\n| persistence | 持久化 | | | |\n| pipeline | 流水线 | | | |\n| plugin | 插件 | | | |\n| prompt | 提示词 | | | |\n| provider | 提供方 | | | |\n| provider-neutral | 提供方无关 | | | |\n| quality gate | 质量门禁 | | | |\n| reasoning | 推理 | 推理(reasoning) | | 需要和 `inference` 区分时保留英文括注 |\n| reasoning_content | 思考内容 | | | |\n| registry | 注册表 | | | |\n| replay | 回放 | | | |\n| resume | 恢复 | | | |\n| runtime | 运行时 | | | |\n| sandbox | 沙箱 | | | |\n| service | 服务 | | | |\n| serving surface | 对外服务接口 | | | |\n| session | 会话 | | | |\n| session event | 会话事件 | | | |\n| sidecar record | 伴随记录 | | 旁挂记录 | 指与文档同目录的伴随记录文件 |\n| smoke test | 冒烟测试 | | | |\n| snapshot | 快照 | | | |\n| source of truth | 真源 | | | |\n| spine | 主干 | | | |\n| staged | 暂存 | | | 沿用 git 官方中文翻译 |\n| stale | 陈旧 | | 过期 | 与 `fresh`(`新鲜`)成对;门禁输出中保留英文 `stale` 不翻译;`expired` 才译为`过期` |\n| step | 步骤 | | | |\n| stream | 流 | | | |\n| streaming | 流式输出 | | | |\n| structural signature | 结构签名 | | | i18n 配对机制用语:门禁比对两侧文件时提取的有序结构序列(标题层级、代码块、列表等) |\n| system prompt | 系统提示词 | | | |\n| taxonomy | 分类体系 | | | |\n| token usage | token 用量 | | | |\n| tool | 工具 | | | |\n| tool call | 工具调用 | | | |\n| tool result | 工具结果 | | | |\n| tool schema | 工具 schema | | | |\n| toolkit | 工具包 | | | |\n| turn | 轮次 | | | |\n| VFS | VFS | 虚拟文件系统(VFS) | | |\n| typecheck | 类型检查 | | | |\n| vocabulary | 词汇 | | | |\n| wire format | 协议格式 | 协议格式(wire format) | | |\n| workflow | 工作流 | | | |\n| wrapper | 包装层 | | | 软件层或 SDK 包装层 |\n| wrapper script | 包装脚本 | | | 可执行脚本包装层 |\n\n\n## Output Format\n\nProduce your output in three XML sections:\n\nThe outer section tags are framing. If Markdown inside any section body contains a line consisting only of `<translation>`, `</translation>`, `<review>`, `</review>`, `<final>`, or `</final>`, prefix that line with `\\`. If the original line already has one or more backslashes immediately before the tag, add one more. The parser removes exactly one framing escape; tags mentioned inline need no escaping.\n\n```xml\n<translation>\n(Complete translation of the source document)\n</translation>\n\n<review>\n(Self-review notes, one correction per line with category tag, e.g.)\n- [Tone] \"旁挂记录\" → \"伴随记录\"(生造词)\n- [Sentence] 第 3 段补充逗号断句\n- [Punctuation] 两处破折号替换为冒号\n- 无修正\n</review>\n\n<final>\n(Final translation after corrections)\n</final>\n```\n\n## Self-Review Instructions\n\nAfter writing `<translation>`, re-read it in the target language only, without looking at the source. Check by category:\n\n**Structure**\n- Is the heading hierarchy, list shape, and code block content identical to the source?\n- Are ALL comments inside code blocks left untranslated (byte-identical to source)?\n- Is the language switcher line correctly flipped (not copied from source)?\n- Are link targets preserved, and are spaces after bold markers present only before Latin letters, digits, or CJK ideographs?\n- Are wrapper-tag lines inside section bodies escaped with one additional backslash?\n\n**Tone & Style**\n- Does every sentence read as if originally written by a native speaker?\n- Is there any colloquial, casual, or overly informal phrasing?\n\n**Sentence Structure**\n- Are there run-on sentences that need breaking?\n- Are there stiff passive constructions that should be converted to active voice?\n\n**Word Choice**\n- Are there overly literal translations that sound unnatural?\n- Is the same target-language word used to translate two distinct source concepts?\n- Is any slang or internal jargon present?\n\n**Terminology**\n- For a Chinese target, are first-occurrence glosses correctly applied (not missing, not repeated)? For an English target, are Chinese glosses absent?\n- Are any \"不要译作\" forbidden translations present?\n- For unlisted terms, does a Chinese target use established Chinese precedent or retain the source term as pending, and does an English target use established English terminology or preserve only an ambiguous source term with a short English gloss?\n\n**Punctuation** (when target is Chinese)\n- Are there em-dashes that should be replaced with colons, periods, or commas?\n- Are list items ending with commas instead of semicolons?\n- Do RFC 2119 keywords preserve the source emphasis exactly?\n\nRecord corrections in `<review>` with category tags. Then output the corrected version in `<final>`. If no corrections are needed, write \"无修正\" in `<review>` and copy the translation unchanged into `<final>`.\n\n## Examples\n\nBelow are representative examples of common problems and their corrections. Follow the \"Good\" versions.\n\n### Colloquial verb → Professional verb\n- Source: `The repo pins pnpm@11.7.0 in package.json`\n- Bad: `仓库在 package.json 中钉住 pnpm@11.7.0`\n- Good: `该仓库在 package.json 中固定使用 pnpm@11.7.0`\n\n### Run-on sentence → Natural phrasing with pause\n- Source: `Read docs/architecture.md before changing anything under packages/.`\n- Bad: `改动 packages/ 下的任何东西之前先读 docs/architecture.md。`\n- Good: `在修改 packages/ 目录下的任何内容之前,请先阅读 docs/architecture.md。`\n\n### Stiff passive voice → Active and natural\n- Source: `a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.`\n- Bad: `门禁绿意味着这对文档曾在当前内容上被确认一致,不意味着这次确认本身是对的。`\n- Good: `门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。`\n\n### Invented word → Natural expression\n- Source: `A sidecar record of both blob hashes makes consistency checkable`\n- Bad: `旁挂记录两侧 blob hash,使一致性可检查`\n- Good: `伴随记录保存两侧 blob hash,使一致性可检查`\n\n### Em-dash → Colon/period\n- Source: `FIXME — an issue that should block a new release. A release should not ship with an open FIXME unless reviewers explicitly agree the change can be merged anyway.`\n- Bad: `FIXME——应当阻塞新版本发布的问题。除非评审者明确同意可以照常合入,发布不应带着未解决的 FIXME 出门。`\n- Good: `FIXME:应当阻塞新版本发布的问题。除非评审者明确同意该更改可以合并,否则发布版本不应包含未解决的 FIXME。`\n\n### Overly literal → Meaningful rendering\n- Source: `awkward phrasing is easier to hear without the source anchoring you`\n- Bad: `没有源文锚着,别扭的表述更容易被听出来`\n- Good: `不对照原文时,更容易察觉别扭的表达`\n\n### Terminology — do not translate what should be kept in English\n- Source: `typed service seams, and explicit extension points`\n- Bad: `类型化的服务 seam(扩展点)与显式扩展点`\n- Good: `类型化的服务 seam 与显式扩展点`\n\n### Slang/jargon → Professional phrasing\n- Source: `The committed agent workflow lives in .agents/skills/dsh-translate-docs`\n- Bad: `进仓的 agent 工作流见 .agents/skills/dsh-translate-docs`\n- Good: `仓库内置的 agent 工作流见 .agents/skills/dsh-translate-docs`\n\n### \"For humans\" — translate the intent, not the word\n- Source: `For humans, start with the development guide`\n- Bad: `对于人工读者,请先从开发指南开始`(\"人工读者\"生硬)\n- Good: `面向开发者:请先阅读开发指南`(\"开发者\"自然,且中文里冒号在此处更自然)\n\n### Code block comments — NEVER translate\n- Source code block contains: `# full-screen TUI coding agent (needs DEEPSEEK_API_KEY)`\n- Bad: `# 全屏 TUI coding agent(需要 DEEPSEEK_API_KEY)`\n- Good: `# full-screen TUI coding agent (needs DEEPSEEK_API_KEY)` (keep exactly as-is, byte-for-byte)\n\n### Language switcher — flip direction\n- Source file (English) has: `English | [中文](README.zh.md)`\n- Bad (copying source unchanged): `English | [中文](README.zh.md)`\n- Good (flipped for Chinese file): `[English](README.md) | 中文`\n\n---\n\nNow translate the following document:" + "content": "# Translation Prompt\n\nYou are a senior technical translator specializing in LLM and agent development documentation. Your task is to translate the given source document from English to Chinese, producing natural, professional technical prose.\n\n## Quality Requirements\n\n### Structure and Format Preservation\n- Output a complete translated document that maintains exactly the same structure as the source: heading hierarchy, list shape, table columns, link targets, and code blocks.\n- Fenced code blocks must be byte-identical to the source, including ALL comments inside them. Do NOT translate comments inside code blocks. This is a hard rule with no exceptions.\n- Inline code spans (commands, flags, paths, API names, version numbers) must be kept verbatim. Never translate or reformat them.\n- Every relative link must point to the same target as in the source. Link text is translated; link targets are not.\n- Language switcher line: when translating into Chinese, write `[English](source-filename.md) | 中文`. When translating into English, write `English | [中文](source-filename.zh.md)`. Do NOT copy the switcher line from the source file unchanged — you must flip the link direction.\n- After a closing bold marker `**`, insert a space before the next character when that character is a Latin letter, digit, or CJK ideograph. Never insert a space before any punctuation (full-width or half-width).\n\n### Tone and Style\n- The translation must read as if originally written in the target language by a native speaker. If an expression sounds like a word-for-word rendering from the source language, rephrase it.\n- Write in a professional, formal tone appropriate for developer documentation. Never use colloquial or casual expressions.\n- Use polite imperative forms where the text instructs the reader to do something.\n- Keep the author's register: concise stays concise, detailed stays detailed.\n\n### Sentence Structure\n- Break long sentences with commas or semicolons. Avoid run-on sentences.\n- Prefer active voice. Convert passive constructions to active if it reads more naturally.\n- Translate meaning, not words. Restructure sentences where the target language grammar requires it.\n- Do not invent words or expressions that do not exist in natural technical writing of the target language.\n\n### Word Choice\n- Prefer precise, formal vocabulary over casual or colloquial alternatives.\n- When multiple synonyms exist, choose the one most commonly used in professional technical documentation of the target language.\n- Avoid slang, internal jargon, or overly literal translations that would not be recognized by the general developer audience.\n- Do not use the same word to translate two different source-language terms that carry distinct meanings.\n- Avoid repeating the same verb in close proximity; vary word choice for readability.\n\n#### When translating into Chinese\n- When a number modifies a noun, always include a Chinese classifier or measure word (量词). For example: \"three-package seam\" → \"由三个包构成的 seam\", not \"三包 seam\".\n\n### Punctuation\n\n#### When translating into Chinese\n- Use full-width Chinese punctuation in prose: `,。:;?!()「」`.\n- Strongly prefer replacing all em-dashes (——) with colons, periods, commas, or parentheses. Keep an em-dash only if no other punctuation works at all.\n- Use enumeration commas (、) between parallel items, not regular commas.\n- List item endings: use semicolons or no punctuation. Do not end list items with commas.\n- Put one half-width space between Chinese text and Latin words/numbers.\n- For RFC 2119 keywords (MUST, MUST NOT, SHOULD, MAY), translate to the corresponding Chinese term (必须、禁止、应当、可以) and keep the SOURCE emphasis marker: plain source stays plain (必须), italic source stays italic (*必须*), and bold source stays bold (**必须**).\n\n#### When translating into English\n(To be added.)\n\n## Terminology\n\nA terminology table is provided below. Follow it strictly:\n- Render every listed term exactly as specified.\n- When the target language is Chinese, use the \"中文\" column. On first occurrence, write the \"首次出现\" value with its parenthetical gloss; on subsequent occurrences, write only the part before the parentheses.\n- When the target language is English, use the \"English\" column without a Chinese gloss; do not copy the \"中文\" or \"首次出现\" value into English prose.\n- If a term has already been glossed as part of a compound term, do not gloss it again when it appears alone later.\n- NEVER use translations listed in the \"不要译作\" column.\n- For technical terms not in the table, follow the target language: for a Chinese target, use an established Chinese rendering from a major Chinese-language OSS or vendor source, or keep the source term and flag it as pending when no such precedent exists; for an English target, use the established English technical term, or preserve an ambiguous source term with a short English gloss and flag it as pending. Do not invent a translation. This rule applies to terminology only; for general prose, freely restructure and paraphrase for natural expression.\n\n# Terminology\n\n本表约定本仓库的中英术语统一译法。\n\n**通用规则:**\n- \"中文\"列为中文译文的正文默认用词。若该列为英文,则中文译文的正文中保留英文不翻译。\n- 首次出现按\"首次出现\"列书写(带括号注释);后续出现只写括号前的部分(可能为中文,也可能为英文),不出现括号内的注释。\n- \"不要译作\"列为严格禁止的译法。\n- 如果某术语已经作为另一个术语的组成部分被括注过(如 `agent loop(智能体循环)` 中已包含 `agent` 的括注),则该术语后续单独出现时无需再次括注。\n\n## 缩写类(中英文文本中均使用缩写)\n\n| English | 中文 | 首次出现 | 不要译作 | 备注 |\n|---|---|---|---|---|\n| ACP | ACP | ACP(Agent Client Protocol) | | |\n| AI | AI | AI(人工智能) | | |\n| API | API | | | |\n| CI | CI | | | |\n| CLI | CLI | CLI(命令行界面) | | |\n| e2e | e2e | | | |\n| HMR | HMR | HMR(热模块替换) | | |\n| JSON Schema | JSON Schema | | | |\n| JSONL | JSONL | | | |\n| LLM | LLM | LLM(大语言模型) | | |\n| MCP | MCP | | | |\n| PR | PR | PR(Pull Request) | | |\n| RAG | RAG | RAG(检索增强生成) | | |\n| SDK | SDK | | | |\n| SSE | SSE | SSE(Server-Sent Events) | | |\n\n## 英文类(中英文文本中均使用英文)\n\n| English | 中文 | 首次出现 | 不要译作 | 备注 |\n|---|---|---|---|---|\n| agent | agent | agent(智能体) | | |\n| Agent Note | Agent Note | Agent Note(agent 决策记录) | 智能体注记、智能体笔记 | 本仓库中由 agent 撰写的提案与决策记录 |\n| agent harness | agent harness | agent harness(智能体框架) | | agent 组合词(agent harness/workflow/loop/skill 等)整体保留英文;未括注过 agent 时首现按对应组合词或 agent 行处理 |\n| agent loop | agent loop | agent loop(智能体循环) | | |\n| backlog | backlog | backlog(待翻清单) | | 仅在双语翻译语境里括注`待翻清单` |\n| blob hash | blob hash | | | `git hash-object` 的结果 |\n| Cordis | Cordis | | | |\n| dispose | dispose | dispose(资源释放) | | |\n| doc-sync | doc-sync | doc-sync(文档同步门禁) | | |\n| fiber | fiber | | | |\n| fixture | fixture | fixture(测试前置数据) | | |\n| fork | fork | | | |\n| Function Calling | Function Calling | Function Calling(函数调用) | | |\n| harness | harness | | | |\n| harness engineering | harness engineering | | | |\n| lint | lint | | | |\n| mock | mock | | | 保留英文;指测试替身 |\n| loader | loader | | | |\n| manifest | manifest | manifest(元数据清单) | | |\n| monorepo | monorepo | | | |\n| Round | Round | | 回合、目标回合、Ralph 回合 | 外层策略使用 Round 时,领域层级为 Session > Round > Turn(轮次) > Step(步骤);Round 是可选的外层策略迭代,并非每个会话轮次都具有的通用层级。Goal Round 与 Ralph Round 均保留英文。一个 Round 承载一个轮次,步骤隶属于该轮次;明确的零步骤轮次仍保持原义。 |\n| schema | schema | | | |\n| schema DSL | schema DSL | | | |\n| seam | seam | | | 与 `extension point` 是不同概念;根据具体语境,可译为`服务边界`或`可替换点` |\n| skill | skill | skill(技能) | | |\n| spawn | spawn | | | |\n| steering | steering | steering(中途引导) | | |\n| task id | task id | | 任务 id | 保留英文 |\n| subagent | subagent | | | |\n| thinking | thinking | | | API 字段保留英文;描述模型模式时译为`思考` |\n| transcript | transcript | transcript(文本记录) | | 指会话渲染给用户或编辑器的完整文本,区别于事件日志 |\n| waterfall | waterfall | waterfall(瀑布式事件) | | |\n| wheel | wheel 包 | | | Python 打包格式 |\n| worktree | worktree | | | git 工作区概念 |\n| Zstandard | Zstandard | | | RFC 8878 compression format; `zstd` remains a code value. |\n\n## 双语类(中英文文本各自使用中英文)\n\n| English | 中文 | 首次出现 | 不要译作 | 备注 |\n|---|---|---|---|---|\n| adapter | 适配器 | | | |\n| adapter contract | 适配器契约 | 适配器契约(adapter contract) | | |\n| append-only | 仅追加 | | | |\n| artifact | 产物 | | | |\n| backend | 后端 | | | |\n| background task | 后台任务 | | | |\n| block | 块 | | | |\n| build target | 构建目标 | | | |\n| cancel | 取消 | | | |\n| feature | 功能 | | 能力 | SDK 产品与工程模型中的可管理产品单元 |\n| feature option | 功能选项 | | variant | 一项 SDK 功能内有限、可选择的实现或配置 |\n| checkpoint | 检查点 | | | |\n| chunk | 分片 | | | |\n| compaction | 压缩 | 压缩(compaction) | | |\n| companion tool | 配套工具 | | | |\n| Cordis plugin config | Cordis 插件配置 | | | Cordis 插件公开的 `Config` 对象或配置结构 |\n| config key | 配置键 | | | Cordis 插件配置中的单个字段 |\n| consumer | 消费方 | | | |\n| content block | 内容块 | | | |\n| Cookbook | 实操手册 | | | 文档标题用语 |\n| context | 上下文 | | | |\n| counterpart | 对侧文件 | | 对应物、配对物 | 双语配对语境;泛指\"另一侧\"时可写「另一侧」 |\n| context compaction | 上下文压缩 | 上下文压缩(context compaction) | | |\n| contract | 契约 | | | 如:`pairing contract` →`配对契约` |\n| Cordis config entry | Cordis 配置项 | | | 指 `cordis.yml` 插件列表中的一项;插件实现本身写`Cordis 插件` |\n| Cordis plugin | Cordis 插件 | | | Cordis 加载的插件实现,不指 `cordis.yml` 中的一项配置 |\n| coverage | 覆盖率 | | | |\n| crash recovery | 崩溃恢复 | | | |\n| deploy root | 部署根目录 | | | |\n| durability | 持久性 | | | |\n| feature requirement | 功能依赖 | | | 功能或功能选项通过 `requires` 声明的关系 |\n| enforcement frontier | 执行红线 | | 强制边界 | i18n 配对机制用语:manifest `required` 清单所划的门禁生效范围;与金标样例(style-samples ⑦)一致 |\n| ergonomics | 易用性 / 开发体验 | | 人体工学 | API 或面向模型的接口用「易用性」;工具链或开发者工作流用「开发体验」 |\n| event | 事件 | | | |\n| event log | 事件日志 | | | |\n| event stream | 事件流 | | | |\n| event-sourced | 事件溯源 | | | 沿用 DDD 社区通行译法 |\n| Executive summary | 摘要 | | | 事故复盘标题用语 |\n| executor | 执行器 | | | |\n| expected output | 预期输出 | | 金标 | 指 snapshot 比较产物;翻译语料的人工校准样例不在此列 |\n| extension | 扩展 | | | |\n| extension point | 扩展点 | | | 注意与 `seam` 区分 |\n| fail-fast | 快速失败 | | | |\n| fenced code block | 围栏代码块 | | | 沿用 MDN 中文翻译 |\n| fingerprint | 指纹 | | | 通用内容指纹;双语配对机制使用 sidecar record 记录两侧 blob hash |\n| finish reason | 结束原因 | | | |\n| foreground run | 前台运行 | | | |\n| freshness | 新鲜度 | | | 沿用 MDN 中文翻译;在本项目中指译文相对源文的同步状态 |\n| hook | 钩子 | | | |\n| implementation | 实现 | | | |\n| inference | 推理 | 推理(inference) | | 需要和 `reasoning` 区分时保留英文括注 |\n| info string | 信息字符串 | | | 沿用 CommonMark 中文翻译;指代码围栏 ``` 之后的语言标注 |\n| injection | 注入 | | | |\n| integration | 集成 | | | |\n| interface | 接口 | | | |\n| language switcher | 语言切换行 | | | i18n 配对机制用语:双语配对文件顶部的互链行 |\n| memory | 记忆 / 内存 | | | 与 `agent` 搭配时译为`记忆`(如 `agent memory` →`智能体记忆`);指系统资源时译为`内存` |\n| merge | 合并 | | | |\n| message | 消息 | | | |\n| mod | 模组 | | | |\n| model provider | 模型提供方 | | | |\n| module | 模块 | | | |\n| non-escalation | 非升权 | | 非升级、不可升级 | 仅用于安全与权限语境,指主体不得获得超出既有授权的权限;普通升级不适用此行 |\n| npm dependency | NPM 依赖 | | | `package.json` 中的包关系;`dependencies`、`devDependencies` 等字段保持原样 |\n| opt-out ratio | opt-out 比例 | | 退出检查比例 | |\n| orphan | 遗留 | | 孤儿、孤立 | 指英文源已不存在的 `.zh.md`(如「遗留译文」);进程语境按 OS 惯用语译「孤儿进程」 |\n| orphan branch | 孤立分支 | | 孤儿分支 | 沿用 git 官方中文翻译 |\n| package | 包 | 包(package) | | 指 npm 包(`@deepseek-ai/dsh-*`);`package.json` 等代码标识保持原样 |\n| pairing | 配对 | | | |\n| parent-subset grants | 父级子集授权 | | 父集合授权 | 指授权范围仅限于父级所持授权的子集 |\n| peer dependency | 对等依赖 | 对等依赖(peer dependency) | | |\n| permission | 权限 | | | |\n| persistence | 持久化 | | | |\n| pipeline | 流水线 | | | |\n| plugin | 插件 | | | |\n| prompt | 提示词 | | | |\n| provider | 提供方 | | | |\n| provider-neutral | 提供方无关 | | | |\n| quality gate | 质量门禁 | | | |\n| quiescence | 完全停稳 | | 静默、静止状态 | 指生命周期工作全部结算后的状态 |\n| reasoning | 推理 | 推理(reasoning) | | 需要和 `inference` 区分时保留英文括注 |\n| reasoning_content | 思考内容 | | | |\n| registry | 注册表 | | | |\n| replay | 回放 | | | |\n| resume | 恢复 | | | |\n| runtime | 运行时 | | | |\n| same-world subprocess | 与宿主共享文件系统和内核的子进程 | | 同世界子进程 | |\n| sandbox | 沙箱 | | | |\n| service | 服务 | | | |\n| serving surface | 对外服务接口 | | | |\n| session | 会话 | | | |\n| session event | 会话事件 | | | |\n| sidecar record | 伴随记录 | | 旁挂记录 | 指与文档同目录的伴随记录文件 |\n| smoke test | 冒烟测试 | | | |\n| snapshot | 快照 | | | |\n| source of truth | 真源 | | | |\n| spine | 主干 | | | |\n| staged | 暂存 | | | 沿用 git 官方中文翻译 |\n| stale | 陈旧 | | 过期 | 与 `fresh`(`新鲜`)成对;门禁输出中保留英文 `stale` 不翻译;`expired` 才译为`过期` |\n| step | 步骤 | | | |\n| stream | 流 | | | |\n| streaming | 流式输出 | | | |\n| structural signature | 结构签名 | | | i18n 配对机制用语:门禁比对两侧文件时提取的有序结构序列(标题层级、代码块、列表等) |\n| Summary | 概述 | | | 事故复盘标题用语 |\n| system prompt | 系统提示词 | | | |\n| taxonomy | 分类体系 | | | |\n| token usage | token 用量 | | | |\n| tool | 工具 | | | |\n| tool call | 工具调用 | | | |\n| tool result | 工具结果 | | | |\n| tool schema | 工具 schema | | | |\n| toolkit | 工具包 | | | |\n| turn | 轮次 | | | |\n| VFS | VFS | 虚拟文件系统(VFS) | | |\n| typecheck | 类型检查 | | | |\n| vocabulary | 词汇 | | | |\n| wire format | 协议格式 | 协议格式(wire format) | | |\n| workflow | 工作流 | | | |\n| wrapper | 包装层 | | | 软件层或 SDK 包装层 |\n| wrapper script | 包装脚本 | | | 可执行脚本包装层 |\n\n\n## Output Format\n\nProduce your output in three XML sections:\n\nThe outer section tags are framing. If Markdown inside any section body contains a line consisting only of `<translation>`, `</translation>`, `<review>`, `</review>`, `<final>`, or `</final>`, prefix that line with `\\`. If the original line already has one or more backslashes immediately before the tag, add one more. The parser removes exactly one framing escape; tags mentioned inline need no escaping.\n\n```xml\n<translation>\n(Complete translation of the source document)\n</translation>\n\n<review>\n(Self-review notes, one correction per line with category tag, e.g.)\n- [Tone] \"旁挂记录\" → \"伴随记录\"(生造词)\n- [Sentence] 第 3 段补充逗号断句\n- [Punctuation] 两处破折号替换为冒号\n- 无修正\n</review>\n\n<final>\n(Final translation after corrections)\n</final>\n```\n\n## Self-Review Instructions\n\nAfter writing `<translation>`, re-read it in the target language only, without looking at the source. Check by category:\n\n**Structure**\n- Is the heading hierarchy, list shape, and code block content identical to the source?\n- Are ALL comments inside code blocks left untranslated (byte-identical to source)?\n- Is the language switcher line correctly flipped (not copied from source)?\n- Are link targets preserved, and are spaces after bold markers present only before Latin letters, digits, or CJK ideographs?\n- Are wrapper-tag lines inside section bodies escaped with one additional backslash?\n\n**Tone & Style**\n- Does every sentence read as if originally written by a native speaker?\n- Is there any colloquial, casual, or overly informal phrasing?\n\n**Sentence Structure**\n- Are there run-on sentences that need breaking?\n- Are there stiff passive constructions that should be converted to active voice?\n\n**Word Choice**\n- Are there overly literal translations that sound unnatural?\n- Is the same target-language word used to translate two distinct source concepts?\n- Is any slang or internal jargon present?\n\n**Terminology**\n- For a Chinese target, are first-occurrence glosses correctly applied (not missing, not repeated)? For an English target, are Chinese glosses absent?\n- Are any \"不要译作\" forbidden translations present?\n- For unlisted terms, does a Chinese target use established Chinese precedent or retain the source term as pending, and does an English target use established English terminology or preserve only an ambiguous source term with a short English gloss?\n\n**Punctuation** (when target is Chinese)\n- Are there em-dashes that should be replaced with colons, periods, or commas?\n- Are list items ending with commas instead of semicolons?\n- Do RFC 2119 keywords preserve the source emphasis exactly?\n\nRecord corrections in `<review>` with category tags. Then output the corrected version in `<final>`. If no corrections are needed, write \"无修正\" in `<review>` and copy the translation unchanged into `<final>`.\n\n## Examples\n\nBelow are representative examples of common problems and their corrections. Follow the \"Good\" versions.\n\n### Colloquial verb → Professional verb\n- Source: `The repo pins pnpm@11.7.0 in package.json`\n- Bad: `仓库在 package.json 中钉住 pnpm@11.7.0`\n- Good: `该仓库在 package.json 中固定使用 pnpm@11.7.0`\n\n### Run-on sentence → Natural phrasing with pause\n- Source: `Read docs/architecture.md before changing anything under packages/.`\n- Bad: `改动 packages/ 下的任何东西之前先读 docs/architecture.md。`\n- Good: `在修改 packages/ 目录下的任何内容之前,请先阅读 docs/architecture.md。`\n\n### Stiff passive voice → Active and natural\n- Source: `a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.`\n- Bad: `门禁绿意味着这对文档曾在当前内容上被确认一致,不意味着这次确认本身是对的。`\n- Good: `门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。`\n\n### Invented word → Natural expression\n- Source: `A sidecar record of both blob hashes makes consistency checkable`\n- Bad: `旁挂记录两侧 blob hash,使一致性可检查`\n- Good: `伴随记录保存两侧 blob hash,使一致性可检查`\n\n### Em-dash → Colon/period\n- Source: `FIXME — an issue that should block a new release. A release should not ship with an open FIXME unless reviewers explicitly agree the change can be merged anyway.`\n- Bad: `FIXME——应当阻塞新版本发布的问题。除非评审者明确同意可以照常合入,发布不应带着未解决的 FIXME 出门。`\n- Good: `FIXME:应当阻塞新版本发布的问题。除非评审者明确同意该更改可以合并,否则发布版本不应包含未解决的 FIXME。`\n\n### Overly literal → Meaningful rendering\n- Source: `awkward phrasing is easier to hear without the source anchoring you`\n- Bad: `没有源文锚着,别扭的表述更容易被听出来`\n- Good: `不对照原文时,更容易察觉别扭的表达`\n\n### Terminology — do not translate what should be kept in English\n- Source: `typed service seams, and explicit extension points`\n- Bad: `类型化的服务 seam(扩展点)与显式扩展点`\n- Good: `类型化的服务 seam 与显式扩展点`\n\n### Slang/jargon → Professional phrasing\n- Source: `The committed agent workflow lives in .agents/skills/dsh-translate-docs`\n- Bad: `进仓的 agent 工作流见 .agents/skills/dsh-translate-docs`\n- Good: `仓库内置的 agent 工作流见 .agents/skills/dsh-translate-docs`\n\n### \"For humans\" — translate the intent, not the word\n- Source: `For humans, start with the development guide`\n- Bad: `对于人工读者,请先从开发指南开始`(\"人工读者\"生硬)\n- Good: `面向开发者:请先阅读开发指南`(\"开发者\"自然,且中文里冒号在此处更自然)\n\n### Code block comments — NEVER translate\n- Source code block contains: `# full-screen TUI coding agent (needs DEEPSEEK_API_KEY)`\n- Bad: `# 全屏 TUI coding agent(需要 DEEPSEEK_API_KEY)`\n- Good: `# full-screen TUI coding agent (needs DEEPSEEK_API_KEY)` (keep exactly as-is, byte-for-byte)\n\n### Language switcher — flip direction\n- Source file (English) has: `English | [中文](README.zh.md)`\n- Bad (copying source unchanged): `English | [中文](README.zh.md)`\n- Good (flipped for Chinese file): `[English](README.md) | 中文`\n\n---\n\nNow translate the following document:" }, { "role": "user", @@ -16,19 +16,19 @@ }, { "role": "user", - "content": "# Development guide\n\nEnglish | [中文](development.zh.md)\n\nThis onboarding guide helps project contributors get started with the local environment, daily workflow, and CI flow; see the Agent Notes for design rationale and technical trade-offs.\n\n## Prerequisites\n\n- Node.js supports 22.19+ and 24+. CI covers 22.19, 24, and 26; see the [Node engine floor Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md).\n- Corepack-enabled pnpm. The repo pins `pnpm@11.7.0` in `package.json`; run `corepack enable` if `pnpm --version` does not resolve through Corepack.\n- Git.\n- Optional: a DeepSeek API key for the TUI/Headless/ACP agent demos and real-API e2e tests.\n\n## First-time setup\n\nInstall dependencies from the repo root:\n\n```sh\npnpm install\n```\n\nThe install also runs the root `postinstall` script, which installs lefthook from the repo dev dependency through `scripts/install-lefthook.mjs`; the wrapper script uses lefthook's reviewed `--force` mode so linked worktrees with an existing `core.hooksPath` do not fail normal `pnpm run …` commands.\n\nIf hooks are missing because dependencies were restored from cache or `postinstall` was skipped, install them manually:\n\n```sh\npnpm exec lefthook install --force\n```\n\nRun typecheck once after a fresh clone:\n\n```sh\npnpm run typecheck\n```\n\nThat first typecheck runs the whole-repo `tsc -b` graph: it emits every package/vendor `lib/types` and checks examples, tests, and scripts through the two no-emit aggregates described below.\n\n## TypeScript project layout\n\nThe repository's TypeScript configuration has exactly three roles; every tsconfig file plays one of them.\n\n| File | Role | Forms a program? |\n|---|---|---|\n| `tsconfig.json` | Solution root: `extends` base, `files: []`, references to the two aggregates. The whole-repo `tsc -b tsconfig.json` graph, the tsserver discovery entry, and — through the inherited `paths` — the resolution config for tsx running `examples/` and `scripts/` (their nearest tsconfig is this file). | No |\n| `tsconfig.host.json` | Host aggregate: host-side packages (via references), examples, tests, scripts, website. Excludes `packages/client`. | Yes |\n| `tsconfig.client.json` | Client aggregate: `packages/client/*` packages and their tests, `apps/web`. | Yes |\n| `tsconfig.base.json` | Shared compilerOptions and the source `paths` map. Also the resolution facade the vitest configs point vite-tsconfig-paths at: it has no `include`, so its `paths` apply to every importer. | No |\n| `tsconfig.base.client.json` | Browser compiler shape (`jsx`, DOM libs, `types: []`) extended by the client aggregate and every `packages/client/*` package. | No |\n\nHost and client stay two aggregate programs because both sides declaration-merge the cordis `Context` interface under the same keys with different services; one program seeing both merges reports a collision. The collision exists only inside a `ts.Program` — module resolution never triggers it — which is why the solution may reference both aggregates and one paths facade may span both sides. Two disciplines follow:\n\n- `tsconfig.base.json` never gains `include` or `files`: they would leak into every extending package project and narrow the facade's match-all scope.\n- A script that builds a repo-wide `ts.Program` seeds `tsconfig.host.json` or `tsconfig.client.json` explicitly — never the root solution, because flattening both aggregates into one program collides the `Context` merges. Program-backed generators and gates (`scripts/ts-project.ts` consumers, doc-typecheck standalone mode) are host-only by decision; the client side gains program-backed tooling only with a concrete need.\n\nStatic analysis and tests resolve workspace imports through the base `paths` map to `src` and must pass on a clean tree; gates that consume built `lib/` output declare that dependency explicitly. Decision record: [solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md); the tsc-first emit pipeline is the [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md).\n\nIf a relevant local check consumes built package output, build once first:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` includes `publint`, which validates package entrypoints against the built `lib/*.js` files, and `verify-node-next-types`, which validates built declarations against a temporary NodeNext consumer. A fresh worktree has no bundled JS or declarations until `pnpm run build` runs; ordinary commits and pushes do not require that build unless their selected checks consume it.\n\n## Environment variables\n\nThe real DeepSeek adapter and key-backed agent demos read credentials from the environment or from a gitignored `.env` at the repo root:\n\n```sh\nDEEPSEEK_API_KEY=sk-...\nDEEPSEEK_BASE_URL=https://... # optional\n```\n\n`DEEPSEEK_BASE_URL` is optional and defaults to the public API. Never commit real credentials. The real-API e2e suites self-skip when `DEEPSEEK_API_KEY` is not set.\n\n## Git hooks\n\nlefthook is configured in `lefthook.yml` as a fast local checkpoint:\n\n- `pre-commit` runs staged-file ESLint fixes, checks the staged diff for whitespace errors, and runs the vendor manifest guard.\n- `pre-push` runs only the incremental repository typecheck (`tsc -b` over the root solution, covering both the host and client aggregates).\n\nThe vendor manifest guard checks that changes under `vendor/*/src` are staged with the matching `vendor/README.md` manifest update. See `vendor/README.md` before editing vendored code.\n\nThe hooks intentionally do not run tests, snapshots, documentation checks, builds, or hygiene. Contributors run the [checks relevant to the changed behavior](../AGENTS.md#run-relevant-checks-locally) once; CI owns exhaustive coverage, built-artifact smokes, and the Node 22.19, 24, and 26 compatibility matrix.\n\nContributors can opt into the comprehensive local gate set with `pnpm run check:all`. The command is independent of both Git hooks and is not an agent instruction.\n\n## CI gates\n\nThe keyless [CI workflow](../.github/workflows/ci.yml) groups independent gates into broad lanes and runs a smaller compatibility signal across supported Node versions. Artifact consumers wait for one build within their lane. The separate real-API workflow runs `pnpm run test:e2e` with its configured worker bound. See [scripts/run-gates.ts](../scripts/run-gates.ts) and the workflow files for the current gate and job inventory.\n\n## Daily commands\n\nUse these from the repo root:\n\n```sh\npnpm run test # unit tests\npnpm run test:coverage # unit tests with per-file coverage gates\npnpm run test:e2e # real-API tests; self-skips without DEEPSEEK_API_KEY\npnpm run check:all # comprehensive opt-in gate set; not wired to Git hooks\npnpm run typecheck # tsc -b over the root solution: emits package/vendor lib/types, checks both aggregates\npnpm run lint # eslint .\npnpm run lint:fix # eslint . --fix\npnpm run doc-typecheck # compile checked TypeScript snippets in Markdown docs\npnpm run gen-cordis-catalog # regenerate docs/cordis-catalog/events.md + services.md from source\npnpm run verify-cordis-catalog # fail if either cordis catalog is stale\npnpm run verify-export-jsdoc # fail if a module-level package export lacks complete JSDoc\npnpm run gen-doc-graphs # regenerate generated relationship docs from source and curated graph definitions\npnpm run verify-doc-graphs # fail if generated relationship docs are stale\npnpm run verify-md-wrap # fail on hard-wrapped prose paragraphs in docs/README markdown\npnpm run verify-mermaid # fail if a ```mermaid diagram has invalid Mermaid syntax\npnpm run verify-type-equiv # fail if a ```ts type-equiv doc block drifts from its source type\npnpm run verify-doc-budgets # fail if a budgeted standing doc exceeds its word ceiling\npnpm run doc-sync # all Markdown/doc gates, scheduled concurrently; the doc-sync leaf list in scripts/run-gates.ts is the full list\npnpm run gen-module-graph # regenerate docs/module-graph.md from package peerDeps\npnpm run verify-module-graph # fail if docs/module-graph.md is stale\npnpm run build # emit lib/types intermediates, then bundle lib/index.* runtime files\npnpm run verify-node-next-types # fail if built declarations are not NodeNext-consumable\npnpm run hygiene # knip, publint, workspace constraints, and NodeNext declaration check\n```\n\nWhen changing package public behavior, update the relevant README or JSDoc in the same change. `pnpm run doc-sync` catches checked TypeScript snippets, generated doc freshness, markdown wrap/link drift, type equivalence, translation pairing, Mermaid syntax, and doc budgets, but broader prose/API sync still needs review.\n\n## Demos\n\nThe one-shot Headless coding agent needs `DEEPSEEK_API_KEY` in the environment or repo-root `.env`:\n\n```sh\npnpm run demo:headless \"summarize this workspace\"\n```\n\nThe full-screen interactive coding agent needs `DEEPSEEK_API_KEY` in the environment or repo-root `.env`:\n\n```sh\npnpm run demo:tui\n```\n\nThe self-referential cordis-agent demo can inspect and modify its live plugin runtime and needs the same credentials:\n\n```sh\npnpm run demo:cordis\n```\n\nThe ACP server agent demo exposes the agent over JSON-RPC stdio and also needs `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:acp\n```\n\n## TODO markers\n\nUse one of three comment tags to flag known issues in the code, ordered by urgency:\n\n- `FIXME` — an issue that should block a new release. A release should not ship with an open `FIXME` unless reviewers explicitly agree the change can be merged anyway.\n- `TODO` — an issue that should be fixed soon, once we have the resources.\n- `XXX` — an issue that we may fix someday; lowest priority, no commitment.\n\nPick the tag that matches the urgency so anyone scanning the code can tell a release blocker from a someday-maybe.\n\n## Documenting types verbatim (`ts type-equiv`)\n\nThe [core data structures](core-data-structures/core.md) docs paste source-equivalent declarations together with their original JSDoc so a reader sees the exact shape and source contract. To keep a paste from drifting when source changes, fence it as ` ```ts type-equiv ` (instead of ` ```ts `) and register it in `scripts/type-equiv.manifest.json` with the source file and symbol it mirrors:\n\n```json\n{ \"doc\": \"docs/core-data-structures/session.md\", \"symbol\": \"SessionEvent\", \"source\": \"packages/core/session/src/types.ts\" }\n```\n\n`pnpm run verify-type-equiv` (part of `doc-sync`) then extracts that symbol's declaration and attached JSDoc from source via the TypeScript parser and asserts the block matches both. For a class whose implementation bodies do not belong in the catalog, use ` ```ts public-api ` and set `\"projection\": \"public-api\"`; the checked projection retains the public fields, constructor, accessors, methods, and original class/member JSDoc while omitting bodies and private or protected members. Comparison ignores whitespace and non-JSDoc comments but requires every original JSDoc comment, including member documentation, so readers see the source contract beside the exact shape. The gate also enforces a 1:1 correspondence by document, symbol, and projection, so a block can't go silently unchecked and a stale entry can't linger. `doc-typecheck` skips both fence kinds (they aren't standalone-compilable) and excludes them from its opt-out ratio. When you change a documented declaration or its JSDoc, the gate fails until you update the paste; when you add or remove a block, update the manifest in the same change.\n\n## Architecture context\n\nRead `docs/architecture.md` before changing anything under `packages/`. The codebase is built around Cordis plugins, event-sourced sessions, typed service seams, and explicit extension points.\n" + "content": "# Development guide\n\nEnglish | [中文](development.zh.md)\n\nThis onboarding guide helps project contributors get started with the local environment, daily workflow, and CI flow; see the Agent Notes for design rationale and technical trade-offs.\n\n## Prerequisites\n\n- Node.js supports 22.19+ and 24+. CI covers 22.19, 24, and 26; see the [Node engine floor Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md).\n- Corepack-enabled pnpm. The repo pins `pnpm@11.7.0` in `package.json`; run `corepack enable` if `pnpm --version` does not resolve through Corepack.\n- Git.\n- Optional: a DeepSeek API key for the TUI, headless, and ACP automation demos and real-API e2e tests.\n\n## First-time setup\n\nInstall dependencies from the repo root:\n\n```sh\npnpm install\n```\n\nThe install also runs the root `postinstall` script, which installs lefthook from the repo dev dependency through `scripts/install-lefthook.mjs`; the wrapper script uses lefthook's reviewed `--force` mode so linked worktrees with an existing `core.hooksPath` do not fail normal `pnpm run …` commands.\n\nIf hooks are missing because dependencies were restored from cache or `postinstall` was skipped, install them manually:\n\n```sh\npnpm exec lefthook install --force\n```\n\nRun typecheck once after a fresh clone:\n\n```sh\npnpm run typecheck\n```\n\nThat first typecheck runs the whole-repo `tsc -b` graph: it emits every package/vendor `lib/types` and checks examples, tests, and scripts through the two no-emit aggregates described below.\n\n## TypeScript project layout\n\nThe repository's TypeScript configuration has exactly three roles; every tsconfig file plays one of them.\n\n| File | Role | Forms a program? |\n|---|---|---|\n| `tsconfig.json` | Solution root: `extends` base, `files: []`, references to the two aggregates. The whole-repo `tsc -b tsconfig.json` graph, the tsserver discovery entry, and — through the inherited `paths` — the resolution config for tsx running `examples/` and `scripts/` (their nearest tsconfig is this file). | No |\n| `tsconfig.host.json` | Host aggregate: host-side packages (via references), examples, tests, scripts, website. Excludes `packages/client`. | Yes |\n| `tsconfig.client.json` | Client aggregate: `packages/client/*` packages and their tests, `apps/web`. | Yes |\n| `tsconfig.base.json` | Shared compilerOptions and the source `paths` map. Also the resolution facade the vitest configs point vite-tsconfig-paths at: it has no `include`, so its `paths` apply to every importer. | No |\n| `tsconfig.base.client.json` | Browser compiler shape (`jsx`, DOM libs, `types: []`) extended by the client aggregate and every `packages/client/*` package. | No |\n\nHost and client stay two aggregate programs because both sides declaration-merge the cordis `Context` interface under the same keys with different services; one program seeing both merges reports a collision. The collision exists only inside a `ts.Program` — module resolution never triggers it — which is why the solution may reference both aggregates and one paths facade may span both sides. Two disciplines follow:\n\n- `tsconfig.base.json` never gains `include` or `files`: they would leak into every extending package project and narrow the facade's match-all scope.\n- A script that builds a repo-wide `ts.Program` seeds `tsconfig.host.json` or `tsconfig.client.json` explicitly — never the root solution, because flattening both aggregates into one program collides the `Context` merges. Program-backed generators and gates (`scripts/ts-project.ts` consumers, doc-typecheck standalone mode) are host-only by decision; the client side gains program-backed tooling only with a concrete need.\n\nStatic analysis and tests resolve workspace imports through the base `paths` map to `src` and must pass on a clean tree; gates that consume built `lib/` output declare that dependency explicitly. Decision record: [solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md); the tsc-first emit pipeline is the [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md).\n\nIf a relevant local check consumes built package output, build once first:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` includes `publint`, which validates package entrypoints against the built `lib/*.js` files, and `verify-node-next-types`, which validates built declarations against a temporary NodeNext consumer. A fresh worktree has no bundled JS or declarations until `pnpm run build` runs; ordinary commits and pushes do not require that build unless their selected checks consume it.\n\n## Environment variables\n\nThe real DeepSeek adapter and key-backed agent demos read credentials from the environment or from a gitignored `.env` at the repo root:\n\n```sh\nDEEPSEEK_API_KEY=sk-...\nDEEPSEEK_BASE_URL=https://... # optional\n```\n\n`DEEPSEEK_BASE_URL` is optional and defaults to the public API. Never commit real credentials. The real-API e2e suites self-skip when `DEEPSEEK_API_KEY` is not set.\n\n## Git hooks\n\nlefthook is configured in `lefthook.yml` as a fast local checkpoint:\n\n- `pre-commit` runs staged-file ESLint fixes, checks the staged diff for whitespace errors, and runs the vendor manifest guard.\n- `pre-push` runs only the incremental repository typecheck (`tsc -b` over the root solution, covering both the host and client aggregates).\n\nThe vendor manifest guard checks that changes under `vendor/*/src` are staged with the matching `vendor/README.md` manifest update. See `vendor/README.md` before editing vendored code.\n\nThe hooks intentionally do not run tests, snapshots, documentation checks, builds, or hygiene. Contributors run the [checks relevant to the changed behavior](../AGENTS.md#run-relevant-checks-locally) once; CI owns exhaustive coverage, built-artifact smokes, and the Node 22.19, 24, and 26 compatibility matrix.\n\nContributors can opt into the comprehensive local gate set with `pnpm run check:all`. The command is independent of both Git hooks and is not an agent instruction.\n\n## CI gates\n\nThe keyless [CI workflow](../.github/workflows/ci.yml) groups independent gates into broad lanes and runs a smaller compatibility signal across supported Node versions. Artifact consumers wait for one build within their lane. The separate real-API workflow runs `pnpm run test:e2e` with its configured worker bound. See [scripts/run-gates.ts](../scripts/run-gates.ts) and the workflow files for the current gate and job inventory.\n\n## Daily commands\n\nUse these from the repo root:\n\n```sh\npnpm run test # unit tests\npnpm run test:coverage # unit tests with per-file coverage gates\npnpm run test:e2e # real-API tests; self-skips without DEEPSEEK_API_KEY\npnpm run check:all # comprehensive opt-in gate set; not wired to Git hooks\npnpm run typecheck # tsc -b over the root solution: emits package/vendor lib/types, checks both aggregates\npnpm run lint # eslint .\npnpm run lint:fix # eslint . --fix\npnpm run doc-typecheck # compile checked TypeScript snippets in Markdown docs\npnpm run gen-cordis-catalog # regenerate docs/cordis-catalog/events.md + services.md from source\npnpm run verify-cordis-catalog # fail if either cordis catalog is stale\npnpm run verify-export-jsdoc # fail if a module-level package export lacks complete JSDoc\npnpm run gen-doc-graphs # regenerate generated relationship docs from source and curated graph definitions\npnpm run verify-doc-graphs # fail if generated relationship docs are stale\npnpm run verify-md-wrap # fail on hard-wrapped prose paragraphs in docs/README markdown\npnpm run verify-mermaid # fail if a ```mermaid diagram has invalid Mermaid syntax\npnpm run verify-type-equiv # fail if a ```ts type-equiv doc block drifts from its source type\npnpm run verify-doc-budgets # fail if a budgeted standing doc exceeds its word ceiling\npnpm run doc-sync # all Markdown/doc gates, scheduled concurrently; the doc-sync leaf list in scripts/run-gates.ts is the full list\npnpm run gen-module-graph # regenerate docs/module-graph.md from package peerDeps\npnpm run verify-module-graph # fail if docs/module-graph.md is stale\npnpm run build # emit lib/types intermediates, then bundle lib/index.* runtime files\npnpm run verify-node-next-types # fail if built declarations are not NodeNext-consumable\npnpm run hygiene # knip, publint, workspace constraints, and NodeNext declaration check\n```\n\nWhen changing package public behavior, update the relevant README or JSDoc in the same change. `pnpm run doc-sync` catches checked TypeScript snippets, generated doc freshness, markdown wrap/link drift, type equivalence, translation pairing, Mermaid syntax, and doc budgets, but broader prose/API sync still needs review.\n\n## Demos\n\nThe one-shot Headless coding agent needs `DEEPSEEK_API_KEY` in the environment or repo-root `.env`:\n\n```sh\npnpm run demo:headless \"summarize this workspace\"\n```\n\nThe full-screen interactive coding agent needs `DEEPSEEK_API_KEY` in the environment or repo-root `.env`:\n\n```sh\npnpm run demo:tui\n```\n\nThe self-referential cordis-agent demo can inspect and modify its live plugin runtime and needs the same credentials:\n\n```sh\npnpm run demo:cordis\n```\n\nThe ACP automation server exposes fresh agent sessions over JSON-RPC stdio and also needs `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:acp\n```\n\n## TODO markers\n\nUse one of three comment tags to flag known issues in the code, ordered by urgency:\n\n- `FIXME` — an issue that should block a new release. A release should not ship with an open `FIXME` unless reviewers explicitly agree the change can be merged anyway.\n- `TODO` — an issue that should be fixed soon, once we have the resources.\n- `XXX` — an issue that we may fix someday; lowest priority, no commitment.\n\nPick the tag that matches the urgency so anyone scanning the code can tell a release blocker from a someday-maybe.\n\n## Documenting types verbatim (`ts type-equiv`)\n\nThe [core data structures](core-data-structures/core.md) docs paste source-equivalent declarations together with their original JSDoc so a reader sees the exact shape and source contract. To keep a paste from drifting when source changes, fence it as ` ```ts type-equiv ` (instead of ` ```ts `) and register it in `scripts/type-equiv.manifest.json` with the source file and symbol it mirrors:\n\n```json\n{ \"doc\": \"docs/core-data-structures/session.md\", \"symbol\": \"SessionEvent\", \"source\": \"packages/core/session/src/types.ts\" }\n```\n\n`pnpm run verify-type-equiv` (part of `doc-sync`) then extracts that symbol's declaration and attached JSDoc from source via the TypeScript parser and asserts the block matches both. For a class whose implementation bodies do not belong in the catalog, use ` ```ts public-api ` and set `\"projection\": \"public-api\"`; the checked projection retains the public fields, constructor, accessors, methods, and original class/member JSDoc while omitting bodies and private or protected members. Comparison ignores whitespace and non-JSDoc comments but requires every original JSDoc comment, including member documentation, so readers see the source contract beside the exact shape. The gate also enforces a 1:1 correspondence by document, symbol, and projection, so a block can't go silently unchecked and a stale entry can't linger. `doc-typecheck` skips both fence kinds (they aren't standalone-compilable) and excludes them from its opt-out ratio. When you change a documented declaration or its JSDoc, the gate fails until you update the paste; when you add or remove a block, update the manifest in the same change.\n\n## Architecture context\n\nRead `docs/architecture.md` before changing anything under `packages/`. The codebase is built around Cordis plugins, event-sourced sessions, typed service seams, and explicit extension points.\n" }, { "role": "assistant", - "content": "# 开发指南\n\n[English](development.md) | 中文\n\n本指南覆盖参与 DeepSeek Harness 开发所需的本地环境搭建、日常工作流与 CI 流程;设计动机与技术权衡请查阅相应 Agent Note。\n\n## 前置条件\n\n- Node.js 支持 22.19+ 与 24+。CI 覆盖 22.19、24 和 26;见 [Node 引擎下限 Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md)。\n- 启用了 Corepack 的 pnpm。仓库在 `package.json` 中固定使用 `pnpm@11.7.0`;如果 `pnpm --version` 无法通过 Corepack 解析,请先运行 `corepack enable`。\n- Git。\n- 可选:一个 DeepSeek API key,用于 TUI/Headless/ACP(Agent Client Protocol) agent(智能体)演示和真实 API 的 e2e 测试。\n\n## 首次搭建\n\n在仓库根目录安装依赖:\n\n```sh\npnpm install\n```\n\n安装过程同时会运行根目录的 `postinstall` 脚本,该脚本通过 `scripts/install-lefthook.mjs` 从仓库 dev 依赖安装 lefthook。包装脚本使用 lefthook 经过评审的 `--force` 模式,确保已存在 `core.hooksPath` 的关联 worktree 不会导致正常的 `pnpm run …` 命令失败。\n\n如果依赖是从缓存恢复或 `postinstall` 被跳过而导致缺少钩子,请手动安装:\n\n```sh\npnpm exec lefthook install --force\n```\n\n新克隆后请先运行一次类型检查:\n\n```sh\npnpm run typecheck\n```\n\n首次类型检查会执行全仓 `tsc -b tsconfig.json` 图:发射每个 package/vendor 的 `lib/types`,并通过下述两个 no-emit 聚合检查示例、测试和脚本。\n\n## TypeScript 项目布局\n\n仓库的 TypeScript 配置只有三种角色;每个 tsconfig 文件恰好扮演其中一种。\n\n| 文件 | 角色 | 是否构成 program? |\n|---|---|---|\n| `tsconfig.json` | solution 根:`extends` base、`files: []`、引用两个聚合。全仓 `tsc -b tsconfig.json` 图、tsserver 发现入口,并经继承的 `paths` 充当 tsx 运行 `examples/` 与 `scripts/` 时的解析配置(它们最近的 tsconfig 就是此文件)。 | 否 |\n| `tsconfig.host.json` | host 聚合:host 侧各包(经 references)、示例、测试、脚本、website。排除 `packages/client`。 | 是 |\n| `tsconfig.client.json` | client 聚合:`packages/client/*` 各包及其测试、`apps/web`。 | 是 |\n| `tsconfig.base.json` | 共享 compilerOptions 与源码 `paths` 映射。同时是各 vitest 配置让 vite-tsconfig-paths 指向的解析门面:它没有 `include`,因此其 `paths` 适用于任何 importer。 | 否 |\n| `tsconfig.base.client.json` | 浏览器编译形状(`jsx`、DOM lib、`types: []`),由 client 聚合和每个 `packages/client/*` 包 extends。 | 否 |\n\nhost 与 client 保持两个聚合 program,是因为两侧在相同键下以不同服务对 cordis `Context` 接口做声明合并;单一 program 同时看到两份合并会报冲突。这种冲突只存在于 `ts.Program` 内部——模块解析永远不会触发它——所以 solution 可以同时引用两个聚合,一个 paths 门面也可以横跨两侧。由此推出两条纪律:\n\n- `tsconfig.base.json` 永不添加 `include` 或 `files`:它们会泄漏进每个 extends 它的包项目,并收窄门面的全匹配范围。\n- 构造全仓 `ts.Program` 的脚本显式种子 `tsconfig.host.json` 或 `tsconfig.client.json`——永不种子根 solution,因为把两个聚合展平进一个 program 会撞上 `Context` 合并冲突。基于 program 的生成器与门禁(`scripts/ts-project.ts` 的消费者、doc-typecheck standalone 模式)按决策仅覆盖 host 侧;client 侧只在出现真实需求时再获得基于 program 的工具。\n\n静态分析和测试通过 base 的 `paths` 映射把工作区 import 解析到 `src`,且必须在干净树上通过;消费构建产物 `lib/` 的门禁显式声明该依赖。决策记录:[solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md);tsc-first 发射管线见 [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md)。\n\n如果相关的本地检查需要使用构建后的包产物,请先构建一次:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` 包含 `publint`(用构建出的 `lib/*.js` 文件校验 package 入口点)和 `verify-node-next-types`(用一个临时的 NodeNext 消费方校验构建出的声明文件)。新 worktree 在 `pnpm run build` 运行之前没有打包的 JS 和声明文件;普通提交和推送无需构建,除非所选检查会使用这些产物。\n\n## 环境变量\n\n真实的 DeepSeek 适配器和需要密钥的 agent 演示从环境变量或仓库根目录一个被 gitignore 的 `.env` 文件读取凭证:\n\n```sh\nDEEPSEEK_API_KEY=sk-...\nDEEPSEEK_BASE_URL=https://... # optional\n```\n\n`DEEPSEEK_BASE_URL` 可选,默认为公开 API。请勿提交真实凭证。未设置 `DEEPSEEK_API_KEY` 时,真实 API 的 e2e 套件会自动跳过。\n\n## Git 钩子\n\nlefthook 在 `lefthook.yml` 中配置,作为快速的本地检查点:\n\n- `pre-commit` 运行对暂存文件的 ESLint 修复,检查暂存 diff 中的空白错误,并运行 vendor manifest(元数据清单)守卫;\n- `pre-push` 只运行仓库增量类型检查(对根 solution 执行 `tsc -b`,覆盖 host 与 client 两个聚合)。\n\nvendor manifest 守卫检查 `vendor/*/src` 下的改动是否连同对应的 `vendor/README.md` manifest 更新一起暂存。请在编辑 vendor 代码前先阅读 `vendor/README.md`。\n\n这些钩子有意不运行测试、快照、文档检查、构建或 `hygiene`。贡献者只运行一次[与改动行为相关的检查](../AGENTS.md#run-relevant-checks-locally);CI 负责全量覆盖率门禁、构建产物冒烟测试,以及 Node 22.19、24 和 26 兼容性矩阵。\n\n贡献者可以选择运行 `pnpm run check:all`,执行全面的本地门禁集。该命令独立于两个 Git 钩子,也不是对 agent 的指令。\n\n## CI 门禁\n\nkeyless [CI 工作流](../.github/workflows/ci.yml) 将独立门禁分组到若干宽粒度 lane,并在受支持的 Node 版本上运行一组较小的兼容性检查。产物消费方在各自 lane 内等待一次 build。单独的真实 API 工作流按其配置的 worker 上限运行 `pnpm run test:e2e`。当前门禁和 job 清单以 [scripts/run-gates.ts](../scripts/run-gates.ts) 和工作流文件为准。\n\n## 日常命令\n\n在仓库根目录使用:\n\n```sh\npnpm run test # unit tests\npnpm run test:coverage # unit tests with per-file coverage gates\npnpm run test:e2e # real-API tests; self-skips without DEEPSEEK_API_KEY\npnpm run check:all # comprehensive opt-in gate set; not wired to Git hooks\npnpm run typecheck # tsc -b over the root solution: emits package/vendor lib/types, checks both aggregates\npnpm run lint # eslint .\npnpm run lint:fix # eslint . --fix\npnpm run doc-typecheck # compile checked TypeScript snippets in Markdown docs\npnpm run gen-cordis-catalog # regenerate docs/cordis-catalog/events.md + services.md from source\npnpm run verify-cordis-catalog # fail if either cordis catalog is stale\npnpm run verify-export-jsdoc # fail if a module-level package export lacks complete JSDoc\npnpm run gen-doc-graphs # regenerate generated relationship docs from source and curated graph definitions\npnpm run verify-doc-graphs # fail if generated relationship docs are stale\npnpm run verify-md-wrap # fail on hard-wrapped prose paragraphs in docs/README markdown\npnpm run verify-mermaid # fail if a ```mermaid diagram has invalid Mermaid syntax\npnpm run verify-type-equiv # fail if a ```ts type-equiv doc block drifts from its source type\npnpm run verify-doc-budgets # fail if a budgeted standing doc exceeds its word ceiling\npnpm run doc-sync # all Markdown/doc gates, scheduled concurrently; the doc-sync leaf list in scripts/run-gates.ts is the full list\npnpm run gen-module-graph # regenerate docs/module-graph.md from package peerDeps\npnpm run verify-module-graph # fail if docs/module-graph.md is stale\npnpm run build # emit lib/types intermediates, then bundle lib/index.* runtime files\npnpm run verify-node-next-types # fail if built declarations are not NodeNext-consumable\npnpm run hygiene # knip, publint, workspace constraints, and NodeNext declaration check\n```\n\n修改 package 的公开行为时,请在同一个变更中更新相关 README 或 JSDoc。`pnpm run doc-sync` 能检测到被检查的 TypeScript 片段、生成文档的新鲜度、Markdown 换行/链接漂移、type-equiv、翻译配对、Mermaid 语法和文档预算,但更广泛的行文/API 同步仍需评审把关。\n\n## 演示\n\n单次运行的 Headless coding agent 需要环境变量或仓库根目录 `.env` 中的 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:headless \"summarize this workspace\"\n```\n\n全屏交互式 coding agent 需要环境变量或仓库根目录 `.env` 中的 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:tui\n```\n\n自指的 cordis-agent 演示可以检查并修改其实时插件运行时,并需要相同的凭证:\n\n```sh\npnpm run demo:cordis\n```\n\nACP 服务器 agent 演示通过 JSON-RPC stdio 暴露 agent,同样需要 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:acp\n```\n\n## TODO 标记\n\n请使用以下三种注释标签之一标记代码中的已知问题,按紧急程度排序:\n\n- `FIXME`:应当阻塞新版本发布的问题。除非评审者明确同意该更改可以合并,否则发布版本不应包含未解决的 `FIXME`;\n- `TODO`:应当尽快修复的问题,等资源到位即可处理;\n- `XXX`:也许某天会修复的问题,优先级最低,不作承诺。\n\n请选择与紧急程度匹配的标签,让浏览代码的人一眼分清「发布阻塞」和「有空再说」。\n\n## 逐字记录类型(`ts type-equiv`)\n\n[核心数据结构](core-data-structures/core.md)文档会把与源码等价的声明及其原始 JSDoc 一并粘贴,让读者看到确切形状和源码契约。为防止粘贴内容在源码变化时漂移,请将其围栏为 ` ```ts type-equiv `(而不是 ` ```ts `),并在 `scripts/type-equiv.manifest.json` 中登记它镜像的源文件和符号:\n\n```json\n{ \"doc\": \"docs/core-data-structures/session.md\", \"symbol\": \"SessionEvent\", \"source\": \"packages/core/session/src/types.ts\" }\n```\n\n`pnpm run verify-type-equiv`(`doc-sync` 的一环)随后通过 TypeScript 解析器从源码提取该符号的声明及其附带的 JSDoc,并断言代码块同时匹配两者。对于不应把实现体写进目录的类,请使用 ` ```ts public-api ` 并设置 `\"projection\": \"public-api\"`;门禁检查的投影会保留公共字段、构造函数、访问器、方法以及类和成员的原始 JSDoc,同时省略实现体和私有或受保护成员。比对会忽略空白和非 JSDoc 注释,但要求保留每条原始 JSDoc(包括成员文档),让读者同时看到源码契约和确切形状。该门禁还按文档、符号和投影强制 1:1 对应,因此不会有块被静默漏检,也不会有陈旧条目滞留。`doc-typecheck` 跳过两种围栏(它们不能独立编译),并将其排除在 opt-out 比例之外。当你改动一个已记录的类型声明或其 JSDoc 时,门禁会失败直到你更新粘贴内容;当你增删一个块时,请在同一个变更里更新 manifest。\n\n## 架构上下文\n\n在修改 `packages/` 目录下的任何内容之前,请先阅读 `docs/architecture.md`。这套代码围绕 Cordis 插件、事件溯源的会话、类型化的服务 seam 与显式扩展点构建。\n" + "content": "# 开发指南\n\n[English](development.md) | 中文\n\n本指南覆盖参与 DeepSeek Harness 开发所需的本地环境搭建、日常工作流与 CI 流程;设计动机与技术权衡请查阅相应 Agent Note。\n\n## 前置条件\n\n- Node.js 支持 22.19+ 与 24+。CI 覆盖 22.19、24 和 26;见 [Node 引擎下限 Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md)。\n- 启用了 Corepack 的 pnpm。仓库在 `package.json` 中固定使用 `pnpm@11.7.0`;如果 `pnpm --version` 无法通过 Corepack 解析,请先运行 `corepack enable`。\n- Git。\n- 可选:一个 DeepSeek API key,用于 TUI、headless 和 ACP(Agent Client Protocol)自动化 agent(智能体)演示以及真实 API 的 e2e 测试。\n\n## 首次搭建\n\n在仓库根目录安装依赖:\n\n```sh\npnpm install\n```\n\n安装过程同时会运行根目录的 `postinstall` 脚本,该脚本通过 `scripts/install-lefthook.mjs` 从仓库 dev 依赖安装 lefthook。包装脚本使用 lefthook 经过评审的 `--force` 模式,确保已存在 `core.hooksPath` 的关联 worktree 不会导致正常的 `pnpm run …` 命令失败。\n\n如果依赖是从缓存恢复或 `postinstall` 被跳过而导致缺少钩子,请手动安装:\n\n```sh\npnpm exec lefthook install --force\n```\n\n新克隆后请先运行一次类型检查:\n\n```sh\npnpm run typecheck\n```\n\n首次类型检查会执行全仓 `tsc -b tsconfig.json` 图:发射每个 package/vendor 的 `lib/types`,并通过下述两个 no-emit 聚合检查示例、测试和脚本。\n\n## TypeScript 项目布局\n\n仓库的 TypeScript 配置只有三种角色;每个 tsconfig 文件恰好扮演其中一种。\n\n| 文件 | 角色 | 是否构成 program? |\n|---|---|---|\n| `tsconfig.json` | solution 根:`extends` base、`files: []`、引用两个聚合。全仓 `tsc -b tsconfig.json` 图、tsserver 发现入口,并经继承的 `paths` 充当 tsx 运行 `examples/` 与 `scripts/` 时的解析配置(它们最近的 tsconfig 就是此文件)。 | 否 |\n| `tsconfig.host.json` | host 聚合:host 侧各包(经 references)、示例、测试、脚本、website。排除 `packages/client`。 | 是 |\n| `tsconfig.client.json` | client 聚合:`packages/client/*` 各包及其测试、`apps/web`。 | 是 |\n| `tsconfig.base.json` | 共享 compilerOptions 与源码 `paths` 映射。同时是各 vitest 配置让 vite-tsconfig-paths 指向的解析门面:它没有 `include`,因此其 `paths` 适用于任何 importer。 | 否 |\n| `tsconfig.base.client.json` | 浏览器编译形状(`jsx`、DOM lib、`types: []`),由 client 聚合和每个 `packages/client/*` 包 extends。 | 否 |\n\nhost 与 client 保持两个聚合 program,是因为两侧在相同键下以不同服务对 cordis `Context` 接口做声明合并;单一 program 同时看到两份合并会报冲突。这种冲突只存在于 `ts.Program` 内部——模块解析永远不会触发它——所以 solution 可以同时引用两个聚合,一个 paths 门面也可以横跨两侧。由此推出两条纪律:\n\n- `tsconfig.base.json` 永不添加 `include` 或 `files`:它们会泄漏进每个 extends 它的包项目,并收窄门面的全匹配范围。\n- 构造全仓 `ts.Program` 的脚本显式种子 `tsconfig.host.json` 或 `tsconfig.client.json`——永不种子根 solution,因为把两个聚合展平进一个 program 会撞上 `Context` 合并冲突。基于 program 的生成器与门禁(`scripts/ts-project.ts` 的消费者、doc-typecheck standalone 模式)按决策仅覆盖 host 侧;client 侧只在出现真实需求时再获得基于 program 的工具。\n\n静态分析和测试通过 base 的 `paths` 映射把工作区 import 解析到 `src`,且必须在干净树上通过;消费构建产物 `lib/` 的门禁显式声明该依赖。决策记录:[solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md);tsc-first 发射管线见 [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md)。\n\n如果相关的本地检查需要使用构建后的包产物,请先构建一次:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` 包含 `publint`(用构建出的 `lib/*.js` 文件校验 package 入口点)和 `verify-node-next-types`(用一个临时的 NodeNext 消费方校验构建出的声明文件)。新 worktree 在 `pnpm run build` 运行之前没有打包的 JS 和声明文件;普通提交和推送无需构建,除非所选检查会使用这些产物。\n\n## 环境变量\n\n真实的 DeepSeek 适配器和需要密钥的 agent 演示从环境变量或仓库根目录一个被 gitignore 的 `.env` 文件读取凭证:\n\n```sh\nDEEPSEEK_API_KEY=sk-...\nDEEPSEEK_BASE_URL=https://... # optional\n```\n\n`DEEPSEEK_BASE_URL` 可选,默认为公开 API。请勿提交真实凭证。未设置 `DEEPSEEK_API_KEY` 时,真实 API 的 e2e 套件会自动跳过。\n\n## Git 钩子\n\nlefthook 在 `lefthook.yml` 中配置,作为快速的本地检查点:\n\n- `pre-commit` 运行对暂存文件的 ESLint 修复,检查暂存 diff 中的空白错误,并运行 vendor manifest(元数据清单)守卫;\n- `pre-push` 只运行仓库增量类型检查(对根 solution 执行 `tsc -b`,覆盖 host 与 client 两个聚合)。\n\nvendor manifest 守卫检查 `vendor/*/src` 下的改动是否连同对应的 `vendor/README.md` manifest 更新一起暂存。请在编辑 vendor 代码前先阅读 `vendor/README.md`。\n\n这些钩子有意不运行测试、快照、文档检查、构建或 `hygiene`。贡献者只运行一次[与改动行为相关的检查](../AGENTS.md#run-relevant-checks-locally);CI 负责全量覆盖率门禁、构建产物冒烟测试,以及 Node 22.19、24 和 26 兼容性矩阵。\n\n贡献者可以选择运行 `pnpm run check:all`,执行全面的本地门禁集。该命令独立于两个 Git 钩子,也不是对 agent 的指令。\n\n## CI 门禁\n\nkeyless [CI 工作流](../.github/workflows/ci.yml) 将独立门禁分组到若干宽粒度 lane,并在受支持的 Node 版本上运行一组较小的兼容性检查。产物消费方在各自 lane 内等待一次 build。单独的真实 API 工作流按其配置的 worker 上限运行 `pnpm run test:e2e`。当前门禁和 job 清单以 [scripts/run-gates.ts](../scripts/run-gates.ts) 和工作流文件为准。\n\n## 日常命令\n\n在仓库根目录使用:\n\n```sh\npnpm run test # unit tests\npnpm run test:coverage # unit tests with per-file coverage gates\npnpm run test:e2e # real-API tests; self-skips without DEEPSEEK_API_KEY\npnpm run check:all # comprehensive opt-in gate set; not wired to Git hooks\npnpm run typecheck # tsc -b over the root solution: emits package/vendor lib/types, checks both aggregates\npnpm run lint # eslint .\npnpm run lint:fix # eslint . --fix\npnpm run doc-typecheck # compile checked TypeScript snippets in Markdown docs\npnpm run gen-cordis-catalog # regenerate docs/cordis-catalog/events.md + services.md from source\npnpm run verify-cordis-catalog # fail if either cordis catalog is stale\npnpm run verify-export-jsdoc # fail if a module-level package export lacks complete JSDoc\npnpm run gen-doc-graphs # regenerate generated relationship docs from source and curated graph definitions\npnpm run verify-doc-graphs # fail if generated relationship docs are stale\npnpm run verify-md-wrap # fail on hard-wrapped prose paragraphs in docs/README markdown\npnpm run verify-mermaid # fail if a ```mermaid diagram has invalid Mermaid syntax\npnpm run verify-type-equiv # fail if a ```ts type-equiv doc block drifts from its source type\npnpm run verify-doc-budgets # fail if a budgeted standing doc exceeds its word ceiling\npnpm run doc-sync # all Markdown/doc gates, scheduled concurrently; the doc-sync leaf list in scripts/run-gates.ts is the full list\npnpm run gen-module-graph # regenerate docs/module-graph.md from package peerDeps\npnpm run verify-module-graph # fail if docs/module-graph.md is stale\npnpm run build # emit lib/types intermediates, then bundle lib/index.* runtime files\npnpm run verify-node-next-types # fail if built declarations are not NodeNext-consumable\npnpm run hygiene # knip, publint, workspace constraints, and NodeNext declaration check\n```\n\n修改 package 的公开行为时,请在同一个变更中更新相关 README 或 JSDoc。`pnpm run doc-sync` 能检测到被检查的 TypeScript 片段、生成文档的新鲜度、Markdown 换行/链接漂移、type-equiv、翻译配对、Mermaid 语法和文档预算,但更广泛的行文/API 同步仍需评审把关。\n\n## 演示\n\n单次运行的 Headless coding agent 需要环境变量或仓库根目录 `.env` 中的 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:headless \"summarize this workspace\"\n```\n\n全屏交互式 coding agent 需要环境变量或仓库根目录 `.env` 中的 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:tui\n```\n\n自指的 cordis-agent 演示可以检查并修改其实时插件运行时,并需要相同的凭证:\n\n```sh\npnpm run demo:cordis\n```\n\nACP 自动化服务器通过 JSON-RPC stdio 提供全新 agent 会话,同样需要 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:acp\n```\n\n## TODO 标记\n\n请使用以下三种注释标签之一标记代码中的已知问题,按紧急程度排序:\n\n- `FIXME`:应当阻塞新版本发布的问题。除非评审者明确同意该更改可以合并,否则发布版本不应包含未解决的 `FIXME`;\n- `TODO`:应当尽快修复的问题,等资源到位即可处理;\n- `XXX`:也许某天会修复的问题,优先级最低,不作承诺。\n\n请选择与紧急程度匹配的标签,让浏览代码的人一眼分清「发布阻塞」和「有空再说」。\n\n## 逐字记录类型(`ts type-equiv`)\n\n[核心数据结构](core-data-structures/core.md)文档会把与源码等价的声明及其原始 JSDoc 一并粘贴,让读者看到确切形状和源码契约。为防止粘贴内容在源码变化时漂移,请将其围栏为 ` ```ts type-equiv `(而不是 ` ```ts `),并在 `scripts/type-equiv.manifest.json` 中登记它镜像的源文件和符号:\n\n```json\n{ \"doc\": \"docs/core-data-structures/session.md\", \"symbol\": \"SessionEvent\", \"source\": \"packages/core/session/src/types.ts\" }\n```\n\n`pnpm run verify-type-equiv`(`doc-sync` 的一环)随后通过 TypeScript 解析器从源码提取该符号的声明及其附带的 JSDoc,并断言代码块同时匹配两者。对于不应把实现体写进目录的类,请使用 ` ```ts public-api ` 并设置 `\"projection\": \"public-api\"`;门禁检查的投影会保留公共字段、构造函数、访问器、方法以及类和成员的原始 JSDoc,同时省略实现体和私有或受保护成员。比对会忽略空白和非 JSDoc 注释,但要求保留每条原始 JSDoc(包括成员文档),让读者同时看到源码契约和确切形状。该门禁还按文档、符号和投影强制 1:1 对应,因此不会有块被静默漏检,也不会有陈旧条目滞留。`doc-typecheck` 跳过两种围栏(它们不能独立编译),并将其排除在 opt-out 比例之外。当你改动一个已记录的类型声明或其 JSDoc 时,门禁会失败直到你更新粘贴内容;当你增删一个块时,请在同一个变更里更新 manifest。\n\n## 架构上下文\n\n在修改 `packages/` 目录下的任何内容之前,请先阅读 `docs/architecture.md`。这套代码围绕 Cordis 插件、事件溯源的会话、类型化的服务 seam 与显式扩展点构建。\n" }, { "role": "user", - "content": "# Bilingual documentation\n\nEnglish | [中文](README.zh.md)\n\nThis repo's documentation is read by people and agents both inside and outside the company, so the README, Agent Notes, and docs tree are maintained in English and Simplified Chinese. This page defines the pairing contract, the enforcement gate, and the rollout policy; [translation-rules.md](translation-rules.md) defines how to translate; [terminology.md](terminology.md) is the terminology source of truth. The committed agent workflow lives in [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md).\n\n## The pairing contract\n\n- **Both languages carry equal authority.** A document may be authored and reviewed in either language first — a Chinese-first Agent Note is as legitimate as an English-first one — and the counterpart is translated from it. Neither file outranks the other; what binds them is that they must say the same thing.\n- **A pair is three sibling files.** The English `foo.md`, the Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`, all in the same directory. No locale directories, no separate translation repo, no interleaved bilingual files. Pairs merge whole: a PR never lands one language without the other two files.\n- **The consistency record.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last time the two were confirmed to say the same thing:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n Blob hashes, not commit hashes, so the record is computable for files edited in the same PR (`git hash-object foo.md`) and consistency is a pure content comparison. The recorded hash also recovers the exact last-confirmed text of either side (`git cat-file -p <hash>`), so an out-of-sync pair is updated by diffing the edited side against its last-confirmed state and patching the counterpart minimally — never by re-translating whole files. After bringing the pair back in line, `pnpm run verify-translation-pairing --write` re-records both hashes; that yaml diff is the reviewable act of confirming consistency.\n- **Language switcher.** Both files link to each other immediately after their H1 heading: the English file carries `English | [中文](foo.zh.md)` and the Chinese file carries `[English](foo.md) | 中文`.\n- **Structure mirrors the counterpart.** Heading depths and order, list kinds, ordered-list starts, list item counts, table row and column counts, link targets, and verbatim code blocks match one to one across the pair — see [translation-rules.md](translation-rules.md) for the full preservation rules. Existing Markdown gates apply to `.zh.md` files unchanged (`verify-md-wrap`, `verify-md-links`).\n\n## The gate: verify-translation-pairing\n\n`pnpm run verify-translation-pairing` (part of `doc-sync`, which contributors run locally for documentation changes and CI runs exhaustively) enforces the contract mechanically:\n\n1. Every file listed as `required` in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair.\n2. Every pair that exists at all — required or not — is complete and consistent: all three files present, each side's current blob hash equals the recorded one (editing either side without re-confirming the pair goes red), both sides carry the language switcher, and the structural signatures match in order — heading depths, verbatim code blocks (info string and content), table row and column counts, list kinds, ordered-list starts, item counts, and every link target apart from the switcher.\n3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all.\n4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth.\n\n`pnpm run verify-translation-pairing --list` prints the current pairing state of every document in scope — missing, out-of-sync, or ok — and is the work list for translation batches. It never fails; it reports.\n\nThe practical rule this gate creates: **when a PR edits either side of a paired document, the same PR updates the counterpart and re-records the pair** (run the [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill, then `--write`), exactly like the repo's existing doc-sync rule for code and READMEs. A PR that leaves a pair out of sync goes red in CI.\n\nThe gate's limit, stated plainly: **a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.** It checks hashes and shape; it cannot judge whether the two sides actually say the same thing, or whether the wording is accurate, well-termed, and natural — that is the reviewer's half of the contract, per [translation-rules.md](translation-rules.md). A re-recorded pair with a sloppy counterpart passes the gate; it must not pass review.\n\n## Scope, exclusions, and rollout\n\n**Scope**: the root `README.md`, everything under `.agents/notes/**`, `docs/**`, and `python/**`. Package READMEs (`packages/**`) join the scope in a later batch.\n\n**Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them):\n\n- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, and `docs/module-graph.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list.\n- `docs/AGENTS.md` and `.agents/notes/**/AGENTS.md` — agent instructions, maintained in English only like the root `AGENTS.md`.\n- `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction.\n- [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior.\n\n**Rollout**: a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after the manifest's `requiredSince` cutoff must merge with its pair. Earlier dates are backlog, including files created on the cutoff's eve. An Agent Note filename records its first-proposed date, so backdating past the cutoff is a review-visible violation. The manifest's `required` list is the current enforcement frontier, not the goal of full coverage. Translation batches add paths to `required`, ratcheting the gate forward. Unlisted documents remain visible in `--list`, while every existing pair is governed by the full contract. Because later edits must update both sides, expand `required` only as fast as translation review can support.\n\n## Division of labor\n\nCounterparts here are produced by an agent running [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) and reviewed by a human — inference is cheap here, review attention is the scarce resource. The gate checks pair completeness, recorded hashes, switchers, and its documented structural signature. Review still owns translation quality, terminology, and structural requirements that the signature does not encode. The prompt contract is executable: [scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) renders the committed template (terminology injected; the template carries its own calibrated rules) into either direction and parses the three-section response, while `verify-translation-prompt` exercises both render directions and the checked-in example in `doc-sync`.\n" + "content": "# Bilingual documentation\n\nEnglish | [中文](README.zh.md)\n\nThis repo's documentation is read by people and agents both inside and outside the company, so the README, Agent Notes, and docs tree are maintained in English and Simplified Chinese. This page defines the pairing contract, the enforcement gate, and the rollout policy; [translation-rules.md](translation-rules.md) defines how to translate; [terminology.md](terminology.md) is the terminology source of truth. The committed agent workflow lives in [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md).\n\n## The pairing contract\n\n- **Both languages carry equal authority.** A document may be authored and reviewed in either language first — a Chinese-first Agent Note is as legitimate as an English-first one — and the counterpart is translated from it. Neither file outranks the other; what binds them is that they must say the same thing.\n- **A pair is three sibling files.** The English `foo.md`, the Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`, all in the same directory. No locale directories, no separate translation repo, no interleaved bilingual files. Pairs merge whole: a PR never lands one language without the other two files.\n- **The consistency record.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last time the two were confirmed to say the same thing:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n Blob hashes, not commit hashes, so the record is computable for files edited in the same PR (`git hash-object foo.md`) and consistency is a pure content comparison. The recorded hash also recovers the exact last-confirmed text of either side (`git cat-file -p <hash>`), so an out-of-sync pair is updated by diffing the edited side against its last-confirmed state and patching the counterpart minimally — never by re-translating whole files. After bringing the pair back in line, `pnpm run verify-translation-pairing --write` re-records both hashes; that yaml diff is the reviewable act of confirming consistency.\n- **Language switcher.** Both files link to each other immediately after their H1 heading: the English file carries `English | [中文](foo.zh.md)` and the Chinese file carries `[English](foo.md) | 中文`.\n- **Structure mirrors the counterpart.** Heading depths and order, list kinds, ordered-list starts, list item counts, table row and column counts, link targets, and verbatim code blocks match one to one across the pair — see [translation-rules.md](translation-rules.md) for the full preservation rules. Existing Markdown gates apply to `.zh.md` files unchanged (`verify-md-wrap`, `verify-md-links`).\n\n## The gate: verify-translation-pairing\n\n`pnpm run verify-translation-pairing` (part of `doc-sync`, which contributors run locally for documentation changes and CI runs exhaustively) enforces the contract mechanically:\n\n1. Every file listed as `required` in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair.\n2. Every pair that exists at all — required or not — is complete and consistent: all three files present, each side's current blob hash equals the recorded one (editing either side without re-confirming the pair goes red), both sides carry the language switcher, and the structural signatures match in order — heading depths, verbatim code blocks (info string and content), table row and column counts, list kinds, ordered-list starts, item counts, and every link target apart from the switcher.\n3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all.\n4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth.\n\n`pnpm run verify-translation-pairing --list` prints the current pairing state of every document in scope — missing, out-of-sync, or ok — and is the work list for translation batches. It never fails; it reports.\n\nThe practical rule this gate creates: **when a PR edits either side of a paired document, the same PR updates the counterpart and re-records the pair** (run the [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill, then `--write`), exactly like the repo's existing doc-sync rule for code and READMEs. A PR that leaves a pair out of sync goes red in CI.\n\nThe gate's limit, stated plainly: **a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.** It checks hashes and shape; it cannot judge whether the two sides actually say the same thing, or whether the wording is accurate, well-termed, and natural — that is the reviewer's half of the contract, per [translation-rules.md](translation-rules.md). A re-recorded pair with a sloppy counterpart passes the gate; it must not pass review.\n\n## Scope, exclusions, and rollout\n\n**Scope**: the root `README.md`, everything under `.agents/notes/**`, `docs/**`, and `python/**`. Package READMEs (`packages/**`) join the scope in a later batch.\n\n**Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them):\n\n- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, `docs/module-graph.md`, `docs/agent-lifecycle.md`, `docs/capability-seams.md`, `docs/event-producer-consumer.md`, `docs/graph-atlas.md`, and `docs/tool-execution-pipeline.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list.\n- `docs/AGENTS.md` and `.agents/notes/**/AGENTS.md` — agent instructions, maintained in English only like the root `AGENTS.md`.\n- `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction.\n- [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior.\n\n**Rollout**: a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after the manifest's `requiredSince` cutoff must merge with its pair. Earlier dates are backlog, including files created on the cutoff's eve. An Agent Note filename records its first-proposed date, so backdating past the cutoff is a review-visible violation. The manifest's `required` list is the current enforcement frontier, not the goal of full coverage. Translation batches add paths to `required`, ratcheting the gate forward. Unlisted documents remain visible in `--list`, while every existing pair is governed by the full contract. Because later edits must update both sides, expand `required` only as fast as translation review can support.\n\n## Division of labor\n\nCounterparts here are produced by an agent running [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) and reviewed by a human — inference is cheap here, review attention is the scarce resource. The gate checks pair completeness, recorded hashes, switchers, and its documented structural signature. Review still owns translation quality, terminology, and structural requirements that the signature does not encode. The prompt contract is executable: [scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) renders the committed template (terminology injected; the template carries its own calibrated rules) into either direction and parses the three-section response, while `verify-translation-prompt` exercises both render directions and the checked-in example in `doc-sync`.\n" }, { "role": "assistant", - "content": "# 双语文档\n\n[English](README.md) | 中文\n\n本仓库的文档会被公司内外的人和 agent(智能体)阅读,因此 README、Agent Note(agent 决策记录)与 docs 目录树以英文和简体中文双语维护。本页定义配对契约、强制门禁与推进策略;[translation-rules.md](translation-rules.md) 定义如何翻译;[terminology.md](terminology.md) 是术语真源。仓库内置的 agent 工作流见 [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md)。\n\n## 配对契约\n\n- **两种语言同权。** 一篇文档可以先用任一语言撰写和评审(先写中文的 Agent Note 与先写英文的一样正当),另一侧由它翻译而来。两个文件谁也不高于谁;约束它们的是二者必须说同样的话。\n- **一对文档是三个同目录文件。** 英文 `foo.md`、中文 `foo.zh.md`,加一份一致性记录 `foo.i18n.yaml`,都在同一目录。不用语言目录,不用独立翻译仓库,不用中英混排的单文件。配对必须整体合并:PR(Pull Request)永远不会只带一种语言而缺其余两个文件。\n- **一致性记录。**`foo.i18n.yaml` 保存两侧文件在上一次被确认「说同样的话」时各自的完整 git blob hash:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n 用 blob hash 而不是 commit hash,这样同一个 PR 里改动的文件也能算出记录(`git hash-object foo.md`),一致性是纯内容比较。记录的 hash 还能还原任一侧上次确认时的确切文本(`git cat-file -p <hash>`),所以失去同步的配对是「把被改的一侧与其上次确认状态做 diff、再最小化地修补另一侧」,从不整篇重译。两侧对齐后,`pnpm run verify-translation-pairing --write` 重新记录两个 hash;那份 yaml diff 就是「确认一致」这个动作本身,可以被评审。\n- **语言切换行。** 两个文件在各自 H1 标题之后立即互链:英文文件带 `English | [中文](foo.zh.md)`,中文文件带 `[English](foo.md) | 中文`。\n- **结构与另一侧一一对应。** 标题深度与顺序、列表类型、有序列表起始编号、列表项数量、表格行列数、链接目标与逐字节一致的代码块在配对两侧一一对应;完整保持规则见 [translation-rules.md](translation-rules.md)。既有 Markdown 门禁对 `.zh.md` 文件原样生效(`verify-md-wrap`、`verify-md-links`)。\n\n## 门禁:verify-translation-pairing\n\n`pnpm run verify-translation-pairing`(`doc-sync`(文档同步门禁)的一环,贡献者会针对文档变更在本地运行,CI 则会完整运行)机械地强制执行这份契约:\n\n1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件都有完整配对。\n2. 任何已存在的配对(无论是否 required)都完整且一致:三个文件齐全、每一侧的当前 blob hash 等于记录值(改了任一侧而没重新确认配对就变红)、双方都带语言切换行、结构签名按序一致:标题深度、逐字节一致的代码块(信息字符串与内容)、表格行列数、列表类型、有序列表起始编号、列表项数量,以及除切换行之外的每个链接目标。\n3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。\n4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。\n\n`pnpm run verify-translation-pairing --list` 打印范围内每篇文档的当前配对状态(missing、out-of-sync 或 ok),是翻译批次的工作清单。它从不失败;它只报告。\n\n这个门禁带来的实际规则是:**当一个 PR 修改了已配对文档的任一侧时,同一个 PR 更新另一侧并重新记录配对**(运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill(技能),再 `--write`),与本仓库既有的代码与 README 的 doc-sync 规则完全一致。留下失去同步的配对的 PR 会在 CI 变红。\n\n把门禁的边界说白:**门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。** 它检查记录的 hash 与结构签名;它无法判断两侧是否真的在说同样的话,也无法判断措辞是否准确、术语是否得当、行文是否自然;这部分契约由评审者把关,见 [translation-rules.md](translation-rules.md)。重新记录了 hash 但另一侧翻得潦草的配对能通过门禁;它不得通过评审。\n\n## 范围、排除与推进\n\n**范围**:根 `README.md`,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部内容。包(package)README(`packages/**`)在后续批次加入范围。\n\n**排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`):\n\n- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md` 与 `docs/module-graph.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。\n- `docs/AGENTS.md` 与 `.agents/notes/**/AGENTS.md`:agent 指令,与根 `AGENTS.md` 一样只以英文维护。\n- `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。\n- [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。\n\n**推进**:以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note),只要标注日期等于或晚于 manifest 的 `requiredSince` 分界日期,合并时就必须配齐双语文件。更早日期的文件属于 backlog(待翻清单),包括分界前夜创建的文件。Agent Note 文件名记录首次提出日期,因此倒填日期绕过分界属于评审可见的违规。manifest 中的 `required` 列表是当前执行红线,并非全量覆盖这一最终目标。翻译批次将路径加入 `required`,使门禁只向前收紧。未列入的文档仍可通过 `--list` 查看,而任何已存在的配对都受完整契约约束。后续修改必须同步更新两侧,因此 `required` 的扩展速度不能超过翻译评审的承载能力。\n\n## 分工\n\n这里的对侧文件由运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) 的 agent 生成,再由人评审:在这里推理(inference)很便宜,评审注意力才是稀缺资源。门禁负责检查配对是否完整、记录的 hash、语言切换行以及本文列出的结构签名;翻译质量、术语和签名未涵盖的结构要求仍由评审把关。提示词契约也有可执行实现:[scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) 会把仓库内置的模板(注入术语表;模板自带经人工校准的规则)渲染为英译中或中译英两个方向的提示词,并解析三段式响应;`doc-sync` 中的 `verify-translation-prompt` 会检查两个渲染方向与仓库内示例。\n" + "content": "# 双语文档\n\n[English](README.md) | 中文\n\n本仓库的文档会被公司内外的人和 agent(智能体)阅读,因此 README、Agent Note(agent 决策记录)与 docs 目录树以英文和简体中文双语维护。本页定义配对契约、强制门禁与推进策略;[translation-rules.md](translation-rules.md) 定义如何翻译;[terminology.md](terminology.md) 是术语真源。仓库内置的 agent 工作流见 [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md)。\n\n## 配对契约\n\n- **两种语言同权。** 一篇文档可以先用任一语言撰写和评审(先写中文的 Agent Note 与先写英文的一样正当),另一侧由它翻译而来。两个文件谁也不高于谁;约束它们的是二者必须说同样的话。\n- **一对文档是三个同目录文件。** 英文 `foo.md`、中文 `foo.zh.md`,加一份一致性记录 `foo.i18n.yaml`,都在同一目录。不用语言目录,不用独立翻译仓库,不用中英混排的单文件。配对必须整体合并:PR(Pull Request)永远不会只带一种语言而缺其余两个文件。\n- **一致性记录。**`foo.i18n.yaml` 保存两侧文件在上一次被确认「说同样的话」时各自的完整 git blob hash:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n 用 blob hash 而不是 commit hash,这样同一个 PR 里改动的文件也能算出记录(`git hash-object foo.md`),一致性是纯内容比较。记录的 hash 还能还原任一侧上次确认时的确切文本(`git cat-file -p <hash>`),所以失去同步的配对是「把被改的一侧与其上次确认状态做 diff、再最小化地修补另一侧」,从不整篇重译。两侧对齐后,`pnpm run verify-translation-pairing --write` 重新记录两个 hash;那份 yaml diff 就是「确认一致」这个动作本身,可以被评审。\n- **语言切换行。** 两个文件在各自 H1 标题之后立即互链:英文文件带 `English | [中文](foo.zh.md)`,中文文件带 `[English](foo.md) | 中文`。\n- **结构与另一侧一一对应。** 标题深度与顺序、列表类型、有序列表起始编号、列表项数量、表格行列数、链接目标与逐字节一致的代码块在配对两侧一一对应;完整保持规则见 [translation-rules.md](translation-rules.md)。既有 Markdown 门禁对 `.zh.md` 文件原样生效(`verify-md-wrap`、`verify-md-links`)。\n\n## 门禁:verify-translation-pairing\n\n`pnpm run verify-translation-pairing`(`doc-sync`(文档同步门禁)的一环,贡献者会针对文档变更在本地运行,CI 则会完整运行)机械地强制执行这份契约:\n\n1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件都有完整配对。\n2. 任何已存在的配对(无论是否 required)都完整且一致:三个文件齐全、每一侧的当前 blob hash 等于记录值(改了任一侧而没重新确认配对就变红)、双方都带语言切换行、结构签名按序一致:标题深度、逐字节一致的代码块(信息字符串与内容)、表格行列数、列表类型、有序列表起始编号、列表项数量,以及除切换行之外的每个链接目标。\n3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。\n4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。\n\n`pnpm run verify-translation-pairing --list` 打印范围内每篇文档的当前配对状态(missing、out-of-sync 或 ok),是翻译批次的工作清单。它从不失败;它只报告。\n\n这个门禁带来的实际规则是:**当一个 PR 修改了已配对文档的任一侧时,同一个 PR 更新另一侧并重新记录配对**(运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill(技能),再 `--write`),与本仓库既有的代码与 README 的 doc-sync 规则完全一致。留下失去同步的配对的 PR 会在 CI 变红。\n\n把门禁的边界说白:**门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。** 它检查记录的 hash 与结构签名;它无法判断两侧是否真的在说同样的话,也无法判断措辞是否准确、术语是否得当、行文是否自然;这部分契约由评审者把关,见 [translation-rules.md](translation-rules.md)。重新记录了 hash 但另一侧翻得潦草的配对能通过门禁;它不得通过评审。\n\n## 范围、排除与推进\n\n**范围**:根 `README.md`,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部内容。包(package)README(`packages/**`)在后续批次加入范围。\n\n**排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`):\n\n- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md`、`docs/module-graph.md`、`docs/agent-lifecycle.md`、`docs/capability-seams.md`、`docs/event-producer-consumer.md`、`docs/graph-atlas.md` 与 `docs/tool-execution-pipeline.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。\n- `docs/AGENTS.md` 与 `.agents/notes/**/AGENTS.md`:agent 指令,与根 `AGENTS.md` 一样只以英文维护。\n- `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。\n- [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。\n\n**推进**:以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note),只要标注日期等于或晚于 manifest 的 `requiredSince` 分界日期,合并时就必须配齐双语文件。更早日期的文件属于 backlog(待翻清单),包括分界前夜创建的文件。Agent Note 文件名记录首次提出日期,因此倒填日期绕过分界属于评审可见的违规。manifest 中的 `required` 列表是当前执行红线,并非全量覆盖这一最终目标。翻译批次将路径加入 `required`,使门禁只向前收紧。未列入的文档仍可通过 `--list` 查看,而任何已存在的配对都受完整契约约束。后续修改必须同步更新两侧,因此 `required` 的扩展速度不能超过翻译评审的承载能力。\n\n## 分工\n\n这里的对侧文件由运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) 的 agent 生成,再由人评审:在这里推理(inference)很便宜,评审注意力才是稀缺资源。门禁负责检查配对是否完整、记录的 hash、语言切换行以及本文列出的结构签名;翻译质量、术语和签名未涵盖的结构要求仍由评审把关。提示词契约也有可执行实现:[scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) 会把仓库内置的模板(注入术语表;模板自带经人工校准的规则)渲染为英译中或中译英两个方向的提示词,并解析三段式响应;`doc-sync` 中的 `verify-translation-prompt` 会检查两个渲染方向与仓库内示例。\n" }, { "role": "user", @@ -40,11 +40,11 @@ }, { "role": "user", - "content": "# Agent Note: Bilingual documentation via paired sibling files and a pairing gate\n\nStatus: implemented\n\nEnglish | [中文](2026-07-02-bilingual-docs-and-pairing-gate.zh.md)\n\n## Problem\n\nThis repo's README and docs tree are read by people and agents inside and outside the company, in both English and Chinese. Maintaining a second language by hand, with no mechanism, is how translations rot: one side moves on, the other silently lies, and no gate notices. The repo's standing answer to invariants of this kind is to encode them as a mechanical check (see [quality gates](2026-06-11-quality-gates.md) and [doc-sync enforcement](2026-06-11-doc-sync-enforcement.md)), so the bilingual policy ships with one.\n\n## Decision\n\n- **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md).\n- **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR.\n- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: required pairs exist, every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical), excluded (generated or bilingual-by-construction) files stay unpaired, and date-named documents on or after the manifest's `requiredSince` cutoff have complete pairs. The `required` list in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) is a ratchet: each merged translation batch adds its files, so coverage only grows.\n- **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent.\n\n## Alternatives considered\n\n- **English as the canonical source with a fingerprint inside the translation** — the design first proposed for this Agent Note: `.zh.md` files carried an HTML comment recording the English source's blob hash, and translation flowed EN → ZH only. Revised in review: the team wants Chinese-first authoring (write and review a Chinese Agent Note, then translate to English) with the two languages holding equal authority, which a one-directional canonical model cannot express. The sidecar record covering BOTH sides replaced the in-file one-directional fingerprint; the blob-hash mechanics survived unchanged.\n- **Locale directories (`docs/en/` + `docs/zh/`, the Kubernetes/ECharts model)** — rejected: this repo has no docs-site framework to map locales to routes, moving every English file would churn every existing cross-reference, and `verify-md-links`/`verify-doc-refs` would need path-mapping logic instead of working unchanged.\n- **A separate translation repo (the PingCAP `docs`/`docs-cn` model)** — rejected: right for a docs product with independent release trains, overkill for a monorepo's own documentation; it also puts the translation outside the reach of this repo's gates.\n- **Interleaved bilingual files (single file, both languages)** — rejected: doubles every diff, breaks the one-line-per-paragraph convention's diff ergonomics, and makes partial inconsistency invisible.\n- **Commit-hash records (the MDN `l10n.sourceCommit` model)** — rejected in favor of blob hashes: a same-PR edit has no commit hash yet, so the MDN model cannot express \"consistent as of the state this PR introduces\", and verifying it requires git history instead of file content.\n- **Comparing git timestamps of the pair (no record)** — rejected: formatting-only edits would false-positive, and a counterpart committed after an unrelated edit would false-negative; content identity is the only signal that means what the gate claims.\n\n## Industry precedent\n\nPaired sibling files with locale suffixes are the dominant Chinese big-tech convention (ant-design `index.zh-CN.md`/`index.en-US.md`; arco-design `README.zh-CN.md` with a top-of-file switcher; Apache ShardingSphere's 387 `.cn.md`/`.en.md` pairs) — but none of those repos *enforce* pairing or consistency in CI; the convention holds by review alone. Consistency automation exists outside China: MDN's `l10n.sourceCommit` front-matter fingerprint, Vue's Ryu-Cho action (upstream-commit watcher that opens issues/PRs for stale translations), Kubernetes' localization drift scripts, and Microsoft's Azure co-op-translator (source-hash-driven LLM re-translation in CI). This design combines the two: the Chinese-ecosystem file layout with a hash-pair gate, plus a committed agent skill in place of a bot service.\n\n## Consequences\n\n- Editing either side of a paired document obligates the same PR to update the counterpart and re-record the pair — the gate makes the doc-sync rule bilingual, and CI (not reviewer memory) carries the invariant.\n- Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, \"who confirmed these consistent, and when\" is answerable from git blame on the yaml.\n- When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring.\n- Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list.\n- Rollout is incremental by design: documents outside `required` are visible backlog (`--list`), not red CI, so pairs land in reviewable batches without a big-bang PR. A date-named document dated on or after the manifest's `requiredSince` cutoff merges bilingual or not at all, so new date-named Agent Notes do not enlarge that backlog.\n- The recorded hashes double as the update tool (`git cat-file -p <hash>` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism.\n" + "content": "# Agent Note: Bilingual documentation via paired sibling files and a pairing gate\n\nStatus: implemented\n\nEnglish | [中文](2026-07-02-bilingual-docs-and-pairing-gate.zh.md)\n\n## Problem\n\nThis repo's README and docs tree are read by people and agents inside and outside the company, in both English and Chinese. Maintaining a second language by hand, with no mechanism, is how translations rot: one side moves on, the other silently lies, and no gate notices. The repo's standing answer to invariants of this kind is to encode them as a mechanical check (see [quality gates](2026-06-11-quality-gates.md) and [doc-sync enforcement](2026-06-11-doc-sync-enforcement.md)), so the bilingual policy ships with one.\n\n## Decision\n\n- **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md).\n- **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR.\n- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: required pairs exist, every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical), excluded (generated or bilingual-by-construction) files stay unpaired, and date-named documents on or after the manifest's `requiredSince` cutoff have complete pairs. The `required` list in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) is a ratchet: each merged translation batch adds its files, so coverage only grows.\n- **The enforcement frontier advances in coherent review batches.** A related set enters `required` only when reviewers can evaluate it as a unit. The core frontier groups [architecture](../../../../docs/architecture.md), the [Cordis primer](../../../../docs/cordis-primer.md), [defensive patterns](../../../../docs/defensive-patterns.md), the [glossary](../../../../docs/glossary.md), and [testing](../../../../docs/testing.md) because their terminology, links, and contributor contracts inform one another; admitting only part would leave the enforced corpus internally inconsistent. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it.\n- **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration.\n- **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent.\n\n## Verification\n\nThe verification contract covers each boundary independently. `verify-translation-pairing` pins pair completeness, hashes, switchers, and structure; [`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) pins locale-specific source selection for published pairs; [`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) pins discovery of Loader YAML and exclusion of translation records; and the [translation-prompt runnable snapshot](../../../../scripts/translation-prompt.snapshot.ts) pins the rendered system message, five reviewed example pairs, source request, and consumed response. Together these checks make pair drift, publication drift, configuration misclassification, and model-visible prompt drift review-visible.\n\n## Alternatives considered\n\n- **English as the canonical source with a fingerprint inside the translation** — the design first proposed for this Agent Note: `.zh.md` files carried an HTML comment recording the English source's blob hash, and translation flowed EN → ZH only. Revised in review: the team wants Chinese-first authoring (write and review a Chinese Agent Note, then translate to English) with the two languages holding equal authority, which a one-directional canonical model cannot express. The sidecar record covering BOTH sides replaced the in-file one-directional fingerprint; the blob-hash mechanics survived unchanged.\n- **Locale directories (`docs/en/` + `docs/zh/`, the Kubernetes/ECharts model)** — rejected: this repo has no docs-site framework to map locales to routes, moving every English file would churn every existing cross-reference, and `verify-md-links`/`verify-doc-refs` would need path-mapping logic instead of working unchanged.\n- **A separate translation repo (the PingCAP `docs`/`docs-cn` model)** — rejected: right for a docs product with independent release trains, overkill for a monorepo's own documentation; it also puts the translation outside the reach of this repo's gates.\n- **Interleaved bilingual files (single file, both languages)** — rejected: doubles every diff, breaks the one-line-per-paragraph convention's diff ergonomics, and makes partial inconsistency invisible.\n- **Commit-hash records (the MDN `l10n.sourceCommit` model)** — rejected in favor of blob hashes: a same-PR edit has no commit hash yet, so the MDN model cannot express \"consistent as of the state this PR introduces\", and verifying it requires git history instead of file content.\n- **Comparing git timestamps of the pair (no record)** — rejected: formatting-only edits would false-positive, and a counterpart committed after an unrelated edit would false-negative; content identity is the only signal that means what the gate claims.\n\n## Industry precedent\n\nPaired sibling files with locale suffixes are the dominant Chinese big-tech convention (ant-design `index.zh-CN.md`/`index.en-US.md`; arco-design `README.zh-CN.md` with a top-of-file switcher; Apache ShardingSphere's 387 `.cn.md`/`.en.md` pairs) — but none of those repos *enforce* pairing or consistency in CI; the convention holds by review alone. Consistency automation exists outside China: MDN's `l10n.sourceCommit` front-matter fingerprint, Vue's Ryu-Cho action (upstream-commit watcher that opens issues/PRs for stale translations), Kubernetes' localization drift scripts, and Microsoft's Azure co-op-translator (source-hash-driven LLM re-translation in CI). This design combines the two: the Chinese-ecosystem file layout with a hash-pair gate, plus a committed agent skill in place of a bot service.\n\n## Consequences\n\n- Editing either side of a paired document obligates the same PR to update the counterpart and re-record the pair — the gate makes the doc-sync rule bilingual, and CI (not reviewer memory) carries the invariant.\n- Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, \"who confirmed these consistent, and when\" is answerable from git blame on the yaml.\n- When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring.\n- Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list.\n- Rollout is incremental by design: documents outside `required` are visible backlog (`--list`), not red CI, so pairs land in reviewable batches without a big-bang PR. A date-named document dated on or after the manifest's `requiredSince` cutoff merges bilingual or not at all, so new date-named Agent Notes do not enlarge that backlog.\n- The recorded hashes double as the update tool (`git cat-file -p <hash>` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism.\n" }, { "role": "assistant", - "content": "# Agent Note:通过配对兄弟文件与配对门禁实现双语文档\n\nStatus: implemented\n\n[English](2026-07-02-bilingual-docs-and-pairing-gate.md) | 中文\n\n## 问题\n\n本仓库的 README 与 docs 目录树会被公司内外的人和 agent(智能体)以中英两种语言阅读。在没有机制的情况下纯靠手工维护第二语言,正是译文腐烂的根源:一侧持续演进,另一侧默默失实,而没有门禁会注意到。对于这类不变式,本仓库一贯的做法是将其编码为机械检查(见[质量门禁](2026-06-11-quality-gates.md)与 [doc-sync 强制](2026-06-11-doc-sync-enforcement.md)),因此双语政策随附一道门禁一起交付。\n\n## 决策\n\n- **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。\n- **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。\n- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:required 的配对必须存在;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的文件(生成物或本身即双语的)不得配对;凡文件名以日期开头且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,也必须有完整配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `required` 清单只进不退:每个合并的翻译批次将自己的文件加入其中,覆盖面只增不减。\n- **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。\n\n## 曾考虑的替代方案\n\n- **英文为正典源、指纹放在译文内**:本 Agent Note 最初提出的设计:`.zh.md` 文件携带一条 HTML 注释记录英文源的 blob hash,翻译只沿 EN → ZH 单向流动。评审中修订:团队需要中文先行的撰写方式(先写、先审中文 Agent Note,再译英文),两种语言同权,而单向正典模型无法表达这一点。覆盖**两侧**的伴随记录取代了文件内的单向指纹;blob hash 的机制本身保持不变。\n- **语言目录(`docs/en/` + `docs/zh/`,Kubernetes/ECharts 模式)**:否决。本仓库没有将 locale 映射到路由的文档站框架;如果移动所有英文文件,所有既有交叉引用都要随之修改;且 `verify-md-links`/`verify-doc-refs` 将需要路径映射逻辑,而非原样工作。\n- **独立翻译仓库(PingCAP `docs`/`docs-cn` 模式)**:否决。适合有独立发布节奏的文档产品,对 monorepo 自身的文档而言过重;还会把译文置于本仓库门禁触及不到的地方。\n- **中英混排单文件(一个文件、两种语言)**:否决。每个 diff 都翻倍,破坏一段一行约定的 diff 易读性,且局部不一致不可见。\n- **Commit hash 式记录(MDN `l10n.sourceCommit` 模式)**:否决,改用 blob hash。同一个 PR 内的改动还没有 commit hash,MDN 模式无法表达「与本 PR 引入的状态一致」,且校验它需要 git 历史而非文件内容。\n- **比较配对两侧的 git 时间戳(无记录)**:否决。纯格式化的改动会误报,一次无关改动之后提交的对侧文件会漏报;只有内容同一性这个信号才与门禁的承诺名实相符。\n\n## 业界先例\n\n带语言后缀的配对兄弟文件是中国大厂的主流约定(ant-design 的 `index.zh-CN.md`/`index.en-US.md`;arco-design 的 `README.zh-CN.md` 加顶部切换行;Apache ShardingSphere 的 387 对 `.cn.md`/`.en.md`),但这些仓库都没有在 CI 中**强制**配对或一致性检查;约定纯靠评审维系。一致性自动化存在于中国以外:MDN 的 `l10n.sourceCommit` front-matter 指纹、Vue 的 Ryu-Cho action(监视上游 commit,为陈旧译文自动开 issue/PR)、Kubernetes 的本地化漂移脚本、微软 Azure co-op-translator(CI 中由源 hash 驱动的 LLM 重译)。本设计将两者结合:中文生态的文件布局,加上 hash 配对门禁,再加一个仓库内置的 agent skill 替代 bot 服务。\n\n## 后果\n\n- 修改已配对文档的任一侧,同一个 PR 就有义务更新对侧并重新记录配对。门禁将 doc-sync 规则双语化,不变式由 CI(而非评审者的记忆)承载。\n- 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。\n- 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。\n- 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。\n- 推进天然是渐进的:`required` 之外的文档是可见的 backlog(待翻清单,`--list`),而非红色的 CI;因此配对按可评审的批次落地,无需一个巨型 PR。凡文件名以日期开头且日期不早于 manifest 中 `requiredSince` 分界日期的文档,都必须配齐双语文件,因此新建的日期命名 Agent Note 不会增加这份 backlog。\n- 记录的 hash 兼作更新工具(`git cat-file -p <hash>` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。\n" + "content": "# Agent Note:通过配对兄弟文件与配对门禁实现双语文档\n\nStatus: implemented\n\n[English](2026-07-02-bilingual-docs-and-pairing-gate.md) | 中文\n\n## 问题\n\n本仓库的 README 与 docs 目录树会被公司内外的人和 agent(智能体)以中英两种语言阅读。在没有机制的情况下纯靠手工维护第二语言,正是译文腐烂的根源:一侧持续演进,另一侧默默失实,而没有门禁会注意到。对于这类不变式,本仓库一贯的做法是将其编码为机械检查(见[质量门禁](2026-06-11-quality-gates.md)与 [doc-sync 强制](2026-06-11-doc-sync-enforcement.md)),因此双语政策随附一道门禁一起交付。\n\n## 决策\n\n- **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。\n- **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。\n- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:required 的配对必须存在;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的文件(生成物或本身即双语的)不得配对;凡文件名以日期开头且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,也必须有完整配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `required` 清单只进不退:每个合并的翻译批次将自己的文件加入其中,覆盖面只增不减。\n- **执行红线按连贯的评审批次推进。** 一组相关文档只有在评审者能够将其作为整体评估时,才进入 `required`。核心红线将[架构](../../../../docs/architecture.md)、[Cordis 入门](../../../../docs/cordis-primer.md)、[防御性模式](../../../../docs/defensive-patterns.md)、[术语表](../../../../docs/glossary.md)和[测试](../../../../docs/testing.md)归为一组,因为它们的术语、链接和贡献者契约相互关联;只纳入其中一部分会使受门禁约束的文档集合内部不一致。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。\n- **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。\n- **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。\n\n## 验证\n\n验证契约分别覆盖每个边界。`verify-translation-pairing` 固定配对完整性、hash、切换行和结构;[`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) 固定已发布配对按 locale 选择对应源文件;[`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) 固定 Loader YAML 的发现以及翻译记录的排除;[翻译提示词可运行快照](../../../../scripts/translation-prompt.snapshot.ts)则固定渲染后的系统消息、五对经评审的示例、源请求和响应消费结果。这些检查共同使配对漂移、发布漂移、配置误分类和模型可见提示词漂移都可在评审中看见。\n\n## 曾考虑的替代方案\n\n- **英文为正典源、指纹放在译文内**:本 Agent Note 最初提出的设计:`.zh.md` 文件携带一条 HTML 注释记录英文源的 blob hash,翻译只沿 EN → ZH 单向流动。评审中修订:团队需要中文先行的撰写方式(先写、先审中文 Agent Note,再译英文),两种语言同权,而单向正典模型无法表达这一点。覆盖**两侧**的伴随记录取代了文件内的单向指纹;blob hash 的机制本身保持不变。\n- **语言目录(`docs/en/` + `docs/zh/`,Kubernetes/ECharts 模式)**:否决。本仓库没有将 locale 映射到路由的文档站框架;如果移动所有英文文件,所有既有交叉引用都要随之修改;且 `verify-md-links`/`verify-doc-refs` 将需要路径映射逻辑,而非原样工作。\n- **独立翻译仓库(PingCAP `docs`/`docs-cn` 模式)**:否决。适合有独立发布节奏的文档产品,对 monorepo 自身的文档而言过重;还会把译文置于本仓库门禁触及不到的地方。\n- **中英混排单文件(一个文件、两种语言)**:否决。每个 diff 都翻倍,破坏一段一行约定的 diff 易读性,且局部不一致不可见。\n- **Commit hash 式记录(MDN `l10n.sourceCommit` 模式)**:否决,改用 blob hash。同一个 PR 内的改动还没有 commit hash,MDN 模式无法表达「与本 PR 引入的状态一致」,且校验它需要 git 历史而非文件内容。\n- **比较配对两侧的 git 时间戳(无记录)**:否决。纯格式化的改动会误报,一次无关改动之后提交的对侧文件会漏报;只有内容同一性这个信号才与门禁的承诺名实相符。\n\n## 业界先例\n\n带语言后缀的配对兄弟文件是中国大厂的主流约定(ant-design 的 `index.zh-CN.md`/`index.en-US.md`;arco-design 的 `README.zh-CN.md` 加顶部切换行;Apache ShardingSphere 的 387 对 `.cn.md`/`.en.md`),但这些仓库都没有在 CI 中**强制**配对或一致性检查;约定纯靠评审维系。一致性自动化存在于中国以外:MDN 的 `l10n.sourceCommit` front-matter 指纹、Vue 的 Ryu-Cho action(监视上游 commit,为陈旧译文自动开 issue/PR)、Kubernetes 的本地化漂移脚本、微软 Azure co-op-translator(CI 中由源 hash 驱动的 LLM 重译)。本设计将两者结合:中文生态的文件布局,加上 hash 配对门禁,再加一个仓库内置的 agent skill 替代 bot 服务。\n\n## 后果\n\n- 修改已配对文档的任一侧,同一个 PR 就有义务更新对侧并重新记录配对。门禁将 doc-sync 规则双语化,不变式由 CI(而非评审者的记忆)承载。\n- 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。\n- 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。\n- 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。\n- 推进天然是渐进的:`required` 之外的文档是可见的 backlog(待翻清单,`--list`),而非红色的 CI;因此配对按可评审的批次落地,无需一个巨型 PR。凡文件名以日期开头且日期不早于 manifest 中 `requiredSince` 分界日期的文档,都必须配齐双语文件,因此新建的日期命名 Agent Note 不会增加这份 backlog。\n- 记录的 hash 兼作更新工具(`git cat-file -p <hash>` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。\n" }, { "role": "user", diff --git a/scripts/translation-pairing.manifest.json b/scripts/translation-pairing.manifest.json index a4fcc93352..4e08844dc9 100644 --- a/scripts/translation-pairing.manifest.json +++ b/scripts/translation-pairing.manifest.json @@ -1,24 +1,201 @@ { "requiredSince": "2026-07-14", "required": [ + ".agents/notes/README.md", + ".agents/notes/implemented/architecture/2026-06-11-content-block-vocabulary.md", + ".agents/notes/implemented/architecture/2026-06-11-custom-schema-dsl.md", + ".agents/notes/implemented/architecture/2026-06-11-dev-invariants-over-deep-readonly.md", + ".agents/notes/implemented/architecture/2026-06-11-event-sourced-sessions.md", + ".agents/notes/implemented/architecture/2026-06-11-microkernel-event-taxonomy.md", + ".agents/notes/implemented/architecture/2026-06-11-runtime-arg-validation.md", + ".agents/notes/implemented/architecture/2026-06-11-structured-error-taxonomy.md", + ".agents/notes/implemented/architecture/2026-06-11-tool-schemas-in-prompt-assembly.md", + ".agents/notes/implemented/architecture/2026-06-13-capability-seams.md", + ".agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.md", + ".agents/notes/implemented/architecture/2026-06-14-session-persistence.md", + ".agents/notes/implemented/architecture/2026-06-15-turn-enclosure-invariant.md", + ".agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.md", + ".agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md", + ".agents/notes/implemented/architecture/2026-06-18-session-surface.md", + ".agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md", + ".agents/notes/implemented/architecture/2026-06-20-branded-ids.md", + ".agents/notes/implemented/architecture/2026-06-20-extract-example-app-packages.md", + ".agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md", + ".agents/notes/implemented/architecture/2026-06-20-package-hierarchy.md", + ".agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md", + ".agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md", + ".agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.md", + ".agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md", + ".agents/notes/implemented/architecture/2026-06-30-event-domain-semantics.md", + ".agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md", + ".agents/notes/implemented/architecture/2026-07-02-result-time-applied-hunk-diffs.md", + ".agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md", + ".agents/notes/implemented/architecture/2026-07-03-filesystem-directory-listing-seam.md", + ".agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md", + ".agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md", + ".agents/notes/implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.md", + ".agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md", + ".agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md", + ".agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.md", ".agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md", + ".agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md", ".agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md", ".agents/notes/implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md", ".agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md", ".agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.md", ".agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md", + ".agents/notes/implemented/feature/2026-06-14-acp-agent-client-protocol.md", + ".agents/notes/implemented/feature/2026-06-14-acp-multi-session.md", + ".agents/notes/implemented/feature/2026-06-15-code-mode.md", + ".agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.md", + ".agents/notes/implemented/feature/2026-06-18-acp-terminal-and-tool-rendering.md", + ".agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md", + ".agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md", + ".agents/notes/implemented/feature/2026-06-22-acp-subagent-backend.md", + ".agents/notes/implemented/feature/2026-06-25-ask-user-question.md", + ".agents/notes/implemented/feature/2026-06-29-todo-write-tool.md", + ".agents/notes/implemented/feature/2026-06-30-hook-bridges.md", + ".agents/notes/implemented/feature/2026-06-30-hook-protocol-lib.md", + ".agents/notes/implemented/feature/2026-06-30-interception-seams.md", + ".agents/notes/implemented/feature/2026-06-30-session-store-fork-api.md", + ".agents/notes/implemented/feature/2026-06-30-subagent-observe-enrich.md", + ".agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md", + ".agents/notes/implemented/feature/2026-07-05-skill-system.md", + ".agents/notes/implemented/feature/2026-07-06-approval-seam.md", + ".agents/notes/implemented/feature/2026-07-06-explicit-tool-order.md", + ".agents/notes/implemented/feature/2026-07-06-sandbox.md", + ".agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.md", + ".agents/notes/implemented/feature/2026-07-07-session-prefix.md", + ".agents/notes/implemented/feature/2026-07-08-repeat-tool-guard.md", + ".agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md", + ".agents/notes/implemented/feature/2026-07-10-session-query-service.md", + ".agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md", + ".agents/notes/implemented/process/2026-06-11-doc-sync-enforcement.md", + ".agents/notes/implemented/process/2026-06-11-quality-gates.md", + ".agents/notes/implemented/process/2026-06-11-tsdown-over-dumble.md", + ".agents/notes/implemented/process/2026-06-11-vendor-cordis-as-source.md", + ".agents/notes/implemented/process/2026-06-16-pnpm-over-yarn.md", + ".agents/notes/implemented/process/2026-06-17-ts-build-config.md", + ".agents/notes/implemented/process/2026-06-18-markdown-cross-link-lint.md", + ".agents/notes/implemented/process/2026-06-20-agent-note-classification.md", + ".agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.md", + ".agents/notes/implemented/process/2026-06-20-generated-cordis-catalog.md", ".agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md", + ".agents/notes/implemented/process/2026-07-02-tool-schema-catalog.md", + ".agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.md", + ".agents/notes/implemented/process/2026-07-04-cordis-jsdoc-completeness-gate.md", + ".agents/notes/implemented/process/2026-07-04-doc-tiers-and-budgets.md", + ".agents/notes/implemented/process/2026-07-04-persistence-log-catalog.md", + ".agents/notes/implemented/process/2026-07-05-uniform-agent-note-format.md", + ".agents/notes/implemented/process/2026-07-06-export-surface-jsdoc-gate.md", + ".agents/notes/implemented/process/2026-07-06-generated-config-catalog.md", + ".agents/notes/implemented/process/2026-07-06-node-engine-floor.md", + ".agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.md", + ".agents/notes/implemented/process/2026-07-06-parallel-pre-push-gates.md", + ".agents/notes/implemented/process/2026-07-10-readme-known-limitations-gate.md", + ".agents/notes/implemented/process/2026-07-12-package-model-experience-contract.md", ".agents/notes/implemented/process/2026-07-19-web-styling-system.md", + ".agents/notes/implemented/simplification/2026-06-19-drop-mutable-session-summary.md", + ".agents/notes/implemented/simplification/2026-06-20-collapse-trace-only-session-events.md", + ".agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-adapter-change-event.md", + ".agents/notes/implemented/simplification/2026-06-20-drop-unconsumed-llm-assembled-surfaces.md", + ".agents/notes/implemented/simplification/2026-06-20-prune-dead-seam-methods.md", + ".agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.md", + ".agents/notes/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.md", + ".agents/notes/implemented/simplification/2026-06-20-unify-agent-and-session-id.md", + ".agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.md", + ".agents/notes/implemented/simplification/2026-07-02-remove-stream-chunk-mirror.md", + ".agents/notes/implemented/simplification/2026-07-04-drop-image-content-block.md", + ".agents/notes/implemented/simplification/2026-07-04-drop-inert-request-knobs.md", + ".agents/notes/implemented/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md", + ".agents/notes/implemented/simplification/2026-07-04-fold-stdio-ui-helper.md", + ".agents/notes/implemented/simplification/2026-07-04-prune-producerless-vocabulary-variants.md", + ".agents/notes/implemented/simplification/2026-07-04-prune-write-only-fs-surface.md", + ".agents/notes/implemented/simplification/2026-07-04-remove-agent-steering-mirror.md", + ".agents/notes/implemented/simplification/2026-07-04-share-app-bin-boot-glue.md", + ".agents/notes/implemented/simplification/2026-07-04-tighten-hook-protocol-contract.md", + ".agents/notes/implemented/simplification/2026-07-04-trim-acp-bridge-unreachable-surface.md", + ".agents/notes/implemented/simplification/2026-07-12-drop-unconsumed-skill-provider-events.md", + ".agents/notes/implemented/simplification/2026-07-12-prune-unused-web-seam-fields.md", + ".agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md", + ".agents/notes/implemented/testing/2026-06-11-property-based-testing.md", + ".agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md", + ".agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md", + ".agents/notes/implemented/testing/2026-06-20-remove-redundant-snapshot-log-expected-output.md", + ".agents/notes/implemented/testing/2026-06-22-fork-child-replay-seed-boundary.md", + ".agents/notes/implemented/testing/2026-06-22-fork-snapshot-scenarios.md", + ".agents/notes/implemented/testing/2026-06-22-subagent-snapshot-replay.md", + ".agents/notes/implemented/testing/2026-07-04-hook-snapshot-matrix.md", + ".agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.md", + ".agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md", + ".agents/notes/implemented/testing/2026-07-08-shared-acp-snapshot-package.md", + ".agents/notes/proposed/architecture/2026-06-16-typed-event-schemas.md", + ".agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.md", + ".agents/notes/proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.md", + ".agents/notes/proposed/feature/2026-07-08-interactive-side-sessions.md", + ".agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.md", + ".agents/notes/rejected/feature/2026-07-13-stream-workflow-progress-through-tool-calls.md", + ".agents/notes/proposed/process/2026-06-11-api-extractor-reports.md", + ".agents/notes/proposed/process/2026-06-11-architectural-conformance.md", + ".agents/notes/proposed/process/2026-06-11-supply-chain-and-vendor-drift.md", + ".agents/notes/proposed/process/2026-06-20-discover-package-inventory.md", + ".agents/notes/proposed/simplification/2026-07-04-prune-dead-core-spine-surface.md", + ".agents/notes/proposed/testing/2026-06-11-deterministic-and-stress-testing.md", + ".agents/notes/proposed/testing/2026-06-11-mutation-testing.md", + ".agents/notes/rejected/architecture/2026-06-11-immutable-public-surfaces.md", + ".agents/notes/rejected/architecture/2026-06-20-providerless-example-base.md", + ".agents/notes/rejected/process/2026-07-04-generate-agent-note-index-tables.md", + ".agents/notes/rejected/simplification/2026-06-20-assembled-assistant-messages-only.md", + ".agents/notes/rejected/simplification/2026-06-20-drop-acp-session-load.md", + ".agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.md", + ".agents/notes/rejected/simplification/2026-06-20-drop-bash-output-spill-files.md", + ".agents/notes/rejected/simplification/2026-06-20-drop-durable-step-boundaries.md", + ".agents/notes/rejected/simplification/2026-06-20-drop-unused-session-lineage.md", + ".agents/notes/rejected/simplification/2026-06-20-fold-session-persistence-interface.md", + ".agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.md", + ".agents/notes/rejected/simplification/2026-06-20-retire-mid-turn-steering.md", + ".agents/notes/rejected/simplification/2026-06-20-single-session-acp-bridge.md", + ".agents/notes/rejected/simplification/2026-06-20-truncate-interrupted-turns.md", + ".agents/notes/rejected/simplification/2026-07-04-prune-unimplemented-subagent-vocabulary.md", + ".agents/notes/rejected/simplification/2026-07-12-collapse-workflow-to-foreground-core.md", + ".agents/notes/rejected/simplification/2026-07-12-prune-unused-skill-registry-surface.md", "README.md", + "docs/architecture.md", "docs/cookbook/adding-a-package.md", "docs/cookbook/adding-a-tool.md", "docs/cookbook/adding-a-vendored-package.md", "docs/cookbook/adding-an-llm-adapter.md", "docs/cookbook/extension-cookbook.md", "docs/cookbook/responding-to-pr-review-on-a-stack.md", + "docs/cordis-primer.md", + "docs/core-data-structures/approval.md", + "docs/core-data-structures/bash.md", + "docs/core-data-structures/code-runtime.md", + "docs/core-data-structures/compaction.md", + "docs/core-data-structures/core.md", + "docs/core-data-structures/filesystem.md", + "docs/core-data-structures/llm-streaming.md", + "docs/core-data-structures/persistence.md", + "docs/core-data-structures/sandbox.md", + "docs/core-data-structures/scope.md", + "docs/core-data-structures/session-query.md", + "docs/core-data-structures/session.md", + "docs/core-data-structures/skills.md", + "docs/core-data-structures/subagent.md", + "docs/core-data-structures/system-prompt.md", + "docs/core-data-structures/tools.md", + "docs/core-data-structures/user-interaction.md", + "docs/core-data-structures/web.md", + "docs/core-data-structures/workflow.md", + "docs/defensive-patterns.md", "docs/development.md", + "docs/glossary.md", "docs/i18n/README.md", "docs/i18n/translation-rules.md", + "docs/postmortem/0001-acp-default-export-drops-inject.md", + "docs/postmortem/0002-js-expression-disabled-filesystem-tools.md", + "docs/postmortem/README.md", + "docs/testing.md", "docs/user/develop/basic/config.md", "docs/user/develop/basic/index.md", "docs/user/develop/basic/tool.md", @@ -39,14 +216,19 @@ ".agents/notes/AGENTS.md", ".agents/notes/implemented/AGENTS.md", "docs/AGENTS.md", + "docs/agent-lifecycle.md", + "docs/capability-seams.md", "docs/config-catalog.md", "docs/cordis-catalog/", + "docs/event-producer-consumer.md", + "docs/graph-atlas.md", "docs/i18n/style-samples.md", "docs/i18n/terminology.md", "docs/i18n/translation-prompt.md", "docs/module-graph.md", "docs/persistence-catalog.md", "docs/tool-catalog.md", + "docs/tool-execution-pipeline.md", "python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/" ] } diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 14fb0969e4..0310306bfa 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -474,26 +474,6 @@ "symbol": "SessionEventTraceObservation", "source": "packages/session-query/session-query/src/types.ts" }, - { - "doc": "docs/core-data-structures/session-reference.md", - "symbol": "SessionReferenceInput", - "source": "packages/context/session-reference/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-reference.md", - "symbol": "SessionReferenceCandidate", - "source": "packages/context/session-reference/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-reference.md", - "symbol": "PreparedReferencedMessage", - "source": "packages/context/session-reference/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-reference.md", - "symbol": "SessionReferenceErrorCode", - "source": "packages/context/session-reference/src/config.ts" - }, { "doc": "docs/core-data-structures/session-title.md", "symbol": "SessionTitleProviderId", @@ -549,6 +529,26 @@ "symbol": "SessionTitleProvider", "source": "packages/session-title/session-title/src/index.ts" }, + { + "doc": "docs/core-data-structures/session-reference.md", + "symbol": "SessionReferenceInput", + "source": "packages/context/session-reference/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-reference.md", + "symbol": "SessionReferenceCandidate", + "source": "packages/context/session-reference/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-reference.md", + "symbol": "PreparedReferencedMessage", + "source": "packages/context/session-reference/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-reference.md", + "symbol": "SessionReferenceErrorCode", + "source": "packages/context/session-reference/src/config.ts" + }, { "doc": "docs/core-data-structures/tools.md", "symbol": "ToolOutputDefinition", @@ -1248,6 +1248,949 @@ "doc": "docs/core-data-structures/session-query.md", "symbol": "SessionSearchHit", "source": "packages/session-query/session-query/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": "SendOptions", + "source": "packages/core/agent/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": "ResolvedAgentInput", + "source": "packages/core/agent/src/types.ts" + }, + { + "doc": "docs/core-data-structures/core.zh.md", + "symbol": "AgentMessageId", + "source": "packages/core/agent/src/types.ts" + }, + { + "doc": "docs/core-data-structures/core.zh.md", + "symbol": "AgentMessage", + "source": "packages/core/agent/src/types.ts" + }, + { + "doc": "docs/core-data-structures/core.zh.md", + "symbol": "CancelOptions", + "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": "PromptMessageData", + "source": "packages/core/session/src/types.ts" + }, + { + "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/persistence.zh.md", + "symbol": "SessionPersistenceRevision", + "source": "packages/session-persistence/session-persistence/src/revision.ts" + }, + { + "doc": "docs/core-data-structures/persistence.zh.md", + "symbol": "SessionPersistenceSnapshot", + "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": "SessionLogSnapshot", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionSurfaceSnapshot", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionTitleObservation", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionTitleObservationResult", + "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": "SessionResultFilter", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionEventResultFilter", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionEventSearchDocument", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionSearchCursor", + "source": "packages/session-query/session-query/src/cursor.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionSearchRequest", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionEventSearchRequest", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionSearchPage", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionEventSearchPage", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionEventSearchHit", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/session-query.zh.md", + "symbol": "SessionSearchHit", + "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/session-query.zh.md", + "symbol": "SessionEventTraceObservation", + "source": "packages/session-query/session-query/src/types.ts" + }, + { + "doc": "docs/core-data-structures/tools.zh.md", + "symbol": "ToolOutputDefinition", + "source": "packages/core/tools/src/index.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": "ValueSchemaSpec", + "source": "packages/core/tools/src/schema.ts" + }, + { + "doc": "docs/core-data-structures/tools.zh.md", + "symbol": "ParameterPropertySpec", + "source": "packages/core/tools/src/schema.ts" + }, + { + "doc": "docs/core-data-structures/tools.zh.md", + "symbol": "ParameterSchemaSpec", + "source": "packages/core/tools/src/schema.ts" + }, + { + "doc": "docs/core-data-structures/tools.zh.md", + "symbol": "InferValue", + "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": "ToolFailure", + "source": "packages/core/tools/src/index.ts" + }, + { + "doc": "docs/core-data-structures/tools.zh.md", + "symbol": "ToolExecutionSuccess", + "source": "packages/core/tools/src/index.ts" + }, + { + "doc": "docs/core-data-structures/tools.zh.md", + "symbol": "ToolExecutionFailure", + "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": "JsonSchemaScalar", + "source": "packages/core/tools/src/json-schema.ts" + }, + { + "doc": "docs/core-data-structures/tools.zh.md", + "symbol": "JsonSchemaType", + "source": "packages/core/tools/src/json-schema.ts" + }, + { + "doc": "docs/core-data-structures/tools.zh.md", + "symbol": "JsonSchemaNode", + "source": "packages/core/tools/src/json-schema.ts" + }, + { + "doc": "docs/core-data-structures/tools.zh.md", + "symbol": "ObjectJsonSchema", + "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": "CodeJsonValue", + "source": "packages/code-runtime/code-runtime/src/types.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": "CodeBindingErrorClass", + "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" } ] } diff --git a/scripts/verify-cordis-config.ts b/scripts/verify-cordis-config.ts index 916db4a168..6041be78ed 100644 --- a/scripts/verify-cordis-config.ts +++ b/scripts/verify-cordis-config.ts @@ -12,6 +12,7 @@ import { globSync, readFileSync } from 'node:fs' import { dirname, relative, resolve } from 'node:path' import * as yaml from 'js-yaml' import ts from 'typescript' +import { cordisConfigFiles } from './cordis-config-files.ts' interface JsExpr { __jsExpr: string @@ -39,10 +40,7 @@ const jsExprType = new yaml.Type('tag:yaml.org,2002:js', { }) const schema = yaml.JSON_SCHEMA.extend(jsExprType) -const files = globSync(['**/*cordis*.yml', '**/*cordis*.yaml'], { - cwd: root, - exclude: ['.claude/**', 'node_modules/**', 'vendor/**'], -}).sort() +const files = cordisConfigFiles(root) const errors: string[] = [] const examplePluginReferences: PluginReference[] = [] diff --git a/tsconfig.base.json b/tsconfig.base.json index 56ab3ffef3..a593094372 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -74,6 +74,9 @@ "./packages/hooks/*/src/invariant.ts", "./packages/session-persistence/*/src/invariant.ts", "./packages/session-query/*/src/invariant.ts", + "./packages/acp/*/src/invariant.ts", + "./packages/storage/*/src/invariant.ts", + "./packages/workspace/*/src/invariant.ts", "./packages/sdk/*/src/invariant.ts", "./packages/ui/*/src/invariant.ts", "./packages/examples/*/src/invariant.ts", @@ -142,6 +145,9 @@ "./packages/session-persistence/*/src", "./packages/session-query/*/src", "./packages/session-title/*/src", + "./packages/acp/*/src", + "./packages/storage/*/src", + "./packages/workspace/*/src", "./packages/sdk/*/src", "./packages/ui/*/src", "./packages/examples/*/src", diff --git a/tsconfig.host.json b/tsconfig.host.json index b67bfb222d..3691878a37 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -45,6 +45,11 @@ { "path": "./packages/session-query/session-query" }, { "path": "./packages/session-query/session-query-sqlite" }, { "path": "./packages/session-query/tool-session-query" }, + { "path": "./packages/storage/storage" }, + { "path": "./packages/storage/storage-json" }, + { "path": "./packages/storage/storage-sqlite" }, + { "path": "./packages/storage/storage-domain" }, + { "path": "./packages/workspace/workspace" }, { "path": "./packages/session-title/session-title" }, { "path": "./packages/session-title/session-title-llm" }, { "path": "./packages/session-title/session-title-first-message-llm" }, @@ -106,7 +111,7 @@ { "path": "./packages/timeout/timeout-policy" }, { "path": "./packages/support/invariants" }, { "path": "./packages/support/agent-loop-testkit" }, - { "path": "./packages/ui/acp" }, + { "path": "./packages/acp/acp" }, { "path": "./packages/examples/acp-demo" }, { "path": "./packages/ui/app-boot" }, { "path": "./packages/ui/jsonrpc" }, diff --git a/vitest.config.ts b/vitest.config.ts index 4040439035..7dfeeb55d6 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -11,6 +11,7 @@ const windowsUnsupportedPackages = process.platform === 'win32' ? [ 'packages/bash/*', 'packages/hooks/*', + 'packages/pty/pty-local', 'packages/sandbox/sandbox-local', 'packages/sdk/create-sdk', 'packages/sdk/helper', @@ -59,7 +60,10 @@ export default defineConfig({ plugins: [pathsPlugin()], test: { name: 'thread-safe', - pool: 'threads', + // Node 24 has aborted in its CJS lexer from a macOS arm64 worker + // thread. A fork contains that external runtime failure to the test + // process; other hosts retain the lower-overhead thread pool. + pool: process.platform === 'darwin' ? 'forks' : 'threads', setupFiles: ['./scripts/test-invariants.ts'], include: testIncludes, exclude: [ @@ -104,8 +108,21 @@ export default defineConfig({ 'packages/client/ui-layout/src/*', 'packages/client/web/src/*', 'packages/host/webserver/src/*', - 'packages/client/modules/src/loader.ts', + 'packages/client/modules/src/client/system.ts', 'packages/client/hmr/src/client/index.ts', + // Web config-tree boot round: the new host-side web-transport halves + // whose remaining branches need real-composition/process harnesses. + // TODO(gui): cover and remove with the client test lane above. + 'packages/client/modules/src/index.ts', + 'packages/client/modules/src/invariant.ts', + 'packages/client/modules/src/client/index.ts', + 'packages/client/modules/src/client/manifest.ts', + 'packages/client/hmr/src/index.ts', + 'packages/client/hmr/src/invariant.ts', + 'packages/client/connection/src/index.ts', + 'packages/client/connection/src/http-bridge.ts', + 'packages/host/apiproxy/src/index.ts', + 'packages/host/apiproxy/src/invariant.ts', ...windowsUnsupportedPackages.map(path => `${path}/src/**/*.ts`), ...windowsCoverageExclusions, ], diff --git a/website/docs.ts b/website/docs.ts index ee7ad64061..1888cd908c 100644 --- a/website/docs.ts +++ b/website/docs.ts @@ -226,14 +226,53 @@ const cordisTutorial = mirroredPages(([ ...(file === 'index.md' ? { sourceAliases: ['docs/cordis-tutorial'] } : {}), }))) +const cordisPrimerReference = pairedPages([ + { + source: 'docs/cordis-primer.md', + route: 'reference/cordis-primer.md', + label: { root: 'Cordis 入门', en: 'Cordis primer' }, + sidebar: { root: 'zh-reference', en: 'en-reference' }, + section: { root: '概念', en: 'Concepts' }, + order: 1, + }, +]) + +const coreDataReference = pairedPages(([ + ['core.md', '核心数据结构', 'Core data structures', 0], + ['scope.md', '作用域', 'Scopes', 1], + ['session.md', '会话', 'Sessions', 2], + ['system-prompt.md', '系统提示词', 'System prompts', 4], + ['tools.md', '工具', 'Tools', 5], + ['llm-streaming.md', 'LLM 流式响应', 'LLM streaming', 6], + ['bash.md', 'Bash 执行', 'Bash execution', 7], + ['filesystem.md', '文件系统', 'Filesystem', 9], + ['code-runtime.md', '代码运行时', 'Code runtime', 10], + ['compaction.md', '上下文压缩', 'Compaction', 11], + ['subagent.md', '子代理', 'Subagents', 12], + ['workflow.md', '工作流', 'Workflows', 13], + ['skills.md', '技能', 'Skills', 14], + ['approval.md', '审批', 'Approvals', 15], + ['user-interaction.md', '用户交互', 'User interaction', 16], + ['sandbox.md', '沙箱', 'Sandboxing', 18], + ['web.md', 'Web 访问', 'Web access', 19], + ['persistence.md', '会话持久化', 'Session persistence', 20], +] as const).map(([file, rootLabel, enLabel, order]): PairedPage => ({ + source: `docs/core-data-structures/${file}`, + route: `reference/core-data-structures/${file}`, + label: { root: rootLabel, en: enLabel }, + sidebar: { root: 'zh-reference', en: 'en-reference' }, + section: { root: '数据结构', en: 'Data structures' }, + order, + ...(file === 'core.md' ? { sourceAliases: ['docs/core-data-structures'] } : {}), +}))) + const reference = mirroredPages([ ...([ - ['docs/architecture.md', 'reference/index.md', '架构', 'Architecture'], - ['docs/cordis-primer.md', 'reference/cordis-primer.md', 'Cordis 入门', 'Cordis primer'], - ['docs/capability-seams.md', 'reference/capability-seams.md', '能力服务', 'Capability services'], - ['docs/agent-lifecycle.md', 'reference/agent-lifecycle.md', 'Agent 生命周期', 'Agent lifecycle'], - ['docs/tool-execution-pipeline.md', 'reference/tool-execution-pipeline.md', 'Tool 执行', 'Tool execution'], - ] as const).map(([source, route, rootLabel, enLabel], order): MirroredPage => ({ + ['docs/architecture.md', 'reference/index.md', '架构', 'Architecture', 0], + ['docs/capability-seams.md', 'reference/capability-seams.md', '能力服务', 'Capability services', 2], + ['docs/agent-lifecycle.md', 'reference/agent-lifecycle.md', 'Agent 生命周期', 'Agent lifecycle', 3], + ['docs/tool-execution-pipeline.md', 'reference/tool-execution-pipeline.md', 'Tool 执行', 'Tool execution', 4], + ] as const).map(([source, route, rootLabel, enLabel, order]): MirroredPage => ({ source, route, contentLocale: 'en-US', @@ -273,28 +312,10 @@ const reference = mirroredPages([ order, })), ...([ - ['core.md', '核心数据结构', 'Core data structures'], - ['scope.md', '作用域', 'Scopes'], - ['session.md', '会话', 'Sessions'], - ['goal.md', '目标', 'Goals'], - ['system-prompt.md', '系统提示词', 'System prompts'], - ['tools.md', '工具', 'Tools'], - ['llm-streaming.md', 'LLM 流式响应', 'LLM streaming'], - ['bash.md', 'Bash 执行', 'Bash execution'], - ['pty.md', 'PTY 会话', 'PTY sessions'], - ['filesystem.md', '文件系统', 'Filesystem'], - ['code-runtime.md', '代码运行时', 'Code runtime'], - ['compaction.md', '上下文压缩', 'Compaction'], - ['subagent.md', '子代理', 'Subagents'], - ['workflow.md', '工作流', 'Workflows'], - ['skills.md', '技能', 'Skills'], - ['approval.md', '审批', 'Approvals'], - ['user-interaction.md', '用户交互', 'User interaction'], - ['commands.md', '命令', 'Human commands'], - ['sandbox.md', '沙箱', 'Sandboxing'], - ['web.md', 'Web 访问', 'Web access'], - ['persistence.md', '会话持久化', 'Session persistence'], - ] as const).map(([file, rootLabel, enLabel], order): MirroredPage => ({ + ['goal.md', '目标', 'Goals', 3], + ['pty.md', 'PTY 会话', 'PTY sessions', 8], + ['commands.md', '命令', 'Human commands', 17], + ] as const).map(([file, rootLabel, enLabel, order]): MirroredPage => ({ source: `docs/core-data-structures/${file}`, route: `reference/core-data-structures/${file}`, contentLocale: 'en-US', @@ -302,7 +323,6 @@ const reference = mirroredPages([ sidebar: { root: 'zh-reference', en: 'en-reference' }, section: { root: '数据结构', en: 'Data structures' }, order, - ...(file === 'core.md' ? { sourceAliases: ['docs/core-data-structures'] } : {}), })), ...([ ['adding-a-package.md', '新增 Package', 'Adding a package'], @@ -325,5 +345,7 @@ export const docsPages: DocsPage[] = [ ...homeAndGuide, ...develop, ...cordisTutorial, + ...cordisPrimerReference, + ...coreDataReference, ...reference, ]